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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
//! This module exposes an SDK for interacting with the [Dark Sky
//! API](https://darksky.net/dev/docs/).

#![doc(html_root_url = "https://jgrillo.github.io/forecast-rs/")]

#![cfg_attr(feature = "serde_derive", feature(rustc_macro))]

#[cfg(feature = "serde_derive")]
#[macro_use]
extern crate serde_derive;

extern crate serde;
extern crate serde_json;

extern crate itertools;

extern crate hyper;

#[cfg(feature = "serde_derive")]
include!("serde_types.in.rs");

#[cfg(feature = "serde_codegen")]
include!(concat!(env!("OUT_DIR"), "/serde_types.rs"));

use std::vec::Vec;
use std::option::Option;

use itertools::join;

use hyper::Url;
use hyper::error::{Result as ApiResult, ParseError};
use hyper::client::{Client, Response, IntoUrl};

// constants

static FORECAST_URL: &'static str = "https://api.darksky.net/forecast";
static EXCLUDE: &'static str = "exclude";
static EXTEND: &'static str = "extend";
static LANG: &'static str = "lang";
static UNITS: &'static str = "units";

// api objects and their builders

/// The ApiClient is a thin wrapper around a `hyper::Client` which sends
/// requests to the Forecast and Time Machine APIs.
#[derive(Debug)]
pub struct ApiClient<'a> {
    client: &'a Client
}

impl<'a> ApiClient<'a> {
    /// Construct a new ApiClient.
    pub fn new(client: &'a Client) -> ApiClient<'a> {
        ApiClient {
            client: client
        }
    }

    /// Send a [Forecast API](https://darksky.net/dev/docs/forecast) request,
    /// returns the corresponding Response.
    ///
    /// # Errors
    ///
    /// This function is a thin wrapper around `hyper::Client.get(..)`, so it
    /// will return an error under the same conditions in which hyper would.
    pub fn get_forecast(self, request: ForecastRequest) -> ApiResult<Response> {
        self.client.get(request).send()
    }

    /// Send a [Time Machine API](https://darksky.net/dev/docs/time-machine)
    /// request, returns the corresponding Response.
    ///
    /// # Errors
    ///
    /// This function is a thin wrapper around `hyper::Client.get(..)`, so it
    /// will return an error under the same conditions in which hyper would.
    pub fn get_time_machine(self, request: TimeMachineRequest) -> ApiResult<Response> {
        self.client.get(request).send()
    }
}

// request model objects and their builders

/// Model object representing a request to the Forecast API.
#[derive(PartialEq, Debug)]
pub struct ForecastRequest<'a> {
    api_key: &'a str,
    latitude: f64,
    longitude: f64,
    url: Url,
    exclude: Vec<ExcludeBlock>,
    extend: Option<ExtendBy>,
    lang: Option<Lang>,
    units: Option<Units>
}

impl<'a> ForecastRequest<'a> {
    pub fn new(
        api_key: &'a str,
        latitude: f64,
        longitude: f64,
        url: Url,
        exclude: Vec<ExcludeBlock>,
        extend: Option<ExtendBy>,
        lang: Option<Lang>,
        units: Option<Units>
    ) -> ForecastRequest<'a> {
        ForecastRequest {
            api_key: api_key,
            latitude: latitude,
            longitude: longitude,
            url: url,
            exclude: exclude,
            extend: extend,
            lang: lang,
            units: units
        }
    }
}

impl<'a> IntoUrl for ForecastRequest<'a> {
    fn into_url(self) -> Result<Url, ParseError> {
        Result::Ok(self.url)
    }
} 

/// Builder object used to construct a ForecastRequest.
#[derive(PartialEq, Debug)]
pub struct ForecastRequestBuilder<'a> {
    api_key: &'a str,
    latitude: f64,
    longitude: f64,
    exclude: Vec<ExcludeBlock>,
    extend: Option<ExtendBy>,
    lang: Option<Lang>,
    units: Option<Units>
}

impl<'a> ForecastRequestBuilder<'a> {

    /// A Forecast API request is constructed with required params `api_key`,
    /// `latitude`, and `longitude`.
    pub fn new(api_key: &'a str, latitude: f64, longitude: f64) -> ForecastRequestBuilder {
        ForecastRequestBuilder {
            api_key: api_key,
            latitude: latitude,
            longitude: longitude,
            exclude: Vec::new(),
            extend: None,
            lang: None,
            units: None
        }
    }

    /// Add a DataBlock to exclude from the response.
    pub fn exclude_block(mut self, exclude_block: ExcludeBlock) -> ForecastRequestBuilder<'a> {
        self.exclude.push(exclude_block);
        self
    }

    /// Add multiple DataBlocks to exclude from the response.
    pub fn exclude_blocks(
        mut self, exclude_blocks: &mut Vec<ExcludeBlock>
    ) -> ForecastRequestBuilder<'a> {
        self.exclude.append(exclude_blocks);
        self
    }

    /// Extend the time window of the response data from 48 hours to 168 hours.
    pub fn extend(mut self, extend: ExtendBy) -> ForecastRequestBuilder<'a> {
        self.extend = Some(extend);
        self
    }

    /// Set the language for messages in the response data.
    pub fn lang(mut self, lang: Lang) -> ForecastRequestBuilder<'a> {
        self.lang = Some(lang);
        self
    }

    /// Set the measurement units for response data.
    pub fn units(mut self, units: Units) -> ForecastRequestBuilder<'a> {
        self.units = Some(units);
        self
    }

    /// Finalize the request.
    pub fn build(self) -> ForecastRequest<'a> {
        ForecastRequest::new(
            self.api_key,
            self.latitude,
            self.longitude,
            self.build_url(),
            self.exclude,
            self.extend,
            self.lang,
            self.units
        )
    }

    fn build_url(&self) -> Url {
        let url_string = format!(
            "{base}/{key}/{lat:.16},{long:.16}", 
            base=FORECAST_URL,
            key=&self.api_key,
            lat=&self.latitude,
            long=&self.longitude
        );
        
        let mut url = Url::parse(&url_string).unwrap();

        {
            let mut query_pairs = url.query_pairs_mut();

            if !&self.exclude.is_empty() {
                let excludes = join(
                    &self.exclude
                        .iter()
                        .map(|e| {
                            let json = serde_json::to_string(e).unwrap();
                            json.trim_matches('"').to_string()
                        })
                        .collect::<Vec<String>>(),
                    ","
                );

                query_pairs.append_pair(EXCLUDE, &excludes);
            }

            if let &Some(ref extend) = &self.extend {
                query_pairs.append_pair(
                    EXTEND, 
                    serde_json::to_string(&extend).unwrap().trim_matches('"')
                );
            }

            if let &Some(ref lang) = &self.lang {
                query_pairs.append_pair(
                    LANG, 
                    serde_json::to_string(&lang).unwrap().trim_matches('"')
                );
            }

            if let &Some(ref units) = &self.units {
                query_pairs.append_pair(
                    UNITS, 
                    serde_json::to_string(&units).unwrap().trim_matches('"')
                );
            }
        };

        url
    }
}

/// Model object representing a request to the Time Machine API.
#[derive(PartialEq, Debug)]
pub struct TimeMachineRequest<'a> {
    api_key: &'a str,
    latitude: f64,
    longitude: f64,
    time: u64,
    url: Url,
    exclude: Vec<ExcludeBlock>,
    lang: Option<Lang>,
    units: Option<Units>
}

impl<'a> TimeMachineRequest<'a> {
    pub fn new(
        api_key: &'a str,
        latitude: f64,
        longitude: f64,
        time: u64,
        url: Url,
        exclude: Vec<ExcludeBlock>,
        lang: Option<Lang>,
        units: Option<Units>
    ) -> TimeMachineRequest<'a> {
        TimeMachineRequest {
            api_key: api_key,
            latitude: latitude,
            longitude: longitude,
            time: time,
            url: url,
            exclude: exclude,
            lang: lang,
            units: units
        }
    }
}

impl<'a> IntoUrl for TimeMachineRequest<'a> {
    fn into_url(self) -> Result<Url, ParseError> {
        Result::Ok(self.url)
    }
}

/// Builder object used to construct a TimeMachineRequest.
#[derive(PartialEq, Debug)]
pub struct TimeMachineRequestBuilder<'a> {
    api_key: &'a str,
    latitude: f64,
    longitude: f64,
    time: u64,
    exclude: Vec<ExcludeBlock>,
    lang: Option<Lang>,
    units: Option<Units>
}

impl<'a> TimeMachineRequestBuilder<'a> {

    /// A Time Machine API request is constructed with required params
    /// `api_key`, `latitude`, `longitude`, and `time`.
    pub fn new(
        api_key: &'a str, latitude: f64, longitude: f64, time: u64
    ) -> TimeMachineRequestBuilder {
        TimeMachineRequestBuilder {
            api_key: api_key,
            latitude: latitude,
            longitude: longitude,
            time: time,
            exclude: Vec::new(),
            lang: None,
            units: None
        }
    }

    /// Add a DataBlock to exclude from the response.
    pub fn exclude_block(mut self, exclude_block: ExcludeBlock) -> TimeMachineRequestBuilder<'a> {
        self.exclude.push(exclude_block);
        self
    }

    /// Add multiple DataBlocks to exclude from the response.
    pub fn exclude_blocks(
        mut self, exclude_blocks: &mut Vec<ExcludeBlock>
    ) -> TimeMachineRequestBuilder<'a> {
        self.exclude.append(exclude_blocks);
        self
    }

    /// Set the language for messages in the response data.
    pub fn lang(mut self, lang: Lang) -> TimeMachineRequestBuilder<'a> {
        self.lang = Some(lang);
        self
    }

    /// Set the measurement units for response data.
    pub fn units(mut self, units: Units) -> TimeMachineRequestBuilder<'a> {
        self.units = Some(units);
        self
    }

    /// Finalize the request.
    pub fn build(self) -> TimeMachineRequest<'a> {
        TimeMachineRequest::new(
            self.api_key,
            self.latitude,
            self.longitude,
            self.time,
            self.build_url(),
            self.exclude,
            self.lang,
            self.units
        )
    }

    fn build_url(&self) -> Url {
        let url_string = format!(
           "{base}/{key}/{lat:.16},{long:.16},{time}", 
            base=FORECAST_URL,
            key=self.api_key,
            lat=self.latitude,
            long=self.longitude,
            time=self.time
        );

        let mut url = Url::parse(&url_string).unwrap();

        {
            let mut query_pairs = url.query_pairs_mut();

            if !self.exclude.is_empty() {
                let excludes = join(
                    &self.exclude
                        .iter()
                        .map(|e| {
                            let json = serde_json::to_string(e).unwrap();
                            json.trim_matches('"').to_string()
                        })
                        .collect::<Vec<String>>(),
                    ","
                );

                query_pairs.append_pair(EXCLUDE, &excludes);
            }

            if let &Some(ref lang) = &self.lang {
                query_pairs.append_pair(
                    LANG, 
                    serde_json::to_string(&lang).unwrap().trim_matches('"')
                );
            }

            if let &Some(ref units) = &self.units {
                query_pairs.append_pair(
                    UNITS, 
                    serde_json::to_string(&units).unwrap().trim_matches('"')
                );
            }
        }

        url
    }
}

// unit tests

#[cfg(test)]
mod tests {
    use super::{ForecastRequestBuilder, ForecastRequest, TimeMachineRequestBuilder, 
                TimeMachineRequest, ExcludeBlock, Units, Lang, ExtendBy, FORECAST_URL,
                EXCLUDE, EXTEND, LANG, UNITS};

    use hyper::Url;

    use std::vec::Vec;

    // constants

    const LAT: f64 = 6.66;
    const LONG: f64 = 66.6;
    const TIME: u64 = 666;

    static API_KEY: &'static str = "some_api_key";

    // tests for request models and their builders

    #[test]
    fn test_forecast_request_builder_defaults() {
        let request = ForecastRequestBuilder::new(API_KEY, LAT, LONG).build();

        let expected_url = Url::parse(
            &format!(
                "{base}/{key}/{lat:.16},{long:.16}?",
                base=FORECAST_URL,
                key=API_KEY,
                lat=LAT,
                long=LONG
            )
        ).unwrap();

        let expected = ForecastRequest::new(
            API_KEY,
            LAT,
            LONG,
            expected_url,
            Vec::new(),
            None,
            None,
            None
        );

        assert_eq!(expected.api_key, request.api_key);
        assert_eq!(expected.latitude, request.latitude);
        assert_eq!(expected.longitude, request.longitude);
        assert_eq!(expected.exclude, request.exclude);
        assert_eq!(expected.extend, request.extend);
        assert_eq!(expected.lang, request.lang);
        assert_eq!(expected.units, request.units);
        assert_eq!(expected.url, request.url);

        assert_eq!(expected, request);
    }

    #[test]
    fn test_forecast_request_builder_simple() {
        let mut blocks = vec![ExcludeBlock::Daily, ExcludeBlock::Alerts];

        let request = ForecastRequestBuilder::new(API_KEY, LAT, LONG)
            .exclude_block(ExcludeBlock::Hourly)
            .exclude_blocks(&mut blocks)
            .extend(ExtendBy::Hourly)
            .lang(Lang::Arabic)
            .units(Units::Imperial)
            .build();

        let expected_url = {
            let mut url = Url::parse(
                &format!(
                    "{base}/{key}/{lat:.16},{long:.16}",
                    base=FORECAST_URL,
                    key=API_KEY,
                    lat=LAT,
                    long=LONG
                )
            ).unwrap();

            url.query_pairs_mut()
                .append_pair(EXCLUDE, "hourly,daily,alerts")
                .append_pair(EXTEND, "hourly")
                .append_pair(LANG, "ar")
                .append_pair(UNITS, "us");

            url
        };

        let expected = ForecastRequest::new(
            API_KEY,
            LAT,
            LONG,
            expected_url,
            vec![ExcludeBlock::Hourly, ExcludeBlock::Daily, ExcludeBlock::Alerts],
            Some(ExtendBy::Hourly),
            Some(Lang::Arabic),
            Some(Units::Imperial)
        );

        assert_eq!(expected, request);
    }

    #[test]
    fn test_forecast_request_builder_complex() {
        let mut builder = ForecastRequestBuilder::new(API_KEY, LAT, LONG);
        let mut blocks = vec![ExcludeBlock::Daily, ExcludeBlock::Alerts];

        builder = builder.exclude_block(ExcludeBlock::Hourly);
        builder = builder.exclude_blocks(&mut blocks);
        builder = builder.extend(ExtendBy::Hourly);
        builder = builder.lang(Lang::Arabic);
        builder = builder.units(Units::Imperial);

        let expected_url = {
            let mut url = Url::parse(
                &format!(
                    "{base}/{key}/{lat:.16},{long:.16}",
                    base=FORECAST_URL,
                    key=API_KEY,
                    lat=LAT,
                    long=LONG
                )
            ).unwrap();

            url.query_pairs_mut()
                .append_pair(EXCLUDE, "hourly,daily,alerts")
                .append_pair(EXTEND, "hourly")
                .append_pair(LANG, "ar")
                .append_pair(UNITS, "us");

            url
        };

        let expected = ForecastRequest::new(
            API_KEY,
            LAT,
            LONG,
            expected_url,
            vec![ExcludeBlock::Hourly, ExcludeBlock::Daily, ExcludeBlock::Alerts],
            Some(ExtendBy::Hourly),
            Some(Lang::Arabic),
            Some(Units::Imperial)
        );

        assert_eq!(expected, builder.build());
    }

    #[test]
    fn test_time_machine_request_builder_defaults() {
        let request = TimeMachineRequestBuilder::new(API_KEY, LAT, LONG, TIME).build();

        let expected_url = Url::parse(
            &format!(
                "{base}/{key}/{lat:.16},{long:.16},{time}?",
                base=FORECAST_URL,
                key=API_KEY,
                lat=LAT,
                long=LONG,
                time=TIME
            )
        ).unwrap();

        let expected = TimeMachineRequest::new(
            API_KEY,
            LAT,
            LONG,
            TIME,
            expected_url,
            Vec::new(),
            None,
            None
        );

        assert_eq!(expected.api_key, request.api_key);
        assert_eq!(expected.latitude, request.latitude);
        assert_eq!(expected.longitude, request.longitude);
        assert_eq!(expected.time, request.time);
        assert_eq!(expected.exclude, request.exclude);
        assert_eq!(expected.lang, request.lang);
        assert_eq!(expected.units, request.units);
        assert_eq!(expected.url, request.url);

        assert_eq!(expected, request);
    }

    #[test]
    fn test_time_machine_request_builder_simple() {
        let mut blocks = vec![ExcludeBlock::Daily, ExcludeBlock::Alerts];

        let request = TimeMachineRequestBuilder::new(API_KEY, LAT, LONG, TIME)
            .exclude_block(ExcludeBlock::Hourly)
            .exclude_blocks(&mut blocks)
            .lang(Lang::Arabic)
            .units(Units::Imperial)
            .build();

        let expected_url = {
            let mut url = Url::parse(
                &format!(
                    "{base}/{key}/{lat:.16},{long:.16},{time}",
                    base=FORECAST_URL,
                    key=API_KEY,
                    lat=LAT,
                    long=LONG,
                    time=TIME
                )
            ).unwrap();

            url.query_pairs_mut()
                .append_pair(EXCLUDE, "hourly,daily,alerts")
                .append_pair(LANG, "ar")
                .append_pair(UNITS, "us");

            url
        };

        let expected = TimeMachineRequest::new(
            API_KEY,
            LAT,
            LONG,
            TIME,
            expected_url,
            vec![ExcludeBlock::Hourly, ExcludeBlock::Daily, ExcludeBlock::Alerts],
            Some(Lang::Arabic),
            Some(Units::Imperial)
        );

        assert_eq!(expected, request);
    }

    #[test]
    fn test_time_machine_request_builder_complex() {
        let mut builder = TimeMachineRequestBuilder::new(API_KEY, LAT, LONG, TIME);
        let mut blocks = vec![ExcludeBlock::Daily, ExcludeBlock::Alerts];

        builder = builder.exclude_block(ExcludeBlock::Hourly);
        builder = builder.exclude_blocks(&mut blocks);
        builder = builder.lang(Lang::Arabic);
        builder = builder.units(Units::Imperial);

        let expected_url = {
            let mut url = Url::parse(
                &format!(
                    "{base}/{key}/{lat:.16},{long:.16},{time}",
                    base=FORECAST_URL,
                    key=API_KEY,
                    lat=LAT,
                    long=LONG,
                    time=TIME
                )
            ).unwrap();

            url.query_pairs_mut()
                .append_pair(EXCLUDE, "hourly,daily,alerts")
                .append_pair(LANG, "ar")
                .append_pair(UNITS, "us");

            url
        };

        let expected = TimeMachineRequest::new(
            API_KEY,
            LAT,
            LONG,
            TIME,
            expected_url,
            vec![ExcludeBlock::Hourly, ExcludeBlock::Daily, ExcludeBlock::Alerts],
            Some(Lang::Arabic),
            Some(Units::Imperial)
        );

        assert_eq!(expected, builder.build());
    }
}