collect_apod 6.69 KB
Newer Older
Dave Morriss's avatar
Dave Morriss committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
#!/usr/bin/env perl
#===============================================================================
#
#         FILE: collect_apod
#
#        USAGE: ./collect_apod [YYMMDD]
#
#  DESCRIPTION: Downloads the current Astronomy Picture of the Day or that
#               relating to the formatted date provided as an argument. In
#               this context "current" can mean two URLs: .../astropix.html or
#               .../apYYMMDD.html. We now *do not* download the
#               .../astropix.html version since it has a different HTML
#               layout.
#
#      OPTIONS: ---
# REQUIREMENTS: ---
#         BUGS: ---
#        NOTES: This version has been rewritten using HTML::TreeBuilder to
#               parse the HTML, and the logic has been improved.
#       AUTHOR: Dave Morriss (djm), Dave.Morriss@gmail.com
#      VERSION: 0.1.2
#      CREATED: 2012-05-06 18:31:13
#     REVISION: 2015-01-04 10:32:44
#
#===============================================================================

use 5.010;
use strict;
use warnings;
use utf8;

use Carp;
use LWP::UserAgent;
use DateTime;
use HTML::TreeBuilder 5 -weak;

use Image::Magick;

use File::Temp;

#
# Version number (manually incremented)
#
our $VERSION = '0.1.2';

#
# Set to 0 to be more silent
#
my $DEBUG = 1;

#
# Script name
#
( my $PROG = $0 ) =~ s|.*/||mx;

#-------------------------------------------------------------------------------
# Edit this to your needs
#-------------------------------------------------------------------------------
#
# Where the script will download the picture. Edit this to where you want
#
my $image_base = "$ENV{HOME}/Backgrounds/apod";

#-------------------------------------------------------------------------------
# Nothing needs editing below here
#-------------------------------------------------------------------------------

#
# Get the argument or default it
#
my $arg = shift;
unless ( defined($arg) ) {
    #
    # APOD wants a date in YYMMDD format
    #
    my $dt = DateTime->now;
    $arg = sprintf( "%02i%02i%02i",
        substr( $dt->year, -2 ),
        $dt->month, $dt->day );
}

#
# Make an URL depending on the argument
#
my $apod_base = "http://apod.nasa.gov/apod";
my $apod_URL  = "$apod_base/ap$arg.html";

#
# General declarations
#
my ( $image_URL, $image_file, $newfile );
my ( $tree, $title, $add_title, $fh, $fname );
my ( $url, $element, $attr, $tag );

#
# Enable Unicode mode
#
binmode STDOUT, ":encoding(UTF-8)";
binmode STDERR, ":encoding(UTF-8)";

if ($DEBUG) {
    print "Base URL:   $apod_base\n";
    print "APOD URL:   $apod_URL\n";
    print "Image base: $image_base\n";
    print "\n";
}

#
# Get the page, pretending to be some unknown User Agent
#
my $ua = LWP::UserAgent->new;
$ua->agent("MyApp/0.1");

my $req = HTTP::Request->new( GET => $apod_URL );

my $res = $ua->request($req);
if ( $res->is_success ) {
    print "GET request successful\n" if $DEBUG;

    #
    # Parse the HTML we got back
    #
    $tree = HTML::TreeBuilder->new;
    $tree->parse_content( $res->content_ref );

    #
    # Get the title
    #
    if ( $title = $tree->look_down( _tag => 'title' ) ) {
        $title = $title->as_trimmed_text();
        if ($DEBUG) {
            print "Found title: $title\n" if $title;
        }
        $add_title = defined($title) && length($title) > 0;
    }
    else {
        $title     = "No title";
        $add_title = 0;
    }

    #
    # Look for the image. This is expected to be the href attribute of an <a>
    # tag. The image we see on the page is merely a link to this (usually)
    # larger image.
    #
    for ( @{ $tree->extract_links('a') } ) {
        ( $url, $element, $attr, $tag ) = @$_;
        if ($DEBUG) {
            print "Found: $url\n" if $url;
        }
        last unless defined($url);
        last if ( $url =~ /\.(jpg|png)$/i );
    }

    #
    # Abort if no image (it might be a video or a GIF)
    #
    die "Image URL not found\n"
        unless defined($url)
        && $url =~ /\.(jpg|png)$/i;

    $image_URL = "$apod_base/$url";

    #
    # Extract the final part for the file name. We usually get a JPEG,
    # sometimes with a shouty extension, which we change. The image we'll make
    # with the title in it will be a PNG.
    #
    ( $image_file = $image_URL ) =~ s|.*/||mx;
    ( $image_file = "$image_base/$image_file" ) =~ s/JPG$/jpg/mx;
    ( $newfile    = $image_file ) =~ s/\.[^.]*$/.png/;

    if ($DEBUG) {
        print "Image URL:      $image_URL\n";
        print "Image file:     $image_file\n";
        print "Annotated file: $newfile\n";
    }

    #
    # Abort if the file already exists (the script already ran?)
    #
    die "File $image_file already exists\n" if ( -f $image_file );
    die "File $newfile already exists\n"    if ( -f $newfile );

    #
    # Set up the temporary file (assuming there's a /tmp directory - this is
    # UNIX isn't it?)
    #
    $fh = File::Temp->new( TEMPLATE => 'apod_image_XXXXXX', DIR => '/tmp' );
    $fname = $fh->filename;

    #
    # Set up the GET request for the image
    #
    $req = HTTP::Request->new( GET => $image_URL );

    #
    # Download the image to the temporary file
    #
    $res = $ua->request( $req, $fname );
    if ( $res->is_success ) {
        print "Downloaded to $fname\n" if $DEBUG;

        #
        # Prepare for the annotation of the file
        #
        my $image = Image::Magick->new;

        #
        # Read the temporary file
        #
        my $imres = $image->Read($fname);
        carp "$imres" if $imres;

        #
        # Apply the title if there is one
        #
        if ($add_title) {
            $imres = $image->Annotate(
                font       => 'kai.ttf',
                pointsize  => 20,
                fill       => 'white',
                undercolor => 'black',
                text       => $title,
                gravity    => 'North'
            );
            carp "$imres" if $imres;
        }

        #
        # Write the result to the transformed image file name
        #
        $imres = $image->Write($newfile);
        carp "$imres" if $imres;

        #
        # Report the output file - if it exists
        #
        if ( -e $newfile ) {
           #
           # The null string here is for the Perl compiler which can't seem to
           # parse this without it
           #
            print "", ( $add_title ? "Annotated" : "Un-annotated" ),
                " image in $newfile\n";
        }
        else {
            print "Unable to write $newfile\n";
        }

    }
    else {
        #
        # The image download failed
        #
        die $res->status_line, " ($image_URL)\n";
    }

}
else {
    #
    # We failed to get the web page
    #
    die $res->status_line, " ($apod_URL)\n";
}

exit;

# vim: syntax=perl:ts=8:sw=4:et:ai:tw=78:fo=tcrqn21:fdm=marker