PageRenderTime 39ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/DDG/Spice/Goodreads.pm

http://github.com/duckduckgo/zeroclickinfo-spice
Perl | 61 lines | 44 code | 12 blank | 5 comment | 1 complexity | bf457111d626d9a0d3cf8ef7b419616f MD5 | raw file
Possible License(s): Apache-2.0
  1. package DDG::Spice::Goodreads;
  2. use strict;
  3. use DDG::Spice;
  4. use URI::Escape;
  5. use Text::Trim;
  6. # Caching
  7. spice is_cached => 1;
  8. # Goodreads API endpoint
  9. my $api_key = '{{ENV{DDG_SPICE_GOODREADS_APIKEY}}}';
  10. my $book_search_endpoint =
  11. uri_escape('https://www.goodreads.com/search/index.xml?key=')
  12. . $api_key
  13. . uri_escape('&search[field]=') . '$1'
  14. . uri_escape('&q=') . '$2';
  15. spice to => 'https://duckduckgo.com/x.js?u=' . $book_search_endpoint;
  16. spice wrap_jsonp_callback => 1;
  17. # Alternative end points to fetch book description and image.
  18. spice alt_to => {
  19. goodreads_book_details => {
  20. to => 'https://duckduckgo.com/x.js?u='
  21. . uri_escape("https://www.goodreads.com/book/show/") . '$1'
  22. . uri_escape("?format=xml&key=")
  23. . $api_key
  24. },
  25. goodreads_book_image => {
  26. is_cached => 1,
  27. proxy_cache_valid => '200 30d',
  28. to => 'https://duckduckgo.com/m.js?q=$1'
  29. }
  30. };
  31. spice from => '([^-]+)-([^-]+)';
  32. # Triggers
  33. triggers startend => "goodreads", "gr";
  34. my $book_pattern = qr/(list )?(of )?books? ?(written )?(on|by|about) /i;
  35. my $goodreads_pattern = qr/(goodreads|gr)/i;
  36. # Handle statement
  37. handle query_clean => sub {
  38. return unless $_ =~ $book_pattern;
  39. my $search_type =
  40. $_ =~ /by/i
  41. ? "authors"
  42. : "title";
  43. $_ =~ s/$book_pattern//g; # removing the book query pattern from query
  44. $_ =~ s/$goodreads_pattern//g; # removing the goodreads trigger pattern from query
  45. $_ = trim($_); # trim spaces from queries
  46. return "$search_type-$_" if $_;
  47. return;
  48. };
  49. 1;