Created
February 6, 2012 22:23
-
-
Save adrienthebo/1755396 to your computer and use it in GitHub Desktop.
Download today's apod image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'fileutils' | |
require 'open-uri' | |
def get_links | |
image_urls = [] | |
# Download latest page | |
puts "Downloading #{$apod_url}" | |
open($apod_url) do |stream| | |
stream.each do |line| | |
if line =~ %r[href="(image/.*)"] | |
image_urls << "#{$apod_url}/#{$1}" | |
end | |
end | |
end | |
image_urls | |
end | |
def get_image(url) | |
image_name = File.join($basedir, File.basename(url)) | |
if File.file? image_name | |
puts "#{image_name} already on disk, not downloading" | |
else | |
begin | |
image = nil | |
puts "Downloading #{url}" | |
open(url) { |stream| image = stream.read } | |
# Save image | |
puts "Saving #{url} as #{image_name}" | |
File.open(image_name, "w") { |f| f.write image } | |
rescue SocketError => e | |
puts e | |
end | |
end | |
end | |
# Prep file structure | |
$basedir = "#{ENV['HOME']}/Pictures" | |
if not File.directory? $basedir | |
FileUtils.mkdir $basedir | |
end | |
$apod_url = "http://apod.nasa.gov/apod" | |
image_urls = get_links | |
unless image_urls.length > 0 | |
$stderr.puts "Could not find image url in current page, bailing out." | |
exit | |
end | |
image_urls.each do |image_url| | |
get_image(image_url) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment