gflights 0.1.0

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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
use crate::{
    parsers::{self, common::FixedFlights},
    protos::{self, urls::Location as LocationProto},
};
use chrono::{Months, NaiveDate};
use parsers::common::{
    AirlineFilter, FlightTimes, Location, PlaceType, SortOrder, StopOptions, StopoverDuration,
    TotalDuration, TravelClass, Travelers,
};
use protos::urls::{ItineraryUrl, Leg};

mod builder;
mod currency;

pub use builder::ConfigBuilder;
pub use currency::Currency;

/// The `TripType` enum is used to specify the type of trip.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum TripType {
    #[default]
    OneWay,
    Return,
    MultiCity,
}

/// The `Config` struct is used to specify the options for a flight search.
///
/// `departure` and `destination` each hold 1–4 airports.  When multiple
/// airports are supplied Google Flights treats them as "any of these" for
/// that end of the journey (e.g. all London-area airports as the origin).
#[derive(Debug, Clone)]
pub struct Config {
    pub departing_date: NaiveDate,
    /// One to four departure airports / city identifiers.
    pub departure: Vec<Location>,
    /// One to four destination airports / city identifiers.
    pub destination: Vec<Location>,
    pub stop_options: StopOptions,
    pub travel_class: TravelClass,
    pub return_date: Option<NaiveDate>,
    pub travellers: Travelers,
    pub departing_times: FlightTimes,
    pub return_times: FlightTimes,
    pub stopover_max: StopoverDuration,
    /// Minimum layover / connection time (default: no minimum).
    pub stopover_min: StopoverDuration,
    pub duration_max: TotalDuration,
    pub trip_type: TripType,
    pub currency: Currency,
    pub fixed_flights: FixedFlights,
    /// BCP-47 language subtag for the Google Flights UI, e.g. `"en"`, `"fr"`.
    pub language: String,
    /// ISO 3166-1 alpha-2 country code for locale, e.g. `"GB"`, `"FR"`.
    pub country: String,
    /// Sort order applied to the search results.
    pub sort_order: SortOrder,
    /// Airlines / alliances to include (position \[4\] of the per-leg array).
    /// Empty = no restriction.
    pub airlines_include: Vec<AirlineFilter>,
    /// Airlines / alliances to exclude (position \[5\] of the per-leg array).
    /// Empty = no restriction.
    pub airlines_exclude: Vec<AirlineFilter>,
    /// Require a connection through these IATA airport codes (position \[9\]).
    /// Empty = no restriction.
    pub connecting_airports: Vec<String>,
    /// If `true`, restrict results to lower-COâ‚‚ emissions flights (position \[13\]).
    pub lower_emissions: bool,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            departing_date: NaiveDate::default(),
            departure: Vec::new(),
            destination: Vec::new(),
            stop_options: StopOptions::default(),
            travel_class: TravelClass::default(),
            return_date: None,
            travellers: Travelers::default(),
            departing_times: FlightTimes::default(),
            return_times: FlightTimes::default(),
            stopover_max: StopoverDuration::default(),
            stopover_min: StopoverDuration::default(),
            duration_max: TotalDuration::default(),
            trip_type: TripType::default(),
            currency: Currency::default(),
            fixed_flights: FixedFlights::default(),
            language: "en".to_string(),
            country: "GB".to_string(),
            sort_order: SortOrder::default(),
            airlines_include: Vec::new(),
            airlines_exclude: Vec::new(),
            connecting_airports: Vec::new(),
            lower_emissions: false,
        }
    }
}

impl Config {
    /// Creates a new `Config` object with the specified options.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        departing_date: NaiveDate,
        departure: Vec<Location>,
        destination: Vec<Location>,
        stop_options: StopOptions,
        travel_class: TravelClass,
        return_date: Option<NaiveDate>,
        travellers: Travelers,
        departing_times: FlightTimes,
        return_times: FlightTimes,
        stopover_max: StopoverDuration,
        duration_max: TotalDuration,
        currency: Option<Currency>,
    ) -> Self {
        let trip_type = match return_date {
            Some(_) => TripType::Return,
            None => TripType::OneWay,
        };
        // MultiCity is unreachable here: trip_type is derived solely from
        // return_date above (Some → Return, None → OneWay), so MultiCity can
        // never be produced by this function.
        let fixed_flights = match trip_type {
            TripType::Return => FixedFlights::new(2),
            TripType::OneWay => FixedFlights::new(1),
            TripType::MultiCity => unreachable!(
                "Config::new() never produces TripType::MultiCity; \
                 use a dedicated multi-city builder when that feature is implemented"
            ),
        };
        Self {
            departing_date,
            departure,
            destination,
            stop_options,
            travel_class,
            return_date,
            travellers,
            departing_times,
            return_times,
            stopover_max,
            stopover_min: StopoverDuration::default(),
            duration_max,
            trip_type,
            currency: currency.unwrap_or_default(),
            fixed_flights,
            language: "en".to_string(),
            country: "GB".to_string(),
            sort_order: SortOrder::default(),
            airlines_include: Vec::new(),
            airlines_exclude: Vec::new(),
            connecting_airports: Vec::new(),
            lower_emissions: false,
        }
    }

    /// Calculates the number of days between the departing and return dates, if this is a return trip.
    pub fn get_diff_days(&self) -> Option<i64> {
        self.return_date
            .map(|x| x.signed_duration_since(self.departing_date).num_days())
    }

    /// Calculates the end date of the graph given the number of months to add to the departing date.
    ///
    /// Returns `None` if the resulting date would overflow `NaiveDate`'s range
    /// (only reachable for dates within a few years of the maximum representable date).
    pub fn get_end_graph(&self, months: Months) -> Option<NaiveDate> {
        self.departing_date.checked_add_months(months)
    }

    /// Returns the Google flight URL for this flight search.
    pub fn to_flight_url(&self) -> String {
        ItineraryUrl::from(self).to_flight_url()
    }

    /// Returns the encoded string relative to this flight search.
    pub fn to_encoded(&self) -> String {
        ItineraryUrl::from(self).to_encoded()
    }

    pub fn builder() -> ConfigBuilder {
        ConfigBuilder::default()
    }
}

/// Conversion to Leg Protobuf, used for creating the URL.
impl From<&Config> for Vec<Leg> {
    fn from(options: &Config) -> Vec<Leg> {
        let stops = match options.stop_options {
            StopOptions::All => None,
            variant => Some(variant as i32 - 1),
        };
        let max_stopover_minutes = options.stopover_max.to_option();
        let max_duration_minutes = options.duration_max.to_option();

        let departure: Vec<LocationProto> =
            options.departure.iter().map(LocationProto::from).collect();
        let destination: Vec<LocationProto> = options
            .destination
            .iter()
            .map(LocationProto::from)
            .collect();

        let first_leg = Leg {
            date: options.departing_date.to_string(),
            departure: departure.clone(),
            arrival: destination.clone(),
            min_hour_departure: options.departing_times.get_departure_hour_min(),
            max_hour_departure: options.departing_times.get_departure_hour_max(),
            min_hour_arrival: options.departing_times.get_arrival_hour_min(),
            max_hour_arrival: options.departing_times.get_arrival_hour_max(),
            stops,
            max_stopover_minutes,
            max_duration_minutes,
        };

        let mut leg_vector: Vec<Leg> = Vec::new();
        leg_vector.push(first_leg);

        match options.trip_type {
            TripType::OneWay => {} //already done
            TripType::Return => {
                let second_leg = Leg {
                    date: options
                        .return_date
                        .expect("return_date is always Some when TripType is Return")
                        .to_string(),
                    departure: destination.clone(),
                    arrival: departure.clone(),
                    min_hour_departure: options.return_times.get_departure_hour_min(),
                    max_hour_departure: options.return_times.get_departure_hour_max(),
                    min_hour_arrival: options.return_times.get_arrival_hour_min(),
                    max_hour_arrival: options.return_times.get_arrival_hour_max(),
                    stops,
                    max_stopover_minutes,
                    max_duration_minutes,
                };
                leg_vector.push(second_leg);
            }
            TripType::MultiCity => unreachable!(
                "MultiCity Config cannot be created via Config::new() or Config::builder(); \
                 construct Config directly only for OneWay or Return trips"
            ),
        }

        leg_vector
    }
}

/// Converts a [`Location`] to the protobuf [`LocationProto`] used in URL encoding.
///
/// Airports use type `1`; cities, regions, and unspecified types use type `2`,
/// which matches how Google Flights encodes region searches.
impl From<&Location> for LocationProto {
    fn from(location: &Location) -> Self {
        let loc_type = match location.loc_type {
            PlaceType::Airport => 1,
            _ => 2,
        };
        LocationProto {
            r#type: loc_type,
            place_name: location.loc_identifier.clone(),
        }
    }
}

/// Conversion from Config to ItineraryUrl, used for creating the URL.
impl From<&Config> for ItineraryUrl {
    fn from(options: &Config) -> Self {
        let trip_type = match options.trip_type {
            TripType::Return => 1,
            TripType::OneWay => 2,
            TripType::MultiCity => unreachable!(
                "MultiCity Config cannot be created via Config::new() or Config::builder(); \
                 construct Config directly only for OneWay or Return trips"
            ),
        };

        let class = options.travel_class as i32;

        let travellers = options.travellers.to_proto_vec();

        let legs: Vec<Leg> = options.into();
        Self {
            legs,
            travellers,
            class,
            trip_type,
        }
    }
}

#[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)
    }

    #[test]
    fn it_works_airports_oneway() {
        let departure = Location {
            loc_identifier: "MXP".to_string(),
            loc_type: PlaceType::Airport,
            location_name: None,
        };
        let destination = Location {
            loc_identifier: "CDG".to_string(),
            loc_type: PlaceType::Airport,
            location_name: None,
        };

        let config = Config {
            departing_date: NaiveDate::parse_from_str("2024-05-01", "%Y-%m-%d").unwrap(),
            departure: vec![departure],
            destination: vec![destination],
            return_date: Some(NaiveDate::parse_from_str("2024-05-03", "%Y-%m-%d").unwrap()),
            trip_type: TripType::OneWay,
            ..Default::default()
        };

        let it_url = ItineraryUrl::from(&config);

        let expected = "Gh4SCjIwMjQtMDUtMDFqBwgBEgNNWFByBwgBEgNDREdCAQFIAZgBAg";
        assert_eq!(it_url.to_encoded(), expected);
    }

    #[test]
    fn it_works_cities() {
        let departure = Location {
            loc_identifier: "/m/02_286".to_string(),
            loc_type: PlaceType::City,
            location_name: None,
        };
        let destination = Location {
            loc_identifier: "/m/04jpl".to_string(),
            loc_type: PlaceType::City,
            location_name: None,
        };

        let config = Config {
            departing_date: NaiveDate::parse_from_str("2024-05-01", "%Y-%m-%d").unwrap(),
            departure: vec![departure],
            destination: vec![destination],
            return_date: Some(NaiveDate::parse_from_str("2024-05-03", "%Y-%m-%d").unwrap()),
            trip_type: TripType::Return,
            ..Default::default()
        };

        let it_url = ItineraryUrl::from(&config);

        let expected = "GikSCjIwMjQtMDUtMDFqDQgCEgkvbS8wMl8yODZyDAgCEggvbS8wNGpwbBopEgoyMDI0LTA1LTAzagwIAhIIL20vMDRqcGxyDQgCEgkvbS8wMl8yODZCAQFIAZgBAQ";
        assert_eq!(it_url.to_encoded(), expected);
    }

    #[test]
    fn it_works_cities_many() {
        let departure = Location {
            loc_identifier: "/m/02_286".to_string(),
            loc_type: PlaceType::City,
            location_name: None,
        };
        let destination = Location {
            loc_identifier: "/m/04jpl".to_string(),
            loc_type: PlaceType::City,
            location_name: None,
        };

        let config = Config {
            departing_date: NaiveDate::parse_from_str("2024-05-01", "%Y-%m-%d").unwrap(),
            departure: vec![departure],
            destination: vec![destination],
            return_date: Some(NaiveDate::parse_from_str("2024-05-03", "%Y-%m-%d").unwrap()),
            trip_type: TripType::Return,
            travellers: parsers::common::Travelers::new(vec![4, 1, 1, 1])
                .expect("valid traveler counts"),
            ..Default::default()
        };
        let it_url = ItineraryUrl::from(&config);

        let expected = "GikSCjIwMjQtMDUtMDFqDQgCEgkvbS8wMl8yODZyDAgCEggvbS8wNGpwbBopEgoyMDI0LTA1LTAzagwIAhIIL20vMDRqcGxyDQgCEgkvbS8wMl8yODZCBwEBAQECAwRIAZgBAQ";
        assert_eq!(it_url.to_encoded(), expected);
    }

    #[test]
    fn test_location_to_location_proto_airport() {
        let location = Location {
            loc_type: PlaceType::Airport,
            loc_identifier: "JFK".to_string(),
            location_name: None,
        };
        let location_proto = LocationProto::from(&location);
        assert_eq!(location_proto.r#type, 1);
        assert_eq!(location_proto.place_name, "JFK");
    }

    #[test]
    fn test_location_to_location_proto_city() {
        let location = Location {
            loc_type: PlaceType::City,
            loc_identifier: "/m/04jpl".to_string(),
            location_name: None,
        };
        let location_proto = LocationProto::from(&location);
        assert_eq!(location_proto.r#type, 2);
        assert_eq!(location_proto.place_name, "/m/04jpl");
    }

    // -----------------------------------------------------------------------
    // Multi-airport unit tests
    // -----------------------------------------------------------------------

    #[test]
    fn builder_accumulates_airports_up_to_four() {
        let lhr = Location {
            loc_identifier: "LHR".to_owned(),
            loc_type: PlaceType::Airport,
            location_name: None,
        };
        let lgw = Location {
            loc_identifier: "LGW".to_owned(),
            loc_type: PlaceType::Airport,
            location_name: None,
        };
        let stn = Location {
            loc_identifier: "STN".to_owned(),
            loc_type: PlaceType::Airport,
            location_name: None,
        };
        let ltn = Location {
            loc_identifier: "LTN".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 config = Config {
            departing_date: future_date(30),
            departure: vec![lhr, lgw, stn, ltn],
            destination: vec![jfk],
            trip_type: TripType::OneWay,
            ..Default::default()
        };
        assert_eq!(config.departure.len(), 4);
        assert_eq!(config.destination.len(), 1);
    }

    #[test]
    fn multi_departure_produces_two_proto_entries() {
        let config = Config {
            departing_date: future_date(30),
            departure: vec![
                Location {
                    loc_identifier: "LHR".to_owned(),
                    loc_type: PlaceType::Airport,
                    location_name: None,
                },
                Location {
                    loc_identifier: "LGW".to_owned(),
                    loc_type: PlaceType::Airport,
                    location_name: None,
                },
            ],
            destination: vec![Location {
                loc_identifier: "JFK".to_owned(),
                loc_type: PlaceType::Airport,
                location_name: None,
            }],
            trip_type: TripType::OneWay,
            ..Default::default()
        };
        let legs: Vec<protos::urls::Leg> = (&config).into();
        assert_eq!(legs.len(), 1);
        assert_eq!(
            legs[0].departure.len(),
            2,
            "both LHR and LGW should appear as separate proto entries"
        );
        let codes: Vec<&str> = legs[0]
            .departure
            .iter()
            .map(|l| l.place_name.as_str())
            .collect();
        assert!(codes.contains(&"LHR"));
        assert!(codes.contains(&"LGW"));
    }

    #[test]
    fn multi_airport_return_trip_swaps_legs() {
        let config = Config {
            departing_date: future_date(30),
            departure: vec![
                Location {
                    loc_identifier: "LHR".to_owned(),
                    loc_type: PlaceType::Airport,
                    location_name: None,
                },
                Location {
                    loc_identifier: "LGW".to_owned(),
                    loc_type: PlaceType::Airport,
                    location_name: None,
                },
            ],
            destination: vec![Location {
                loc_identifier: "JFK".to_owned(),
                loc_type: PlaceType::Airport,
                location_name: None,
            }],
            return_date: Some(future_date(37)),
            trip_type: TripType::Return,
            ..Default::default()
        };
        let legs: Vec<protos::urls::Leg> = (&config).into();
        assert_eq!(legs.len(), 2);
        assert_eq!(legs[0].departure.len(), 2);
        assert_eq!(legs[0].arrival.len(), 1);
        assert_eq!(legs[0].arrival[0].place_name, "JFK");
        assert_eq!(legs[1].departure.len(), 1);
        assert_eq!(legs[1].departure[0].place_name, "JFK");
        assert_eq!(legs[1].arrival.len(), 2);
    }

    // -----------------------------------------------------------------------
    // Config::new()
    // -----------------------------------------------------------------------

    #[test]
    fn config_new_oneway_sets_correct_trip_type() {
        let dep = Location {
            loc_identifier: "LHR".to_owned(),
            loc_type: PlaceType::Airport,
            location_name: None,
        };
        let dst = Location {
            loc_identifier: "JFK".to_owned(),
            loc_type: PlaceType::Airport,
            location_name: None,
        };
        let date = future_date(30);
        let travelers = crate::parsers::common::Travelers::new(vec![1, 0, 0, 0]).unwrap();
        let cfg = Config::new(
            date,
            vec![dep],
            vec![dst],
            StopOptions::default(),
            TravelClass::default(),
            None, // one-way
            travelers,
            FlightTimes::default(),
            FlightTimes::default(),
            StopoverDuration::default(),
            TotalDuration::default(),
            None,
        );
        assert!(matches!(cfg.trip_type, TripType::OneWay));
        assert!(cfg.return_date.is_none());
    }

    #[test]
    fn config_new_return_sets_correct_trip_type() {
        let dep = Location {
            loc_identifier: "MXP".to_owned(),
            loc_type: PlaceType::Airport,
            location_name: None,
        };
        let dst = Location {
            loc_identifier: "CDG".to_owned(),
            loc_type: PlaceType::Airport,
            location_name: None,
        };
        let date = future_date(30);
        let ret = future_date(37);
        let travelers = crate::parsers::common::Travelers::new(vec![2, 0, 0, 0]).unwrap();
        let cfg = Config::new(
            date,
            vec![dep],
            vec![dst],
            StopOptions::default(),
            TravelClass::default(),
            Some(ret),
            travelers,
            FlightTimes::default(),
            FlightTimes::default(),
            StopoverDuration::default(),
            TotalDuration::default(),
            Some(Currency::Euro),
        );
        assert!(matches!(cfg.trip_type, TripType::Return));
        assert_eq!(cfg.get_diff_days(), Some(7));
    }

    #[test]
    fn config_get_end_graph_adds_months() {
        use chrono::{Datelike, Months};
        let cfg = Config {
            departing_date: chrono::NaiveDate::from_ymd_opt(2026, 1, 15).unwrap(),
            ..Default::default()
        };
        let end = cfg.get_end_graph(Months::new(3)).unwrap();
        assert_eq!(end.month(), 4);
        assert_eq!(end.year(), 2026);
    }
}