Skip to content

Instantly share code, notes, and snippets.

@jxpx777
Created October 1, 2012 17:32
Show Gist options
  • Select an option

  • Save jxpx777/3813207 to your computer and use it in GitHub Desktop.

Select an option

Save jxpx777/3813207 to your computer and use it in GitHub Desktop.
require 'delayed_job'
require 'net/http'
class ImagesController < ApplicationController
def fetch
components = params[:url].split('/')
url = clean_url(components[0])
filename = components[1] + params[:format]
custom_image_path = File.join("public", "image_cache", "custom", url.host, filename)
default_image_path = File.join("public", "image_cache", "default", url.host, filename)
file = if File.exist?(custom_image_path)
custom_image_path
elsif File.exist?(default_image_path)
default_image_path
else
nil
end
logger.debug("ImagesController#fetch : file is #{file.inspect}")
if file.present?
logger.debug "getting image #{file} for #{url.host}"
logger.debug(File.mtime(file))
logger.debug "local timestamp: #{File.mtime(file)}: \nlast_modified header: #{request.headers['If-Modified-Since']}"
if request.headers['If-Modified-Since'].blank? || File.mtime(file) > DateTime.parse(request.headers['If-Modified-Since'])
send_file file
else
head :status => :not_modified
end
return
end
job = Delayed::Job.find_by_domain(url.host)
unless job
logger.debug("A job for #{url.host} was not found. Enqueuing and returning 404.")
job = Delayed::Job.enqueue(WebImageJob.new(url))
job.domain = url.host
job.save!
else
logger.debug("A job for #{url.host} was already enqueued. Ignoring and returning 404")
end
head :status => :not_found
end
def clean_url(domain)
url= URI.parse domain rescue URI.parse "http://#{domain}"
url= URI.parse "http://#{domain}" if url.is_a? URI::Generic
Net::HTTP.start(url.host) do |http|
resp = http.get('/')
case resp when Net::HTTPRedirection then
url = URI.parse resp['location']
end
end
url
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment