PageRenderTime 37ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/DDG/Spice/Seasons.pm

http://github.com/duckduckgo/zeroclickinfo-spice
Perl | 73 lines | 43 code | 19 blank | 11 comment | 8 complexity | 313ce271c10da1ba29c67a83fb07c85a MD5 | raw file
Possible License(s): Apache-2.0
  1. package DDG::Spice::Seasons;
  2. # ABSTRACT: Return dates for the start of given seasons, solstices, equinoctes
  3. use DDG::Spice;
  4. use Locale::Country qw/country2code/;
  5. my @seasons = qw(spring summer autumn winter fall vernal autumnal march june september december);
  6. my $seasons_qr = join "|", @seasons;
  7. triggers any => @seasons;
  8. spice from => "(.+)/(.+)/.*";
  9. spice to => 'https://api.xmltime.com/holidays?accesskey={{ENV{DDG_SPICE_TIME_AND_DATE_ACCESSKEY}}}&secretkey={{ENV{DDG_SPICE_TIME_AND_DATE_SECRETKEY}}}&callback={{callback}}&country=$2&year=$1&types=seasons&version=1';
  10. spice proxy_cache_valid => "200 30d";
  11. spice is_cached => 1;
  12. # Note: In 2014, Timeanddate.com API returned results for 1695 through 2290. 319 years into past, 76 years into future.
  13. use constant {
  14. YEARS_INTO_FUTURE => 276,
  15. API_EPOCH => 1965
  16. };
  17. # Common aliases
  18. my %aliases = (
  19. 'march' => 'spring',
  20. 'vernal' => 'spring',
  21. 'june' => 'summer',
  22. 'september' => 'autumn',
  23. 'fall' => 'autumn',
  24. 'autumnal' => 'autumn',
  25. 'december' => 'winter'
  26. );
  27. # Handle statement
  28. handle query_lc => sub {
  29. return unless /^(?:(?<year>\d{4}) )?(?:(?:when is the ))?(?:(?:first day|start|beginning) of )?(?<season>$seasons_qr)(?: equinox| solstice)?(?: (?<year>\d{4}))?(?: in (?<country>[\D]+))?(?: (?<year>\d{4}))?$/;
  30. # Get season
  31. my $season = $aliases{$+{season}} // $+{season};
  32. # Get location
  33. my $country;
  34. if ($+{country}){
  35. return unless $country = country2code($+{country});
  36. } else {
  37. $country = lc $loc->country_code;
  38. }
  39. # Detect year
  40. my $current_year = (localtime(time))[5] + 1900;
  41. my $year = $+{year} // $current_year;
  42. # Keep year within API limits
  43. return unless (defined $year && $year >= API_EPOCH && $year <= ($current_year + YEARS_INTO_FUTURE));
  44. # Make sure all required parameters are set
  45. return unless (defined $year && defined $country && defined $season);
  46. my $caching = 0;
  47. # Cache queries that specify year and country
  48. if ($+{country} && $+{year}) {
  49. $caching = 1;
  50. }
  51. # Season is not required for the API call, but used in the frontend
  52. return $year, $country, $season, {is_cached => $caching};
  53. };
  54. 1;