Skip to content

Instantly share code, notes, and snippets.

@adrienthebo
Created February 6, 2012 22:23
Show Gist options
  • Save adrienthebo/1755396 to your computer and use it in GitHub Desktop.
Save adrienthebo/1755396 to your computer and use it in GitHub Desktop.
Download today's apod image
#!/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