#!/usr/bin/perl  -w
# get_recommendations.pl
#
# Skrypt loguje si na Amazon, pobiera rekomendacje
# i sortuje je od najwyszych ocen.
# Uycie: perl get_recommendations.pl

use strict;
use HTTP::Cookies;
use LWP::UserAgent;

# Konto e-mail i haso do Amazon.
my $email = 'tutaj wstaw adres e-mail';
my $password = 'tutaj wstaw haso';

# Adres URL Amazon dla zwykych uytkownikw.
my $logurl = "http://www.amazon.com/exec/obidos/flex-sign-in-done/";

# Teraz logujemy si do Amazon.
my $ua = LWP::UserAgent->new;
$ua->agent("(compatible; MSIE 4.01; MSN 2.5; AOL 4.0; Windows 98)");
$ua->cookie_jar( HTTP::Cookies->new('file' => 'cookies.lwp','autosave' => 1));
my %headers = ( 'content-type' => "application/x-www-form-urlencoded" );
$ua->post($logurl, 
  [ email       => $email,
    password    => $password,
    method      => 'get', opt => 'oa',
    page        => 'recs/instant-recs-sign-in-standard.html',
    response    => "tg/recs/recs-post-login-dispatch/-/recs/pd_rw_gw_r",
    'next-page' => 'recs/instant-recs-register-standard.html',
    action      => 'sign-in checked' ], %headers);

# Ustawiamy pewne zmienne na posortowane rekomendacje.
my (%title_list, %author_list);
my (@asins, @ratings, $done);

# Zalogowalimy si, wic damy rekomendacji.
my $recurl = "http://www.amazon.com/exec/obidos/tg/". 
             "stores/recs/instant-recs/-/books/0/t";

# Wszystkie rekomendacje Amazon wstawiamy do tablicy, tytu
# i autor do tablic asocjacyjnych.
until ($done) {

     # Wysanie dania o rekomendacje.
     my $content = $ua->get($recurl)->content;

     # Ptla w kodzie HTML, szukanie pasujcych danych.
     while ($content =~ m!<td colspan=2 width=100%>.*?detail/-/(.*?)/ref.
*?<b>(.*?)</b>.*?by (.*?)\n.*?Average Customer Review&#58;.*?(.*?)out of 5 
stars.*?<td colspan=3><hr noshade size=1></td>!mgis) {
         my ($asin,$title,$author,$rating) = ($1||'',$2||'',$3||'',$4||'');
         $title  =~ s!<.+?>!!g; # po prostu usuwamy wszystkie znaczniki HTML.
         $rating =~ s!\n!!g;    # z ocen usuwamy znaki nowego wiersza.
         $rating =~ s! !!g;     # z ocen usuwamy spacje.
         $title_list{$asin} = $title;    # zapisujemy tytu.
         $author_list{$asin} = $author;  # i autora.
         push (@asins, $asin);           # i numery ASIN.
         push (@ratings, $rating);       # i... no, tak!
     }

     # Czy s jeszcze jakie wyniki? Jeli tak, kontynuujemy ptl.
     if ($content =~ m!<a href=(.*?instant-recs.*?)>more results.*?</a>!i) {
        $recurl = "http://www.amazon.com$1"; # korekta URL.
     } else { $done = 1; } # koniec, to ju wszystko.
}

# Sortowanie wynikw od najwyszych ocen i pokazujemy!
for (sort { $ratings[$b] <=> $ratings[$a] } 0..$#ratings) {
    next unless $asins[$_]; # pominicie spacji.
    print "$title_list{$asins[$_]}  ($asins[$_])\n" . 
          "by $author_list{$asins[$_]} \n" .
          "$ratings[$_] stars.\n\n";
}

