Skip to content

Instantly share code, notes, and snippets.

@xaicron
Created January 16, 2011 10:41
Show Gist options
  • Save xaicron/781692 to your computer and use it in GitHub Desktop.
Save xaicron/781692 to your computer and use it in GitHub Desktop.
#!/usr/bin/evn perl
use strict;
use warnings;
use LWP::UserAgent;
use JSON;
use Getopt::Long qw/GetOptions/;
use Encode;
use Term::Encoding qw/term_encoding/;
use Sub::Retry;
my $save_dir = '.';
GetOptions(
'help|h!' => sub { usage() },
'dir|d=s' => \$save_dir,
) or usage();
my $id = shift || usage();
my $enc = term_encoding;
my $api_url = 'http://imeero.com/api/entry';
my $strage_url = 'http://storage.imeero.com/photos';
my $ua = LWP::UserAgent->new;
main: {
init();
my $info = get_info($id);
my $title = encode $enc => decode_utf8 $info->{entry}{title};
my $max = $info->{entry}{image_length};
printf "Fetch %s\n", $title;
for my $i (0..($max - 1)) {
download($id, $i);
sleep 1;
}
}
sub init {
mkdir $save_dir unless -d $save_dir;
chdir $save_dir or die $!;
}
sub get_info {
my $id = shift;
my $json = retry 3, 1, sub {
my $res = $ua->get("$api_url?id=$id");
$res->is_success or die "\n", $res->status_line;
$res->content;
};
return decode_json $json;
}
sub download {
my ($id, $count) = @_;
my $file = "$count.jpg";
my $url = "$strage_url/$id/$file";
printf "--> Getting: %s ...", $url;
my $res = retry 3, 1, sub {
my $res = $ua->get($url);
$res->is_success or die "\n", $res->status_line;
$res;
};
warn "\n contentn type miss match! ($url)\n" unless $res->content_type =~ /jpe?g/;
open my $fh, '>:raw', $file or die "can't create $file $!";
print $fh $res->content;
close $fh;
print " done.\n";
}
sub usage {
print << 'USAGE';
usage: imeero_getter.pl [options] id
options:
-d, --dir save directory
USAGE
exit 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment