JGaudette
1/15/2010 - 6:05 PM

modis-desktop.rb

#!/usr/bin/ruby
# Download NASA MODIS imagery and use it as a desktop background.
# You'll need ImageMagick installed for this to work.
require 'date'
require 'net/http'

# Screen width/height
X = 2580
Y = 1024

# Offset within image
XOFF = 0
YOFF = 500

# The default image is of GB - it may require some fiddling to customize for your area.
IMAGE = "Europe_2_01"
# 1km, 500m, or 250m per pixel. Europe_2_01 is 1150km wide, so set this to 250m if your
# target width is <2300px, to save your bandwidth and NASA's.
RES = "250m"
DEST = "modis.jpg"
# Minimum image size - sometimes white or partially white images crop up.
IMG_MIN_SIZE = 4000000

t = DateTime.now

tmpfile = ''
Net::HTTP.start('rapidfire.sci.gsfc.nasa.gov') { |http|
  # Aqua takes images of the afternoon:
  url = "/subsets/tmp/#{IMAGE}.#{t.year}#{t.yday.to_s.rjust(3, '0')}.aqua.#{RES}.jpg"
  res = http.head(url)
  if res.code != '200' or res["Content-Length"].to_i < IMG_MIN_SIZE
    # Terra = this morning
    url = "/subsets/tmp/#{IMAGE}.#{t.year}#{t.yday.to_s.rjust(3, '0')}.terra.#{RES}.jpg"
    res = http.head(url)
  end
  if res.code != '200' or res["Content-Length"].to_i < IMG_MIN_SIZE
    # Yesterday's Aqua image
    url = "/subsets/tmp/#{IMAGE}.#{t.year}#{(t.yday - 1).to_s.rjust(3, '0')}.aqua.#{RES}.jpg"
    res = http.head(url)
  end
  if res.code != '200' or res["Content-Length"].to_i < IMG_MIN_SIZE
    raise Exception.new("No image found!")
  end

  tmpfile = "modistmp.#{res["Etag"].gsub(/"/, '')}.jpg"
  if File.exists?(tmpfile)
    puts "We already have the most up-to-date image - quitting"
    exit
  end

  puts "Fetching #{url} to #{tmpfile}..."
  res = http.get(url)
  File.open(tmpfile, 'w') { |f| f.write(res.body) }
}

# Resize
`convert #{tmpfile} -resize '#{X+XOFF}' -crop '#{X}x#{Y}+#{XOFF}+#{YOFF}' -sharpen 1 #{DEST}`

# Set the Gnome background:
`gconftool-2 -t str --set /desktop/gnome/background/picture_filename #{File.expand_path(DEST)}`

# Clean images older than 1 day. Yeah, it's ugly.
`find . -name 'modistmp.*.jpg' -mtime +1 | xargs rm -f`