Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
ballpark_api / lib / ballpark_api / request.rb
Size: Mime:
require 'oauth2'
module BallparkApi
  # Defines HTTP request methods
  module Request
    # Perform an HTTP GET request
    def get(path, options = {})
      request(:get, path, options)
    end

    # Perform an HTTP POST request
    def post(path, options = {})
      request(:post, path, options)
    end

    def get_token(client_email, client_password, client_id, client_secret)
      conn = Faraday.new
      resp = conn.post "https://#{api_site}/session", 'session[email]' => client_email, 'session[password]' => client_password
      if resp.status == 302 and resp.headers['set-cookie'] =~ /(user_credentials=[^;]+)/
        user_crs = $1
        if resp.headers['set-cookie'] =~ /(_ballpark_app_session=[^;]+)/
          cookies = "#{$1}; #{user_crs}"
          callback_uri = "urn:ietf:wg:oauth:2.0:oob"
          client = OAuth2::Client.new(client_id, client_secret, site: "http://#{api_site}")
          url = client.auth_code.authorize_url(:redirect_uri => callback_uri, :response_type => 'code')
          resp2 = conn.get url do |req|
            req.headers['Cookie'] = cookies
          end
          if resp2.status == 302 and resp2.headers['Location'] =~ %r{authorize/(.+)$}
            token = client.auth_code.get_token($1, :redirect_uri => callback_uri)
          end
        end
      end
    end

    def refresh_token(client_id, client_secret, r_token)
      client = OAuth2::Client.new(client_id, client_secret, site: "http://#{api_site}")
      token =  OAuth2::AccessToken.new(client, '')
      token.refresh_token = r_token
      token.refresh!
    end

    private

    # Perform an HTTP request
    def request(method, methodPath, options)
      path = api_version + methodPath
      response = connection.send(method) do |request|
        case method
        when :get
          formatted_options = format_options(options)
          request.url(path,formatted_options)
        when :post, :put
          request.headers['Content-Type'] = 'application/json'
          request.body = options.to_json unless options.empty?
          request.url(path)
        end
      end

      Response.create(response.body)
    end

    def format_options(options)
      options[:access_token] = api_key unless options.has_key?(:access_token)
      return options
    end

    # TODO: Replace or remove this method if necessary.
    # Format the fields to a format that the BallparkApi likes
    # @param [Array or String] fields can be specified as an Array or String
    # @return String
    def format_fields(fields)
      if fields.instance_of?(Array)
        return fields.join(",")
      elsif fields.instance_of?(String)
        return fields
      end
    end

  end
end