Class: CALLR::Api

Inherits:
Object
  • Object
show all
Defined in:
lib/callr.rb

Constant Summary collapse

API_URL =
"https://api.callr.com/json-rpc/v1.1/"

Instance Method Summary collapse

Constructor Details

#initialize(login, password, options = nil) ⇒ Api

Initialization

Parameters:

  • string

    login

  • string

    password



29
30
31
32
33
# File 'lib/callr.rb', line 29

def initialize(, password, options = nil)
  @login = 
  @password = password
  set_options(options)
end

Instance Method Details

#call(method, *params) ⇒ Object

Send a request to CALLR webservice



68
69
70
# File 'lib/callr.rb', line 68

def call(method, *params)
  send(method, params)
end

#send(method, params = [], id = nil) ⇒ Object

Send a request to CALLR webservice



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/callr.rb', line 75

def send(method, params = [], id = nil)
  check_auth()

  json = {
    :id => id.nil? || id.is_a?(Integer) == false ? rand(999 - 100) + 100 : id,
    :jsonrpc => "2.0",
    :method => method,
    :params => params.is_a?(Array) ? params : []
  }.to_json

  uri = URI.parse(API_URL)
  http = http_or_http_proxy(uri)

  req = Net::HTTP::Post.new(uri.request_uri, @headers)
  req.basic_auth(@login, @password)
  req.add_field('User-Agent', "sdk=RUBY; sdk-version=#{SDK_VERSION}; lang-version=#{RUBY_VERSION}; platform=#{RUBY_PLATFORM}")
  req.add_field('CALLR-Login-As', @login_as) unless @login_as.to_s.empty?

  begin
    res = http.request(req, json)
    if res.code.to_i != 200
      raise CallrException.new("HTTP_CODE_ERROR", -1, {:http_code => res.code.to_i, :http_message => res.message})
    end
    return parse_response(res)
  rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Errno::ETIMEDOUT, Errno::ECONNREFUSED,
      Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
    raise CallrException.new("HTTP_EXCEPTION", -2, {:exception => e})
  end
end

#set_login_as(type, target) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/callr.rb', line 44

def (type, target)
  case type
  when 'user'
    type = 'User.login'
  when 'account'
    type = 'Account.hash'
  else
    raise CallrLocalException.new("INVALID_LOGIN_AS_TYPE", 2)
  end

  @login_as = "#{type} #{target}"
end

#set_options(options) ⇒ Object



37
38
39
40
41
42
# File 'lib/callr.rb', line 37

def set_options(options)
  if options.is_a?(Hash)
    options = symbolize_keys(options)
    set_proxy(options[:proxy]) if options.has_key?(:proxy)
  end
end

#set_proxy(proxy) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/callr.rb', line 57

def set_proxy(proxy)
  if proxy.is_a?(String)
    @proxy = URI.parse(proxy)
  else
    raise CallrLocalException.new("PROXY_NOT_STRING", 1)
  end
end