1#!/usr/bin/perl
2###########################################
3# similar
4# Mike Schilli, 2003 (m@perlmeister.com)
5# Fetch books that are similar to a book
6# and spider Amazon to a depth of 1.
7###########################################
8use warnings;
9use strict;
10
11use Net::Amazon;
12use Net::Amazon::Request::ASIN;
13use Data::Dumper;
14
15use Log::Log4perl qw(:easy);
16Log::Log4perl->easy_init($DEBUG);
17
18my $DEPTH = 1;
19
20my $ua = Net::Amazon->new(
21    associate_tag => $ENV{AMAZON_ASSOCIATE_TAG},
22    token         => $ENV{AMAZON_TOKEN},
23    secret_key    => $ENV{AMAZON_SECRET_KEY},
24);
25
26$ARGV[0] = "0201360683";
27die "usage: $0 asin\n(use 0201360683 as an example)\n" unless defined $ARGV[0];
28
29print "Finding similar items (depth=$DEPTH) for:\n",
30      asin($ARGV[0]), "\n\n";
31
32for(similars($ua, $ARGV[0], $DEPTH)) {
33    print $_->title(), "\n";
34}
35
36###########################################
37sub similars {
38###########################################
39    my($ua, $asin, $levels, $found) = @_;
40
41    $found = { } unless defined $found;
42
43    my $req = Net::Amazon::Request::ASIN->new(
44        asin  => $asin,
45        type  => 'heavy',
46    );
47
48        # Response is of type Net::Amazon::ASIN::Response
49    my $resp = $ua->request($req);
50
51    if($resp->is_error()) {
52        warn "Error: ", $resp->message(), "\n";
53        return ();
54    }
55
56    my @new = ();
57
58    ($found->{$asin}) = $resp->properties();
59
60    return values %$found if $levels < 1;
61
62    my $prod = $resp->xmlref()->{Details}->{SimilarProducts}->{Product};
63
64    unless(defined $prod) {
65        warn "$asin doesn't have similar items defined";
66        return values %$found;
67    }
68
69    my @plist = ($prod);
70    @plist = @{$prod} if ref($prod) eq "ARRAY";
71
72    for(@plist) {
73        if(!exists $found->{$_}) {
74            $found->{$_}++;
75            push @new, $_;
76        }
77    }
78
79    for(@new) {
80        similars($ua, $_, $levels-1, $found);
81    }
82
83    return values %$found;
84}
85
86###########################################
87sub asin {
88###########################################
89    my($asin) = @_;
90
91    my $req = Net::Amazon::Request::ASIN->new(
92        asin  => $ARGV[0],
93    );
94
95   # Response is of type Net::Amazon::ASIN::Response
96   my $resp = $ua->request($req);
97
98   if($resp->is_success()) {
99       return $resp->as_string();
100   } else {
101       die("Error: ", $resp->message(), "\n");
102   }
103}
104