Sha256: 205b94c93f50e286c9a11a783c561e9886b8eb8943f6bb588e3099938c832c58

Contents?: true

Size: 1.36 KB

Versions: 4

Compression:

Stored size: 1.36 KB

Contents

require "social_avatar_proxy/timeout_error"
require "social_avatar_proxy/too_many_redirects_error"
require "net/https"
require "net/http"
require "uri"
require "timeout"

module SocialAvatarProxy  
  class RemoteFileResolver
    def initialize(url, limit = 5)
      # timeout if we have no redirects left
      raise TooManyRedirectsError if limit <= 0
      # store the limit and URL
      @url, @redirect_limit = url, limit
    end
    
    def resolve
      response = Timeout::timeout(30) do
        perform_request
      end
      
      # if this is a redirect
      if response.kind_of?(Net::HTTPRedirection)
        # follow the redirect
        resolver = self.class.new(response["location"], @redirect_limit - 1)
        resolver.resolve
      # if this is not a redirect
      else
        # return the response
        response
      end
    rescue Timeout::Error => e
      raise TimeoutError, e.message, e.backtrace
    end
    
    private
    def uri
      URI.parse(@url)
    end
    
    def perform_request
      http = Net::HTTP.new(uri.host, uri.port)
      # enable SSL without verification if on HTTPS
      if uri.scheme == "https"
        http.use_ssl = true
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end
      # create the request
      request = Net::HTTP::Get.new(uri.request_uri)
      # run the request
      http.request(request)
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
social-avatar-proxy-2.0.1 lib/social_avatar_proxy/remote_file_resolver.rb
social-avatar-proxy-2.0.0 lib/social_avatar_proxy/remote_file_resolver.rb
social-avatar-proxy-1.2.0 lib/social_avatar_proxy/remote_file_resolver.rb
social-avatar-proxy-1.1.0 lib/social_avatar_proxy/remote_file_resolver.rb