Sha256: 5cb53c4295ee5f0a78c60fbdb5b0f2232d12a163144508ce6f0aa20c1edd707b

Contents?: true

Size: 912 Bytes

Versions: 3

Compression:

Stored size: 912 Bytes

Contents

require "json"
require "mechanize"

module ADPDownloader
  class HttpClient
    def initialize
      headers = {"Accept" => "application/json, text/plain, */*"}
      @agent = Mechanize.new {|a| a.request_headers = headers}
      res = _login(Config.credentials)
      _raise_on_error(res)
    end

    def get(url)
      JSON.parse(download(url))
    end

    def post(url, data)
      @agent.post(url, data)
    end

    def download(url)
      @agent.get(url).body
    end

    private
    def _login(creds)
      @agent.post(LOGIN_URL, {
        "target" => TARGET_URL,
        "user" => creds[:username],
        "password" => creds[:password],
      })
    end

    def _raise_on_error(res)
      uri = res.uri.to_s.downcase
      if not uri.start_with? TARGET_URL or uri.include? "login"
        raise "Unable to authenticate: make sure your username and password are correct"
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
adp-downloader-0.2.4 lib/adp-downloader/http_client.rb
adp-downloader-0.2.3 lib/adp-downloader/http_client.rb
adp-downloader-0.2.2 lib/adp-downloader/http_client.rb