]> git.donarmstrong.com Git - bin.git/blob - get_coverart
add get_coverart
[bin.git] / get_coverart
1 #! /usr/bin/perl
2 # get_coverart downloads coverart, and is released
3 # under the terms of the GPL version 2, or any later version, at your
4 # option. See the file README and COPYING for more information.
5 # Copyright 2011 by Don Armstrong <don@donarmstrong.com>.
6
7
8 use warnings;
9 use strict;
10
11 use Getopt::Long;
12 use Pod::Usage;
13
14 =head1 NAME
15
16 get_coverart -- download coverart
17
18 =head1 SYNOPSIS
19
20 get_coverart --asin B000NIIUX8 --cover cover.jpg [options]
21
22  Options:
23   --asin Amazon image ID
24   --cover file name to save cover to
25   --debug, -d debugging level (Default 0)
26   --help, -h display this help
27   --man, -m display manual
28
29 =head1 OPTIONS
30
31 =over
32
33 =item B<--debug, -d>
34
35 Debug verbosity. (Default 0)
36
37 =item B<--help, -h>
38
39 Display brief usage information.
40
41 =item B<--man, -m>
42
43 Display this manual.
44
45 =back
46
47 =head1 EXAMPLES
48
49 get_coverart --asin B000NIIUX8 --cover cover.jpg
50 get_coverart --asin B000NIIUX8 > cover.jpg
51
52 =cut
53
54
55 use URI::Escape;
56 use WWW::Mechanize;
57 use HTTP::Cookies;
58 use IO::Dir;
59 use IO::File;
60 use vars qw($DEBUG);
61
62 my %options = (debug           => 0,
63                help            => 0,
64                man             => 0,
65                );
66
67 GetOptions(\%options,
68            'asin=s',
69            'cover=s',
70            'debug|d+','help|h|?','man|m');
71
72 pod2usage() if $options{help};
73 pod2usage({verbose=>2}) if $options{man};
74
75 $DEBUG = $options{debug};
76
77 my @USAGE_ERRORS;
78 if (not exists $options{asin}) {
79     push @USAGE_ERRORS,"You must give an ASIN.";
80 }
81
82 pod2usage(join("\n",@USAGE_ERRORS)) if @USAGE_ERRORS;
83
84
85 my $wfh = \*STDOUT;
86 if (exists $options{cover}) {
87     $wfh = IO::File->new($options{cover},O_WRONLY|O_CREAT|O_EXCL) or die "Unable to create file: $options{cover}: $!";
88 }
89
90 my $m = WWW::Mechanize->new();
91
92 mm_get($m,"http://www.amazon.com/gp/product/$options{asin}");
93 if ($m->status() != 200) {
94     print STDERR "Unable to get product for asin $options{asin}";
95     exit 1;
96 }
97 my $content = $m->content();
98 my $parser = HTML::TokeParser->new(\$content);
99 my $image;
100 while (my $token = $parser->get_tag('img')) {
101     if (exists $token->[1]{id} and $token->[1]{id} eq 'prodImage') {
102         $image = $token->[1]{src};
103     }
104 }
105 mm_get($m,$image);
106 print {$wfh} $m->content;
107
108
109 sub mm_get{
110     my ($m,$url) = @_;
111     my $rerun = 8;
112     my $return;
113     do {
114         eval {
115             $return = $m->get($url);
116         };
117     } while ($@ and
118              ($rerun-- > 0) and sleep 5);
119     return $return;
120 }
121
122
123 __END__