summaryrefslogtreecommitdiff
path: root/lib/gcstar/GCPlugins/GCbooks/GCAmazon.pm
blob: 7d70ec4959ed1aedb97d3199ad6c705460963485 (plain)
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
package GCPlugins::GCbooks::GCAmazon;

###################################################
#
#  Copyright 2005-2009 Tian
#
#  This file is part of GCstar.
#
#  GCstar is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  GCstar is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with GCstar; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
###################################################

use strict;
use utf8;

use GCPlugins::GCbooks::GCbooksCommon;

{
    package GCPlugins::GCbooks::GCPluginAmazon;
    
    use base qw(GCPlugins::GCbooks::GCbooksPluginsBase);
    use XML::Simple;
    use LWP::Simple qw($ua);
    use Encode;
    use HTML::Entities;
    use GCUtils;

    sub parse
    {
        my ($self, $page) = @_;
        return if $page =~ /^<!DOCTYPE html/;
        my $xml;
        my $xs = XML::Simple->new;

        if ($self->{parsingList})
        {
            $xml = $xs->XMLin($page, ForceArray => ['Item','Author'], KeyAttr => []);
            my $book;
            foreach $book ( @{ $xml -> {'Items'} -> {'Item'} })
            {
                $self->{itemIdx}++;
                my $url = $self->baseAWSUrl."&Operation=ItemLookup&ResponseGroup=Large,EditorialReview&ItemId=".$book->{ASIN};
                
                $self->{itemsList}[$self->{itemIdx}]->{url} = $url;
                $self->{itemsList}[$self->{itemIdx}]->{title} = $book->{ItemAttributes}->{'Title'};
                for my $author (@{$book->{ItemAttributes}->{'Author'}})
                {
                    $self->{itemsList}[$self->{itemIdx}]->{authors} .= ", "
                        if $self->{itemsList}[$self->{itemIdx}]->{authors};
                    $self->{itemsList}[$self->{itemIdx}]->{authors} .= $author;
                }
                $self->{itemsList}[$self->{itemIdx}]->{publication} = $book->{ItemAttributes}->{'PublicationDate'};
                $self->{itemsList}[$self->{itemIdx}]->{format} = $book->{ItemAttributes}->{'Binding'};
                $self->{itemsList}[$self->{itemIdx}]->{edition} = $book->{ItemAttributes}->{'Edition'};
            }
        }
        else
        {
            $xml = $xs->XMLin($page, ForceArray => ['Author','EditorialReview','Language'], KeyAttr => []);   
            $self->{curInfo}->{title} = $xml->{Items}->{Item}->{ItemAttributes}->{Title};
            for my $author (@{$xml->{Items}->{Item}->{ItemAttributes}->{Author}})
            {
                push @{$self->{curInfo}->{authors}}, [$author];
            }
            
            my $htmlDescription;
            if ($xml->{Items}->{Item}->{EditorialReviews}->{EditorialReview}[0]->{Content})
            {
                $htmlDescription = $xml->{Items}->{Item}->{EditorialReviews}->{EditorialReview}[0]->{Content};
            }
            else
            {
                # Unfortunately the api doesn't always return the product description, which is due to
                # copyright concerns or something. In this case, grab the product html and parse it for
                # the description.
                my $response = $ua->get($xml->{Items}->{Item}->{DetailPageURL});
                my $result;
                eval {
                    $result = $response->decoded_content;
                };
                
                # Replace some bad characters. TODO - will probably need to extend this for de/jp plugins
                $result =~ s|\x{92}|'|gi;
                $result =~ s|&#146;|'|gi;
                $result =~ s|&#149;|*|gi;
                $result =~ s|&#156;|oe|gi;
                $result =~ s|&#133;|...|gi;
                $result =~ s|\x{85}|...|gi;
                $result =~ s|\x{8C}|OE|gi;
                $result =~ s|\x{9C}|oe|gi;
                $result =~ s|&#252;|ü|g;
                $result =~ s|&#223;|ß|g;
                $result =~ s|&#246;|ö|g;
                $result =~ s|&#220;|Ü|g;
                $result =~ s|&#228;|ä|g;  
		        $result =~ s/&#132;/&#187;/gm;
		        $result =~ s/&#147;/&#171;/gm;                              
                
                # Chop out the product description
                $result =~ /<div class="productDescriptionWrapper">(.*?)<(\/)*?div/s;
                $htmlDescription = $1;
                
                # Decode
                decode_entities($htmlDescription);
                $htmlDescription = decode('ISO-8859-1', $htmlDescription);
            }
            
            # Replace some html with line breaks, strip out the rest
            $htmlDescription =~ s/<br>/\n/ig;
            $htmlDescription =~ s/<p>/\n\n/ig;
            $htmlDescription =~ s/<(.*?)>//gi;            
            $htmlDescription =~ s/^\s*//;
            $htmlDescription =~ s/\s*$//;         
            $htmlDescription =~ s/ {1,}/ /g;   
            $self->{curInfo}->{description} = $htmlDescription;
            
            $self->{curInfo}->{publisher} = $xml->{Items}->{Item}->{ItemAttributes}->{Publisher}
                if (!ref($xml->{Items}->{Item}->{ItemAttributes}->{Publisher}));
            $self->{curInfo}->{publication} = $xml->{Items}->{Item}->{ItemAttributes}->{PublicationDate}
                if (!ref($xml->{Items}->{Item}->{ItemAttributes}->{PublicationDate}));
            $self->{curInfo}->{language} = $xml->{Items}->{Item}->{ItemAttributes}->{Languages}->{Language}[0]->{Name}
                if (ref($xml->{Items}->{Item}->{ItemAttributes}->{Languages}->{Language}));
            $self->{curInfo}->{pages} = $xml->{Items}->{Item}->{ItemAttributes}->{NumberOfPages}
                if (!ref($xml->{Items}->{Item}->{ItemAttributes}->{NumberOfPages}));
            $self->{curInfo}->{isbn} = $xml->{Items}->{Item}->{ItemAttributes}->{EAN}
                if (!ref($xml->{Items}->{Item}->{ItemAttributes}->{EAN}));
            $self->{curInfo}->{format} = $xml->{Items}->{Item}->{ItemAttributes}->{Binding}
                if (!ref($xml->{Items}->{Item}->{ItemAttributes}->{Binding}));
            $self->{curInfo}->{edition} = $xml->{Items}->{Item}->{ItemAttributes}->{Edition}
                if (!ref($xml->{Items}->{Item}->{ItemAttributes}->{Edition}));
            $self->{curInfo}->{web} = $xml->{Items}->{Item}->{DetailPageURL};

            # Genre handling via Amazon's browsenodes. Stupidly complicated way of doing things, IMO
            # Loop through all the nodes:
            for my $node (@{$xml->{Items}->{Item}->{BrowseNodes}->{BrowseNode}})
            {
                my $genre = '';
                my $ancestor = $node;
                
                # Push the lowest node to the temporary genre list
                my @genre_list = ($node->{Name});
                
                # Start stepping down through the current node to find it's children
                while ($ancestor->{Ancestors}->{BrowseNode})
                {
                    $ancestor = $ancestor->{Ancestors}->{BrowseNode};
                    if (($ancestor->{Name} eq 'Specialty Stores') ||
                        ($ancestor->{Name} eq 'Refinements') || 
                        ($ancestor->{Name} eq 'Self Service') || 
                        ($ancestor->{Name} eq 'Specialty Boutique'))
                    {
                        # Some categories we definetly want to ignore, since they are full of rubbish tags
                        $genre = 'ignore';
                        last;
                    }
                    elsif ($ancestor->{Name} =~ m/A\-Z/) 
                    {
                        # Clear out the current genres from the node, will be full of rubbish like "Authors A-K"
                        # Keep looping afterwards though, since there could be valid tags below the author
                        # specific ones
                        undef(@genre_list);
                    }
                    elsif ($ancestor->{Name} eq 'Subjects')
                    {
                        # Don't go deeper than a Subjects node
                        last;
                    }
                    else
                    {
                        # Add the current node to the temporary list, if it's not already included in either list
                        push @genre_list, $ancestor->{Name}
                            if ((!GCUtils::inArrayTest($ancestor->{Name}, @genre_list)) && 
                                (!GCUtils::inArrayTest($ancestor->{Name}, @{$self->{curInfo}->{genre}})));
                    }
                }
                
                if ($genre ne 'ignore')
                {               
                    # Add temporary list to item info
                    push @{$self->{curInfo}->{genre}}, [$_] foreach @genre_list;
                }
            }   
            
            # Let's sort the list for good measure
            @{$self->{curInfo}->{genre}} = sort @{$self->{curInfo}->{genre}};
            

            # Fetch either the big original pic, or just the small thumbnail pic
            if ($self->{bigPics})
            {
                $self->{curInfo}->{cover} = $xml->{Items}->{Item}->{LargeImage}->{URL};
            }
            else
            {
                $self->{curInfo}->{cover} = $xml->{Items}->{Item}->{SmallImage}->{URL};
            }
        }
    }

    sub new
    {
        my $proto = shift;
        my $class = ref($proto) || $proto;
        my $self  = $class->SUPER::new();
        bless ($self, $class);

        $self->{hasField} = {
            title => 1,
            authors => 1,
            publication => 1,
            format => 1,
            edition => 1,
        };

        return $self;
    }
    
    sub getItemUrl
    {
        my ($self, $url) = @_;
        if (!$url)
        {
            # If we're not passed a url, return a hint so that gcstar knows what type
            # of addresses this plugin handles
            $url = "http://".$self->baseWWWamazonUrl();
        }
        elsif ($url !~ m/sowacs.appspot.com/)
        {        
            # Convert amazon url to aws url
            $url =~ /\/dp\/(\w*)[\/|%3F]/;
            my $asinid = $1;
            $url = $self->baseAWSUrl."&Operation=ItemLookup&ResponseGroup=Large,EditorialReview&ItemId=".$asinid;
        }
        return $url;
    }

    sub preProcess
    {
        my ($self, $html) = @_;

        return $html;
    }
    
    sub decodeEntitiesWanted
    {
        return 0;
    }

    sub getSearchUrl
    {
		my ($self, $word) = @_;		

        my $key = 
            ($self->{searchField} eq 'authors') ? 'Author' :
            ($self->{searchField} eq 'title')   ? 'Title' :
            ($self->{searchField} eq 'isbn')    ? 'Keywords' :
                                                  '';
       $word =~ s/\D//g
            if $key eq 'Keywords';
		return $self->baseAWSUrl."&Operation=ItemSearch&$key=$word&SearchIndex=Books&ResponseGroup=Medium";
    }
    
    sub baseAWSUrl
    {	
        my $self = shift;
		return "http://sowacs.appspot.com/AWS/%5Bamazon\@gcstar.org%5D".$self->baseAmazonUrl()."/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=AKIAJJ5TJWI62A5OOTQQ&AssociateTag=AKIAJJ5TJWI62A5OOTQQ";
    }
    
    sub baseAmazonUrl
    {
		return "ecs.amazonaws.com";    
    }
    
    sub baseWWWamazonUrl
    {   
		return "www.amazon.com";    
    }    
    
    sub changeUrl
    {
        my ($self, $url) = @_;
        # Make sure the url is for the api, not the main movie page
        return $self->getItemUrl($url);
    }

    sub getName
    {
        return "Amazon (US)";
    }
    
    sub getAuthor
    {
        return 'Zombiepig';
    }
    
    sub getLang
    {
        return 'EN';
    }

    sub getCharset
    {
        my $self = shift;
    
        return "UTF-8";
    }
    
    sub getSearchCharset
    {
        my $self = shift;
        
        # Need urls to be double character encoded
        return "utf8";
    }

    sub convertCharset
    {
        my ($self, $value) = @_;
        return $value;
    }

    sub getNotConverted
    {
        my $self = shift;
        return [];
    }

    sub isPreferred
    {
        return 1;
    }
    
    sub getSearchFieldsArray
    {
        return ['title', 'authors', 'isbn'];
    }

}

1;