Skip to content

Instantly share code, notes, and snippets.

@james
Forked from russss/modis-desktop.rb
Created January 11, 2010 09:53
Show Gist options
  • Save james/274116 to your computer and use it in GitHub Desktop.
Save james/274116 to your computer and use it in GitHub Desktop.
#!/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 = 1440
Y = 900
# Offset within image
XOFF = 0
YOFF = 0
t = DateTime.now
# 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.#{t}.jpg"
# Minimum image size - sometimes white or partially white images crop up.
IMG_MIN_SIZE = 4000000
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
puts "converting..."
`convert #{tmpfile} -resize '#{X+XOFF}' -crop '#{X}x#{Y}+#{XOFF}+#{YOFF}' -sharpen 1 #{DEST}`
puts "setting bg to #{File.expand_path(DEST)}"
`/usr/bin/osascript << END
tell application "Finder"
set desktop picture to POSIX file "#{File.expand_path(DEST)}"
end tell
END`
# Clean images older than 1 day. Yeah, it's ugly.
`find . -name 'modistmp.*.jpg' -mtime +1 | xargs rm -f`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment