gflights 0.3.1

Unofficial async Rust client for the Google Flights web API — search flights, price graphs, and booking offers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
use anyhow::{anyhow, Result};
use chrono::NaiveDate;

use crate::parsers::common::{
    AirlineFilter, FixedFlights, FlightTimes, Location, PlaceType, SortOrder, StopOptions,
    StopoverDuration, TotalDuration, TravelClass, Travelers,
};
use crate::requests::api::ApiClient;

use super::{Config, TripType};

/// Maximum number of airports Google Flights accepts per origin/destination side.
/// Exceeding this makes the API silently return zero results, so the builder
/// rejects the overflow up front.
const MAX_AIRPORTS_PER_SIDE: usize = 7;

/// Builder for [`Config`].  Obtain one via [`Config::builder()`].
#[derive(Default)]
pub struct ConfigBuilder {
    pub(super) departing_date: Option<NaiveDate>,
    pub(super) departure: Vec<Location>,
    pub(super) destination: Vec<Location>,
    pub(super) stop_options: StopOptions,
    pub(super) travel_class: TravelClass,
    pub(super) return_date: Option<NaiveDate>,
    pub(super) travelers: Travelers,
    pub(super) departing_times: FlightTimes,
    pub(super) return_times: FlightTimes,
    pub(super) stopover_max: StopoverDuration,
    /// Minimum layover duration. Default: no minimum.
    pub(super) stopover_min: StopoverDuration,
    pub(super) duration_max: TotalDuration,
    /// Sort order for search results. Default: [`SortOrder::Best`].
    pub(super) sort_order: SortOrder,
    /// Airlines / alliances to include. Empty = no restriction.
    pub(super) airlines_include: Vec<AirlineFilter>,
    /// Airlines / alliances to exclude. Empty = no restriction.
    pub(super) airlines_exclude: Vec<AirlineFilter>,
    /// Connecting airport IATA codes. Empty = no restriction.
    pub(super) connecting_airports: Vec<String>,
    /// Restrict to lower-COâ‚‚ emissions flights. Default: `false`.
    pub(super) lower_emissions: bool,
    /// Maximum price filter. `None` = no price cap.
    pub(super) max_price: Option<i32>,
    /// Baggage filter `(carry_on_count, checked_count)`. `None` = no restriction.
    pub(super) baggage: Option<(u8, u8)>,
}

impl ConfigBuilder {
    pub fn departing_date(mut self, date: NaiveDate) -> Self {
        self.departing_date = Some(date);
        self
    }

    /// Set the departure to a single airport/city from a string, clearing any previously
    /// added departure airports.  Resolves IATA codes and city names via the network.
    pub async fn departure(mut self, location: &str, client: &ApiClient) -> Result<Self> {
        let loc = get_location(location, client).await?;
        self.departure = vec![loc];
        Ok(self)
    }

    /// Set the departure to a single [`Location`] directly, without a network lookup.
    ///
    /// Use this when you already have a `Location` (e.g. from a previous city lookup or
    /// when building tests without an [`ApiClient`]).
    pub fn departure_location(mut self, location: Location) -> Self {
        self.departure = vec![location];
        self
    }

    /// Add an additional departure airport/city (up to 7 total).
    /// Google Flights will search "any of these airports" as the origin.
    pub async fn add_departure(mut self, location: &str, client: &ApiClient) -> Result<Self> {
        ensure_airport_capacity(self.departure.len(), "departure")?;
        let loc = get_location(location, client).await?;
        self.departure.push(loc);
        Ok(self)
    }

    /// Set the destination to a single airport/city from a string, clearing any previously
    /// added destination airports.  Resolves IATA codes and city names via the network.
    pub async fn destination(mut self, location: &str, client: &ApiClient) -> Result<Self> {
        let loc = get_location(location, client).await?;
        self.destination = vec![loc];
        Ok(self)
    }

    /// Set the destination to a single [`Location`] directly, without a network lookup.
    ///
    /// Use this when you already have a `Location` (e.g. from a previous city lookup or
    /// when building tests without an [`ApiClient`]).
    pub fn destination_location(mut self, location: Location) -> Self {
        self.destination = vec![location];
        self
    }

    /// Add an additional destination airport/city (up to 7 total).
    /// Google Flights will search "any of these airports" as the destination.
    pub async fn add_destination(mut self, location: &str, client: &ApiClient) -> Result<Self> {
        ensure_airport_capacity(self.destination.len(), "destination")?;
        let loc = get_location(location, client).await?;
        self.destination.push(loc);
        Ok(self)
    }

    pub fn return_date(mut self, date: NaiveDate) -> Self {
        self.return_date = Some(date);
        self
    }

    pub fn travelers(mut self, travelers: Travelers) -> Self {
        self.travelers = travelers;
        self
    }

    pub fn stop_options(mut self, stop_options: StopOptions) -> Self {
        self.stop_options = stop_options;
        self
    }

    pub fn travel_class(mut self, travel_class: TravelClass) -> Self {
        self.travel_class = travel_class;
        self
    }

    pub fn departing_times(mut self, times: FlightTimes) -> Self {
        self.departing_times = times;
        self
    }

    pub fn return_times(mut self, times: FlightTimes) -> Self {
        self.return_times = times;
        self
    }

    pub fn stopover_max(mut self, duration: StopoverDuration) -> Self {
        self.stopover_max = duration;
        self
    }

    /// Set the minimum layover / connection duration.
    ///
    /// Use this to avoid very short layovers.  Google Flights lets you choose
    /// minimum layover times in 30-minute intervals.
    pub fn stopover_min(mut self, duration: StopoverDuration) -> Self {
        self.stopover_min = duration;
        self
    }

    pub fn duration_max(mut self, duration: TotalDuration) -> Self {
        self.duration_max = duration;
        self
    }

    /// Set the sort order for flight search results.
    ///
    /// Defaults to [`SortOrder::Best`] (Google's composite ranking).
    pub fn sort_order(mut self, sort_order: SortOrder) -> Self {
        self.sort_order = sort_order;
        self
    }

    /// Replace the entire airlines-include list.
    ///
    /// Accepts IATA codes (`"LX"`, `"LH"`) and alliance names
    /// (`"ONEWORLD"`, `"SKYTEAM"`, `"STAR_ALLIANCE"`).
    pub fn airlines_include(mut self, filters: Vec<AirlineFilter>) -> Self {
        self.airlines_include = filters;
        self
    }

    /// Add a single airline/alliance to the include filter.
    pub fn add_airline_include(mut self, filter: AirlineFilter) -> Self {
        self.airlines_include.push(filter);
        self
    }

    /// Replace the entire airlines-exclude list.
    pub fn airlines_exclude(mut self, filters: Vec<AirlineFilter>) -> Self {
        self.airlines_exclude = filters;
        self
    }

    /// Add a single airline/alliance to the exclude filter.
    pub fn add_airline_exclude(mut self, filter: AirlineFilter) -> Self {
        self.airlines_exclude.push(filter);
        self
    }

    /// Set the list of connecting airports (IATA codes, e.g. `"CDG"`).
    ///
    /// Only itineraries that connect through at least one of these airports
    /// will be returned.
    pub fn connecting_airports(mut self, airports: Vec<String>) -> Self {
        self.connecting_airports = airports;
        self
    }

    /// Add a single connecting airport (IATA code).
    pub fn add_connecting_airport(mut self, airport: impl Into<String>) -> Self {
        self.connecting_airports.push(airport.into());
        self
    }

    /// If `true`, restrict results to flights with lower COâ‚‚ emissions.
    ///
    /// Defaults to `false` (no restriction).
    pub fn lower_emissions(mut self, lower: bool) -> Self {
        self.lower_emissions = lower;
        self
    }

    /// Set a maximum price cap (in the search currency).
    ///
    /// Defaults to `None` (no cap).
    pub fn max_price(mut self, price: i32) -> Self {
        self.max_price = Some(price);
        self
    }

    /// Set the baggage filter `(carry_on_count, checked_count)`.
    ///
    /// Defaults to `None` (no restriction).
    pub fn baggage(mut self, carry_on: u8, checked: u8) -> Self {
        self.baggage = Some((carry_on, checked));
        self
    }

    pub fn build(self) -> Result<Config> {
        let departing_date = self
            .departing_date
            .ok_or(anyhow!("Departing date is required"))?;
        let trip_type = match self.return_date {
            Some(_) => TripType::Return,
            None => TripType::OneWay,
        };
        if self.departure.is_empty() {
            return Err(anyhow!("At least one departure airport is required"));
        }
        if self.destination.is_empty() {
            return Err(anyhow!("At least one destination airport is required"));
        }
        Ok(Config {
            departing_date,
            departure: self.departure,
            destination: self.destination,
            stop_options: self.stop_options,
            travel_class: self.travel_class,
            return_date: self.return_date,
            travellers: self.travelers,
            departing_times: self.departing_times,
            return_times: self.return_times,
            stopover_max: self.stopover_max,
            stopover_min: self.stopover_min,
            duration_max: self.duration_max,
            trip_type,
            fixed_flights: match trip_type {
                TripType::Return => FixedFlights::new(2),
                TripType::OneWay => FixedFlights::new(1),
                TripType::MultiCity => {
                    return Err(anyhow!("Multi-city trips are not yet implemented"));
                }
            },
            sort_order: self.sort_order,
            airlines_include: self.airlines_include,
            airlines_exclude: self.airlines_exclude,
            connecting_airports: self.connecting_airports,
            lower_emissions: self.lower_emissions,
            max_price: self.max_price,
            baggage: self.baggage,
        })
    }
}

pub(super) async fn get_location_pub(
    location: &str,
    client: &ApiClient,
) -> Result<Location, anyhow::Error> {
    get_location(location, client).await
}

async fn get_location(location: &str, client: &ApiClient) -> Result<Location, anyhow::Error> {
    let departure = if location.len() == 3 && location.chars().all(char::is_uppercase) {
        if location.starts_with('X') {
            eprintln!(
                "Warning: '{}' looks like a rail station code. \
                 If you meant a city, use the full name (e.g. 'Rome').",
                location
            );
        }
        Location {
            loc_identifier: location.to_owned(),
            loc_type: PlaceType::Airport,
            location_name: Some(location.to_string()),
        }
    } else {
        client.request_city(location).await?.to_city_list()
    };
    Ok(departure)
}

/// Returns an error if a side already holds [`MAX_AIRPORTS_PER_SIDE`] airports,
/// i.e. adding one more would exceed what Google Flights accepts.
fn ensure_airport_capacity(current: usize, side: &str) -> Result<()> {
    if current >= MAX_AIRPORTS_PER_SIDE {
        return Err(anyhow!(
            "A maximum of {MAX_AIRPORTS_PER_SIDE} {side} airports is supported"
        ));
    }
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use chrono::{Duration, Utc};

    fn future_date(days: i64) -> NaiveDate {
        Utc::now().date_naive() + Duration::days(days)
    }

    /// The capacity guard allows up to seven airports and rejects the eighth,
    /// with a message naming the side. Exercises the exact check used by
    /// `add_departure`/`add_destination` without a network round-trip.
    #[test]
    fn airport_capacity_allows_seven_rejects_eighth() {
        for occupied in 0..MAX_AIRPORTS_PER_SIDE {
            assert!(
                ensure_airport_capacity(occupied, "departure").is_ok(),
                "{occupied} occupied airports should still allow another"
            );
        }
        let err = ensure_airport_capacity(MAX_AIRPORTS_PER_SIDE, "destination")
            .unwrap_err()
            .to_string();
        assert!(err.contains("maximum of 7"), "got: {err}");
        assert!(err.contains("destination"), "got: {err}");
    }

    /// `build()` returns an error when no departure airport was set.
    #[test]
    fn build_fails_without_departure() {
        let result = Config::builder().departing_date(future_date(30)).build();
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("departure"), "error should mention departure");
    }

    /// `build()` returns an error when departure is set but destination is not.
    #[test]
    fn build_fails_without_destination() {
        let lhr = Location {
            loc_identifier: "LHR".to_owned(),
            loc_type: PlaceType::Airport,
            location_name: None,
        };
        let result = Config::builder()
            .departing_date(future_date(30))
            .departure_location(lhr)
            .build();
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("destination"),
            "error should mention destination, got: {msg}"
        );
    }

    /// `build()` returns an error when neither departure nor destination is set.
    #[test]
    fn build_fails_without_both_airports() {
        let result = Config::builder().departing_date(future_date(30)).build();
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("departure") || msg.contains("destination"),
            "error should mention a missing airport, got: {msg}"
        );
    }

    /// ConfigBuilder::sort_order() propagates the chosen sort order.
    #[test]
    fn builder_sort_order_setter_propagates() {
        let lhr = Location {
            loc_identifier: "LHR".to_owned(),
            loc_type: PlaceType::Airport,
            location_name: None,
        };
        let jfk = Location {
            loc_identifier: "JFK".to_owned(),
            loc_type: PlaceType::Airport,
            location_name: None,
        };
        let cfg = Config::builder()
            .departing_date(future_date(30))
            .departure_location(lhr)
            .destination_location(jfk)
            .sort_order(SortOrder::Price)
            .build()
            .expect("valid config");
        assert!(matches!(cfg.sort_order, SortOrder::Price));
    }

    /// All ConfigBuilder filter setters propagate to the built Config.
    #[test]
    fn builder_filter_setters_propagate() {
        use crate::parsers::common::{AirlineCode, AirlineFilter, Alliance};
        let lhr = Location {
            loc_identifier: "LHR".to_owned(),
            loc_type: PlaceType::Airport,
            location_name: None,
        };
        let jfk = Location {
            loc_identifier: "JFK".to_owned(),
            loc_type: PlaceType::Airport,
            location_name: None,
        };
        let cfg = Config::builder()
            .departing_date(future_date(30))
            .departure_location(lhr)
            .destination_location(jfk)
            .add_airline_include(AirlineFilter::Airline(AirlineCode::new("LX").unwrap()))
            .add_airline_include(AirlineFilter::Alliance(Alliance::OneWorld))
            .add_airline_exclude(AirlineFilter::Airline(AirlineCode::new("FR").unwrap()))
            .add_connecting_airport("CDG")
            .lower_emissions(true)
            .stopover_min(StopoverDuration::Minutes(60))
            .stopover_max(StopoverDuration::Minutes(180))
            .build()
            .expect("valid config");

        assert_eq!(cfg.airlines_include.len(), 2);
        assert_eq!(cfg.airlines_exclude.len(), 1);
        assert_eq!(cfg.connecting_airports, vec!["CDG"]);
        assert!(cfg.lower_emissions);
        assert!(matches!(cfg.stopover_min, StopoverDuration::Minutes(60)));
        assert!(matches!(cfg.stopover_max, StopoverDuration::Minutes(180)));
    }

    /// `departure_location` accepts an X-prefixed code (e.g. a rail station code)
    /// without error — the warning is printed to stderr but the Location is created
    /// and the Config builds successfully.  The warning path is exercised via the
    /// async `departure()` helper in live tests; here we verify the code path that
    /// already has a `Location` does not reject X-prefix codes.
    #[test]
    fn x_prefixed_location_builds_without_error() {
        let xrj = Location {
            loc_identifier: "XRJ".to_owned(),
            loc_type: PlaceType::Airport,
            location_name: Some("XRJ".to_owned()),
        };
        let xvq = Location {
            loc_identifier: "XVQ".to_owned(),
            loc_type: PlaceType::Airport,
            location_name: Some("XVQ".to_owned()),
        };
        let cfg = Config::builder()
            .departing_date(future_date(30))
            .departure_location(xrj)
            .destination_location(xvq)
            .build()
            .expect("X-prefixed location codes must not be rejected by Config::build");
        assert_eq!(cfg.departure[0].loc_identifier, "XRJ");
        assert_eq!(cfg.destination[0].loc_identifier, "XVQ");
    }
}