# MT-WAIR # # A "What am I reading" plugin for MT # # Ricardo Cerqueira, 2003-2004 # # Image size option bu suggestion of Noel Llopis # package MT::Plugin::MTWAIR; use strict; use XML::Simple; use LWP::UserAgent; use MT::Template::Context; ## If you use amazon.co.uk, amazon.de, or amazon.fr to buy & search # for your books, uncomment the line which matches your country and # make sure all other $europe lines are commented out # # UK #my $europe="&locale=uk"; # France #my $europe="&locale=fr"; # Germany #my $europe="&locale=de"; # Default (amazon.com) my $europe=""; ## Got an Amazon partner/affiliate ID? Put it here # my $partnerid="webservices-20"; ########################## ## Stop editing now :) ########################## MT::Template::Context->add_container_tag( wair => \&wair ); MT::Template::Context->add_tag(wairName => sub { shift->stash('wairName'); } ); MT::Template::Context->add_tag(wairAuthor => sub { shift->stash('wairAuthor'); } ); MT::Template::Context->add_tag(wairImage => sub { shift->stash('wairImage'); } ); MT::Template::Context->add_tag(wairURL => sub { shift->stash('wairURL'); } ); sub wair { my ($ctx, $args) = @_; my $asin = $ctx->stash('mt-list_current') ? $ctx->stash('mt-list_current_item') : $args->{asin}; return $ctx->error("No ASIN provided!") unless $asin; # Image size defaults to medium my $imgsize = "Medium"; if (defined $args->{imagesize}) { if ($args->{imagesize} =~ /^s/i) { $imgsize = "Small"; } elsif ($args->{imagesize} =~ /^l/i) { $imgsize = "Large"; } else { $imgsize = "Medium"; } } my $bookdata = getAmazonData($asin,$imgsize); if ($bookdata) { $ctx->stash("wairName" => $bookdata->{name}); $ctx->stash("wairAuthor" => $bookdata->{author}); $ctx->stash("wairImage" => $bookdata->{image}); $ctx->stash("wairURL" => $bookdata->{amazonurl}); } my $tokens = $ctx->stash('tokens'); my $builder = $ctx->stash('builder'); my $ret = $builder->build($ctx, $tokens); #return $ctx->error($builder->errstr) unless defined $ret; return "Unable to retrieve data from Amazon!" unless defined $ret; return $ret; } sub getAmazonData { my $asin = shift; my $imgsize = shift; $imgsize = "ImageUrl".$imgsize; my $ua = LWP::UserAgent->new( keep_alive => 1, timeout => 20, agent => 'rmcc\'s MTWAIR Plugin' ); my $host = $europe ? "xml-eu.amazon.com" : "xml.amazon.com"; my $url="http://$host/onca/xml3?t=$partnerid&dev-t=D1NAK9R26OAS2&AsinSearch=$asin&type=heavy&f=xml$europe"; my $response = $ua->get($url); die "Error fetching data" unless ($response->is_success); my $xmldata = $response->content; my $book=XMLin($xmldata); my %result; $result{name} = $book->{Details}->{ProductName}; $result{author} = $book->{Details}->{Authors} ? $book->{Details}->{Authors}->{Author} : $book->{Details}->{Artists}->{Artist}; $result{image} = $book->{Details}->{$imgsize}; $result{amazonurl} = $book->{Details}->{url}; if (ref $result{author} eq 'ARRAY') { $result{author} = join ", ",@{$result{author}}; } return $result{name} ? \%result : undef; } 1;