module Wallzilla::Fetcher

Constants

WRONG_API_KEY

Public Instance Methods

download_photo(url) click to toggle source
# File lib/wallzilla/fetcher.rb, line 40
def download_photo(url)
  uri = URI.parse(url)
  Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http|
    resp = http.get(uri.path)
    file = Tempfile.new(["flickr", ".jpg"], encoding: "binary")
    file.binmode
    file.write(resp.body)
    file.flush
    file
  end
end
fetch(keyword) click to toggle source

Downoads image to tempfile for the given keyword returns:

file handler if image found and downloaded
nil if no image found
# File lib/wallzilla/fetcher.rb, line 15
def fetch(keyword)
  if image = search_image(keyword)
    download_photo(image)
  else
    nil
  end
end
search_image(keyword) click to toggle source
# File lib/wallzilla/fetcher.rb, line 23
def search_image(keyword)
  url = flickr_search_url(keyword)
  uri = URI.parse(url)
  response = Net::HTTP.get_response(uri)

  result = JSON.parse(response.body)

  if (100...117).cover?(result["code"])
    fail(result["message"])
  end

  photos = result["photos"]["photo"]
  return nil if photos.empty?

  photos.first[photo_size_code]
end

Private Instance Methods

flickr_api_key() click to toggle source
# File lib/wallzilla/fetcher.rb, line 71
def flickr_api_key
  Wallzilla::Runner.flickr_api_key
end
flickr_search_url(keyword, key = flickr_api_key) click to toggle source
# File lib/wallzilla/fetcher.rb, line 54
def flickr_search_url(keyword, key = flickr_api_key)
  "https://api.flickr.com/services/rest/?method=flickr.photos.search" +
    "&api_key=#{key}" +
    "&text=#{keyword}" +
    "&content_type=1" + # Only photos
    "&sort=interestingness-desc" +
    "&extras=#{photo_size_code}" +
    "&media=photos" +
    "&per_page=1" +
    "&format=json" +
    "&nojsoncallback=1"
end
photo_size_code() click to toggle source
# File lib/wallzilla/fetcher.rb, line 67
def photo_size_code
  "url_c"
end