Sha256: 4f4586dc33053163dc2e485333eba5ba860da7605ec4fe58ebfd95fd834dafc4

Contents?: true

Size: 1.35 KB

Versions: 8

Compression:

Stored size: 1.35 KB

Contents

require "net/https"
require "net/http"
require "uri"
require "timeout"

module SocialAvatarProxy
  class TooManyRedirects < StandardError; end
  class TimeoutError < Timeout::Error; end
  
  class RemoteFileResolver
    def initialize(url, limit = 5)
      # timeout if we have no redirects left
      raise TooManyRedirects 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

8 entries across 8 versions & 1 rubygems

Version Path
social-avatar-proxy-1.0.1 lib/social_avatar_proxy/remote_file_resolver.rb
social-avatar-proxy-1.0.0 lib/social_avatar_proxy/remote_file_resolver.rb
social-avatar-proxy-0.0.9 lib/social_avatar_proxy/remote_file_resolver.rb
social-avatar-proxy-0.0.8 lib/social_avatar_proxy/remote_file_resolver.rb
social-avatar-proxy-0.0.7 lib/social_avatar_proxy/remote_file_resolver.rb
social-avatar-proxy-0.0.6 lib/social_avatar_proxy/remote_file_resolver.rb
social-avatar-proxy-0.0.5 lib/social_avatar_proxy/remote_file_resolver.rb
social-avatar-proxy-0.0.4 lib/social_avatar_proxy/remote_file_resolver.rb