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