Sha256: 617e99c4da67fc3eb9e0e4f55a16f17959196991ec33a8dc8d907dd1aeb1f8f2

Contents?: true

Size: 1.69 KB

Versions: 3

Compression:

Stored size: 1.69 KB

Contents

# frozen_string_literal: true

module ProxyFetcher
  # Default ProxyFetcher proxy validator that checks either proxy
  # connectable or not. It tries to send HEAD request to default
  # URL to check if proxy can be used (aka connectable?).
  class ProxyValidator
    # Default URL that will be used to check if proxy can be used.
    URL_TO_CHECK = 'https://google.com'.freeze

    # Initialize new ProxyValidator instance
    #
    # @param proxy_addr [String] proxy address or IP
    # @param proxy_port [String, Integer] proxy port
    #
    # @return [ProxyValidator]
    #
    def initialize(proxy_addr, proxy_port)
      uri = URI.parse(URL_TO_CHECK)
      @http = Net::HTTP.new(uri.host, uri.port, proxy_addr, proxy_port.to_i)

      return unless uri.is_a?(URI::HTTPS)

      @http.use_ssl = true
      @http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end

    # Checks if proxy is connectable (can be used to connect
    # resources via proxy server).
    #
    # @return [Boolean]
    #   true if connection to the server using proxy established, otherwise false
    #
    def connectable?
      @http.open_timeout = ProxyFetcher.config.timeout
      @http.read_timeout = ProxyFetcher.config.timeout

      @http.start { |connection| return true if connection.request_head('/') }

      false
    rescue StandardError
      false
    end

    # Short variant to validate proxy.
    #
    # @param proxy_addr [String] proxy address or IP
    # @param proxy_port [String, Integer] proxy port
    #
    # @return [Boolean]
    #   true if connection to the server using proxy established, otherwise false
    #
    def self.connectable?(proxy_addr, proxy_port)
      new(proxy_addr, proxy_port).connectable?
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
proxy_fetcher-0.6.5 lib/proxy_fetcher/utils/proxy_validator.rb
proxy_fetcher-0.6.4 lib/proxy_fetcher/utils/proxy_validator.rb
proxy_fetcher-0.6.3 lib/proxy_fetcher/utils/proxy_validator.rb