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
pub mod model;

use std::{collections::HashMap, time::Duration};

use reqwest::{header::{self, HeaderValue}, Client, Url};

#[derive(Debug)]
pub struct HolidayEventApi {
    client: Client,
    base_url: Url,
}

static APP_USER_AGENT: &str = concat!(
    "HolidayApiRust/",
    env!("CARGO_PKG_VERSION"),
);

impl HolidayEventApi {
    pub fn new(api_key: String, base_url: Option<String>) -> Result<Self, String> {
        if api_key.is_empty() {
            return Err("Please provide a valid API key. Get one at https://apilayer.com/marketplace/checkiday-api#pricing.".into());
        }
        // TODO expose and test more errors
        let mut headers = header::HeaderMap::new();
        headers.insert("apikey", header::HeaderValue::from_str(&api_key.as_str()).unwrap());
        let rustc = rustc_version_runtime::version();
        headers.insert("X-Platform-Version", header::HeaderValue::from_str(&rustc.to_string()).unwrap());

        let client = reqwest::Client::builder()
            .default_headers(headers)
            .user_agent(APP_USER_AGENT)
            .timeout(Duration::from_secs(10))
            .build().unwrap();

        let base_url = Url::parse(base_url.unwrap_or("https://api.apilayer.com/checkiday/".to_string()).as_str()).unwrap();

        Ok(Self {
            client,
            base_url,
        })
    }

    /// Gets the Events for the provided Date
    pub async fn get_events(&self, request: model::GetEventsRequest) -> Result<model::GetEventsResponse, String> {
        let mut params: HashMap<String, String> = HashMap::from([
            ("adult".into(), request.adult.unwrap_or(false).to_string())]);

        if let Some(tz) = request.timezone {
            params.insert("timezone".into(), tz);
        }

        if let Some(date) = request.date {
            params.insert("date".into(), date);
        }

        self.request("events".into(), params).await
    }

    /// Gets the Event Info for the provided Event
    pub async fn get_event_info(&self, request: model::GetEventInfoRequest) -> Result<model::GetEventInfoResponse, String> {
        if request.id.is_empty() {
            return Err("Event id is required.".into());
        }

        let mut params: HashMap<String, String> = HashMap::from([("id".into(), request.id)]);

        if let Some(start) = request.start {
            params.insert("start".into(), start.to_string());
        }

        if let Some(end) = request.end {
            params.insert("end".into(), end.to_string());
        }

        self.request("event".into(), params).await
    }

    /// Searches for Events with the given criteria
    pub async fn search(&self, request: model::SearchRequest) -> Result<model::SearchResponse, String> {
        if request.query.is_empty() {
            return Err("Search query is required.".into());
        }

        let params: HashMap<String, String> = HashMap::from([
            ("query".into(), request.query),
            ("adult".into(), request.adult.unwrap_or(false).to_string()),
        ]);

        self.request("search".into(), params).await
    }

    async fn request<T>(&self, path: String, params: HashMap<String, String>) -> Result<T, String> where T: serde::de::DeserializeOwned + std::fmt::Debug + model::RateLimited {
        let mut url = self.base_url.join(&path.to_string()).unwrap();
        url.query_pairs_mut().extend_pairs(params);

        let res = self.client.get(url).send().await;
        if res.is_err() {
            let err = res.unwrap_err().to_string();
            return Err(format!("Can't process request: {err}").into());
        }
        let res = res.unwrap();
        let status = res.status();
        if !status.is_success() {
            let json = res.json::<HashMap<String, String>>().await;
            if json.is_err() || json.as_ref().unwrap().get("error").unwrap_or(&"".into()).is_empty() {
                return Err(status.canonical_reason().unwrap_or(status.as_str()).into());
            } else {
                return Err(json.unwrap().get("error").unwrap().to_owned());
            }
        }
        let headers = res.headers().to_owned();
        let json = res.json::<T>().await;
        if json.is_err() {
            let err = json.unwrap_err().to_string();
            return Err(format!("Can't parse response: {err}"));
        }
        let rate_limit = model::RateLimit {
            limit_month: headers.get("x-ratelimit-limit-month").unwrap_or(&HeaderValue::from_str("").unwrap()).to_str().unwrap_or("").parse::<i32>().unwrap_or(0),
            remaining_month: headers.get("x-ratelimit-remaining-month").unwrap_or(&HeaderValue::from_str("").unwrap()).to_str().unwrap_or("").parse::<i32>().unwrap_or(0),
        };
        let mut result = json.unwrap();
        result.set_rate_limit(rate_limit);
        Ok(result)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use mockito::{Matcher, Server};

    macro_rules! aw {
        ($e:expr) => {
            tokio_test::block_on($e)
        };
    }

    mod new {
        use super::*;

        #[test]
        fn fails_with_missing_api_key() {
            let result = HolidayEventApi::new("".into(), None);
            assert_eq!(true, result.is_err());
            assert_eq!("Please provide a valid API key. Get one at https://apilayer.com/marketplace/checkiday-api#pricing.".to_string(), result.unwrap_err());
        }

        #[test]
        fn returns_a_new_client() {
            assert!(HolidayEventApi::new("abc123".into(), None).is_ok());
        }

    }

    mod common_functionality {
        use crate::model::RateLimited;

        use super::*;

        #[test]
        fn passes_along_api_key() {
            let mut server = Server::new();

            let mock = server.mock("GET", "/events")
                .match_query(Matcher::Any)
                .match_header("apikey", "abc123")
                .with_body_from_file("testdata/getEvents-default.json")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            assert!(aw!(api.get_events(model::GetEventsRequest { date: None, adult: None, timezone: None })).is_ok());

            mock.assert();
        }

        #[test]
        fn passes_along_user_agent() {
            let mut server = Server::new();

            let app_version = env!("CARGO_PKG_VERSION");
            let mock = server.mock("GET", "/events")
                .match_query(Matcher::Any)
                .match_header("user-agent", format!("HolidayApiRust/{app_version}").as_str())
                .with_body_from_file("testdata/getEvents-default.json")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            assert!(aw!(api.get_events(model::GetEventsRequest { date: None, adult: None, timezone: None })).is_ok());

            mock.assert();
        }

        #[test]
        fn passes_along_platform_version() {
            let mut server = Server::new();

            let app_version = rustc_version_runtime::version().to_string();
            let mock = server.mock("GET", "/events")
                .match_query(Matcher::Any)
                .match_header("x-platform-version", app_version.as_str())
                .with_body_from_file("testdata/getEvents-default.json")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            assert!(aw!(api.get_events(model::GetEventsRequest { date: None, adult: None, timezone: None })).is_ok());

            mock.assert();
        }

        #[test]
        fn passes_along_error() {
            let mut server = Server::new();

            let mock = server.mock("GET", "/events")
                .match_query(Matcher::Any)
                .with_status(401)
                .with_body("{\"error\":\"MyError!\"}")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            let result = aw!(api.get_events(model::GetEventsRequest { date: None, adult: None, timezone: None }));

            assert_eq!("MyError!", result.unwrap_err());

            mock.assert();
        }

        #[test]
        fn server_error_500() {
            let mut server = Server::new();

            let mock = server.mock("GET", "/events")
                .match_query(Matcher::Any)
                .with_status(500)
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            let result = aw!(api.get_events(model::GetEventsRequest { date: None, adult: None, timezone: None }));

            assert_eq!("Internal Server Error", result.unwrap_err());

            mock.assert();
        }

        #[test]
        fn server_error_unknown() {
            let mut server = Server::new();

            let mock = server.mock("GET", "/events")
                .match_query(Matcher::Any)
                .with_status(599)
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            let result = aw!(api.get_events(model::GetEventsRequest { date: None, adult: None, timezone: None }));

            assert_eq!("599", result.unwrap_err());

            mock.assert();
        }

        #[test]
        fn server_error_other() {
            let fake_url = "http://localhost".to_string();
            let api = HolidayEventApi::new("abc123".into(), Some(fake_url)).unwrap();
            let result = aw!(api.get_events(model::GetEventsRequest { date: None, adult: None, timezone: None }));

            assert_eq!("Can't process request: error sending request for url (http://localhost/events?adult=false): error trying to connect: tcp connect error: Connection refused (os error 61)", result.unwrap_err());
        }

        #[test]
        fn server_error_malformed_response() {
            let mut server = Server::new();

            let mock = server.mock("GET", "/events")
                .match_query(Matcher::Any)
                .with_body("{")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            let result = aw!(api.get_events(model::GetEventsRequest { date: None, adult: None, timezone: None }));

            assert_eq!("Can't parse response: error decoding response body: EOF while parsing an object at line 1 column 1", result.unwrap_err());

            mock.assert();
        }

        #[test]
        fn follows_redirects() {
            let mut server = Server::new();

            let url = server.url();
            let mock = server.mock("GET", "/events")
                .match_query(Matcher::Any)
                .with_status(302)
                .with_header("Location", format!("{url}/redirected").as_str())
                .create();

            let mock2 = server.mock("GET", "/redirected")
                .match_query(Matcher::Any)
                .with_body_from_file("testdata/getEvents-default.json")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            assert!(aw!(api.get_events(model::GetEventsRequest { date: None, adult: None, timezone: None })).is_ok());

            mock.assert();
            mock2.assert();
        }

        #[test]
        fn reports_rate_limits() {
            let mut server = Server::new();

            let mock = server.mock("GET", "/events")
                .match_query(Matcher::Any)
                .with_header("X-RateLimit-Limit-Month", "100")
                .with_header("x-ratelimit-remaining-month", "88")
                .with_body_from_file("testdata/getEvents-default.json")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            let result = aw!(api.get_events(model::GetEventsRequest { date: None, adult: None, timezone: None }));

            assert!(result.is_ok());
            let result = result.unwrap();
            assert_eq!(100, result.get_rate_limit().limit_month);
            assert_eq!(88, result.get_rate_limit().remaining_month);

            mock.assert();
        }
    }

    mod get_events {
        use super::*;

        #[test]
        fn fetches_with_default_parameters() {
            let mut server = Server::new();

            let mock = server.mock("GET", "/events")
                .match_query(Matcher::Any)
                .with_body_from_file("testdata/getEvents-default.json")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            let result = aw!(api.get_events(model::GetEventsRequest { date: None, adult: None, timezone: None }));

            assert!(result.is_ok());
            let result = result.unwrap();
            assert_eq!(false, result.adult);
            assert_eq!("America/Chicago", result.timezone);
            assert_eq!(2, result.events.len());
            assert_eq!(1, result.multiday_starting.len());
            assert_eq!(2, result.multiday_ongoing.len());
            assert_eq!(&model::EventSummary {
                id: "b80630ae75c35f34c0526173dd999cfc".into(),
                name: "Cinco de Mayo".into(),
                url: "https://www.checkiday.com/b80630ae75c35f34c0526173dd999cfc/cinco-de-mayo".into(),
            }, result.events.get(0).unwrap());

            mock.assert();
        }

        #[test]
        fn fetches_with_set_parameters() {
            let mut server = Server::new();

            let mock = server.mock("GET", "/events")
                .match_query(Matcher::AllOf(vec![
                    Matcher::UrlEncoded("adult".into(), "true".into()),
                    Matcher::UrlEncoded("timezone".into(), "America/New_York".into()),
                    Matcher::UrlEncoded("date".into(), "7/16/1992".into()),
                ]))
                .with_body_from_file("testdata/getEvents-parameters.json")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            let result = aw!(api.get_events(model::GetEventsRequest {
                date: Some("7/16/1992".into()), adult: Some(true), timezone: Some("America/New_York".into())
            }));

            assert!(result.is_ok());
            let result = result.unwrap();
            assert_eq!(true, result.adult);
            assert_eq!("America/New_York", result.timezone);
            assert_eq!(2, result.events.len());
            assert_eq!(0, result.multiday_starting.len());
            assert_eq!(1, result.multiday_ongoing.len());
            assert_eq!(&model::EventSummary {
                id: "6ebb6fd5e483de2fde33969a6c398472".into(),
                name: "Get to Know Your Customers Day".into(),
                url: "https://www.checkiday.com/6ebb6fd5e483de2fde33969a6c398472/get-to-know-your-customers-day".into(),
            }, result.events.get(0).unwrap());

            mock.assert();
        }
    }

    mod get_event_info {
        use super::*;

        #[test]
        fn fetches_with_default_parameters() {
            let mut server = Server::new();

            let mock = server.mock("GET", "/event")
                .match_query(Matcher::UrlEncoded("id".into(), "f90b893ea04939d7456f30c54f68d7b4".into()))
                .with_body_from_file("testdata/getEventInfo-default.json")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            let result = aw!(api.get_event_info(model::GetEventInfoRequest { id: "f90b893ea04939d7456f30c54f68d7b4".into(), start: None, end: None }));

            assert!(result.is_ok());
            let result = result.unwrap();
            assert_eq!("f90b893ea04939d7456f30c54f68d7b4", result.event.id);
            assert_eq!(2, result.event.hashtags.len());

            mock.assert();
        }

        #[test]
        fn fetches_with_set_parameters() {
            let mut server = Server::new();

            let mock = server.mock("GET", "/event")
                .match_query(Matcher::AllOf(vec![
                    Matcher::UrlEncoded("id".into(), "f90b893ea04939d7456f30c54f68d7b4".into()),
                    Matcher::UrlEncoded("start".into(), "2002".into()),
                    Matcher::UrlEncoded("end".into(), "2003".into()),
                ]))
                .with_body_from_file("testdata/getEventInfo-parameters.json")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            let result = aw!(api.get_event_info(model::GetEventInfoRequest {
                id: "f90b893ea04939d7456f30c54f68d7b4".into(), start: Some(2002), end: Some(2003)
            }));

            assert!(result.is_ok());
            let result = result.unwrap();
            assert_eq!(3, result.event.occurrences.len());
            assert_eq!(&model::Occurrence {
                date: model::OccurrenceDate::Date("08/08/2002".into()),
                length: 1,
            }, result.event.occurrences.get(0).unwrap());
            assert_eq!(&model::Occurrence {
                date: model::OccurrenceDate::Timestamp(1734772794),
                length: 1,
            }, result.event.occurrences.get(1).unwrap());
            assert_eq!(&model::Occurrence {
                date: model::OccurrenceDate::Timestamp(-12345),
                length: 7,
            }, result.event.occurrences.get(2).unwrap());

            mock.assert();
        }

        #[test]
        fn invalid_event() {
            let mut server = Server::new();

            let mock = server.mock("GET", "/event")
                .match_query(Matcher::AllOf(vec![
                    Matcher::UrlEncoded("id".into(), "hi".into()),
                ]))
                .with_status(404)
                .with_body("{\"error\":\"Event not found.\"}")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            let result = aw!(api.get_event_info(model::GetEventInfoRequest {
                id: "hi".into(), start: None, end: None,
            }));

            assert!(result.is_err());
            assert_eq!("Event not found.", result.unwrap_err());

            mock.assert();
        }

        #[test]
        fn missing_id() {
            let api = HolidayEventApi::new("abc123".into(), None).unwrap();
            let result = aw!(api.get_event_info(model::GetEventInfoRequest {
                id: "".into(), start: None, end: None,
            }));

            assert!(result.is_err());
            assert_eq!("Event id is required.", result.unwrap_err());
        }
    }

    mod search {
        use super::*;

        #[test]
        fn fetches_with_default_parameters() {
            let mut server = Server::new();

            let mock = server.mock("GET", "/search")
                .match_query(Matcher::UrlEncoded("query".into(), "zucchini".into()))
                .with_body_from_file("testdata/search-default.json")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            let result = aw!(api.search(model::SearchRequest { query: "zucchini".into(), adult: None }));

            assert!(result.is_ok());
            let result = result.unwrap();
            assert_eq!(false, result.adult);
            assert_eq!("zucchini", result.query);
            assert_eq!(3, result.events.len());
            assert_eq!(&model::EventSummary {
                id: "cc81cbd8730098456f85f69798cbc867".into(),
                name: "National Zucchini Bread Day".into(),
                url: "https://www.checkiday.com/cc81cbd8730098456f85f69798cbc867/national-zucchini-bread-day".into(),
            }, result.events.get(0).unwrap());

            mock.assert();
        }

        #[test]
        fn fetches_with_set_parameters() {
            let mut server = Server::new();

            let mock = server.mock("GET", "/search")
                .match_query(Matcher::UrlEncoded("query".into(), "porch day".into()))
                .match_query(Matcher::UrlEncoded("adult".into(), "true".into()))
                .with_body_from_file("testdata/search-parameters.json")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            let result = aw!(api.search(model::SearchRequest { query: "porch day".into(), adult: Some(true) }));

            assert!(result.is_ok());
            let result = result.unwrap();
            assert_eq!(true, result.adult);
            assert_eq!("porch day", result.query);
            assert_eq!(1, result.events.len());
            assert_eq!(&model::EventSummary {
                id: "61363236f06e4eb8e4e14e5925c2503d".into(),
                name: "Sneak Some Zucchini Onto Your Neighbor's Porch Day".into(),
                url: "https://www.checkiday.com/61363236f06e4eb8e4e14e5925c2503d/sneak-some-zucchini-onto-your-neighbors-porch-day".into(),
            }, result.events.get(0).unwrap());

            mock.assert();
        }

        #[test]
        fn query_too_short() {
            let mut server = Server::new();

            let mock = server.mock("GET", "/search")
                .match_query(Matcher::UrlEncoded("query".into(), "a".into()))
                .with_status(400)
                .with_body("{\"error\":\"Please enter a longer search term.\"}")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            let result = aw!(api.search(model::SearchRequest { query: "a".into(), adult: None }));

            assert!(result.is_err());
            assert_eq!("Please enter a longer search term.", result.unwrap_err());

            mock.assert();
        }

        #[test]
        fn too_many_results() {
            let mut server = Server::new();

            let mock = server.mock("GET", "/search")
                .match_query(Matcher::UrlEncoded("query".into(), "day".into()))
                .with_status(400)
                .with_body("{\"error\":\"Too many results returned. Please refine your query.\"}")
                .create();

            let api = HolidayEventApi::new("abc123".into(), Some(server.url())).unwrap();
            let result = aw!(api.search(model::SearchRequest { query: "day".into(), adult: None }));

            assert!(result.is_err());
            assert_eq!("Too many results returned. Please refine your query.", result.unwrap_err());

            mock.assert();
        }

        #[test]
        fn missing_parameters() {
            let api = HolidayEventApi::new("abc123".into(), None).unwrap();
            let result = aw!(api.search(model::SearchRequest { query: "".into(), adult: None }));

            assert!(result.is_err());
            assert_eq!("Search query is required.", result.unwrap_err());
        }
    }
}