Class: RingCentralSdk::REST::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/ringcentral_sdk/rest/client.rb

Overview

Client is the RingCentral REST API client class which handles HTTP requests with built-in OAuth handling

Constant Summary collapse

ACCESS_TOKEN_TTL =

10 minutes

600
REFRESH_TOKEN_TTL =

10 hours

36_000
REFRESH_TOKEN_TTL_REMEMBER =

1 week

604_800
ACCOUNT_PREFIX =
'/account/'.freeze
ACCOUNT_ID =
'~'.freeze
AUTHZ_ENDPOINT =
'/restapi/oauth/authorize'.freeze
TOKEN_ENDPOINT =
'/restapi/oauth/token'.freeze
REVOKE_ENDPOINT =
'/restapi/oauth/revoke'.freeze
API_VERSION =
'v1.0'.freeze
URL_PREFIX =
'/restapi'.freeze
DEFAULT_LANGUAGE =
'en-us'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize {|config| ... } ⇒ Client

Returns a new instance of Client.

Yields:

Raises:

  • (ArgumentError)


28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/ringcentral_sdk/rest/client.rb', line 28

def initialize
  init_attributes

  raise ArgumentError, 'Config block not given' unless block_given?
  @config = RingCentralSdk::REST::Configuration.new
  yield config
  @config.inflate

  @oauth2client = new_oauth2_client

  # Remove Password Grant
  # unless @config.username.to_s.empty?
  #  authorize_password @config.username, @config.extension, @config.password
  # end

  authorize_jwt(@config.jwt) unless @config.jwt.to_s.empty?

  @messages = RingCentralSdk::REST::Messages.new self
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



26
27
28
# File 'lib/ringcentral_sdk/rest/client.rb', line 26

def config
  @config
end

#httpObject (readonly)

Returns the value of attribute http.



26
27
28
# File 'lib/ringcentral_sdk/rest/client.rb', line 26

def http
  @http
end

#loggerObject (readonly)

Returns the value of attribute logger.



26
27
28
# File 'lib/ringcentral_sdk/rest/client.rb', line 26

def logger
  @logger
end

#messagesObject (readonly)

Returns the value of attribute messages.



26
27
28
# File 'lib/ringcentral_sdk/rest/client.rb', line 26

def messages
  @messages
end

#oauth2clientObject (readonly)

Returns the value of attribute oauth2client.



26
27
28
# File 'lib/ringcentral_sdk/rest/client.rb', line 26

def oauth2client
  @oauth2client
end

#user_agentObject (readonly)

Returns the value of attribute user_agent.



26
27
28
# File 'lib/ringcentral_sdk/rest/client.rb', line 26

def user_agent
  @user_agent
end

Instance Method Details

#_add_redirect_uri(opts = {}) ⇒ Object



103
104
105
106
107
108
# File 'lib/ringcentral_sdk/rest/client.rb', line 103

def _add_redirect_uri(opts = {})
  if !opts.key?(:redirect_uri) && !@config.redirect_url.to_s.empty?
    opts[:redirect_uri] = @config.redirect_url.to_s
  end
  opts
end

#api_keyObject



186
187
188
# File 'lib/ringcentral_sdk/rest/client.rb', line 186

def api_key
  Base64.encode64("#{@config.client_id}:#{@config.client_secret}").gsub(/\s/, '')
end

#authorize_code(code, params = {}) ⇒ Object



97
98
99
100
101
# File 'lib/ringcentral_sdk/rest/client.rb', line 97

def authorize_code(code, params = {})
  token = @oauth2client.auth_code.get_token(code, _add_redirect_uri(params))
  set_token(token)
  token
end

#authorize_jwt(jwt) ⇒ Object Also known as: authorize, login

def authorize_password(username, extension = ”, password = ”, params = {})

token = @oauth2client.password.get_token(username, password, {
  extension: extension,
  headers: { 'Authorization' => 'Basic ' + api_key }
}.merge(params))
set_token token
token

end



119
120
121
122
123
124
125
126
# File 'lib/ringcentral_sdk/rest/client.rb', line 119

def authorize_jwt(jwt)
  token = @oauth2client.get_token({
    grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
    assertion: jwt
  })
  set_token token
  token
end

#authorize_url(opts = {}) ⇒ Object



93
94
95
# File 'lib/ringcentral_sdk/rest/client.rb', line 93

def authorize_url(opts = {})
  @oauth2client.auth_code.authorize_url(_add_redirect_uri(opts))
end

#build_user_agentObject



235
236
237
238
239
240
241
242
# File 'lib/ringcentral_sdk/rest/client.rb', line 235

def build_user_agent
  ua = "ringcentral-sdk-ruby/#{RingCentralSdk::VERSION} %s/%s %s" % [
    (RUBY_ENGINE rescue nil || 'ruby'),
    RUBY_VERSION,
    RUBY_PLATFORM
  ]
  ua.strip
end

#create_subscriptionObject



244
245
246
# File 'lib/ringcentral_sdk/rest/client.rb', line 244

def create_subscription
  RingCentralSdk::REST::Subscription.new self
end

#create_url(url, add_server = false, add_method = nil, add_token = false) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/ringcentral_sdk/rest/client.rb', line 57

def create_url(url, add_server = false, add_method = nil, add_token = false)
  built_url = ''
  has_http = !url.index('http://').nil? && !url.index('https://').nil?

  built_url += @config.server_url if add_server && !has_http

  if url.index(URL_PREFIX).nil? && !has_http
    built_url += URL_PREFIX + '/' + API_VERSION + '/'
  end

  if url.index('/') == 0
    if built_url =~ %r{/$}
      built_url += url.gsub(%r{^/+}, '')
    else
      built_url += url
    end
  else # no /
    if built_url =~ %r{/$}
      built_url += url
    else
      built_url += '/' << url
    end
  end

  built_url
end

#create_urls(urls, add_server = false, add_method = nil, add_token = false) ⇒ Object

Raises:

  • (ArgumentError)


84
85
86
87
88
89
90
91
# File 'lib/ringcentral_sdk/rest/client.rb', line 84

def create_urls(urls, add_server = false, add_method = nil, add_token = false)
  raise(ArgumentError, 'URLs is not an array') unless urls.is_a? Array
  built_urls = []
  urls.each do |url|
    built_urls.push(create_url(url, add_server, add_method, add_token))
  end
  built_urls
end

#inflate_request(req_faraday, req_sdk) ⇒ Object



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/ringcentral_sdk/rest/client.rb', line 218

def inflate_request(req_faraday, req_sdk)
  req_faraday.url req_sdk.url
  req_faraday.body = req_sdk.body if req_sdk.body
  if req_sdk.params.is_a? Hash
    req_sdk.params.each { |k, v| req_faraday.params[k] = v }
  end
  if req_sdk.headers.is_a? Hash
    req_sdk.headers.each { |k, v| req_faraday.headers[k] = v }
  end

  ct = req_sdk.content_type
  if !ct.nil? && !ct.to_s.strip.empty?
    req_faraday.headers['Content-Type'] = ct.to_s
  end
  req_faraday
end

#init_attributesObject



48
49
50
51
# File 'lib/ringcentral_sdk/rest/client.rb', line 48

def init_attributes
  @http = nil
  @user_agent = build_user_agent
end

#new_oauth2_clientObject



166
167
168
169
170
171
172
173
174
# File 'lib/ringcentral_sdk/rest/client.rb', line 166

def new_oauth2_client
  OAuth2::Client.new(
    @config.client_id,
    @config.client_secret,
    site: @config.server_url,
    authorize_url: @config.authorize_url,
    token_url: TOKEN_ENDPOINT
  )
end

#send_request(request_sdk = {}) ⇒ Object



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/ringcentral_sdk/rest/client.rb', line 190

def send_request(request_sdk = {})
  if request_sdk.is_a? Hash
    request_sdk = RingCentralSdk::REST::Request::Simple.new request_sdk
  elsif !request_sdk.is_a? RingCentralSdk::REST::Request::Base
    raise ArgumentError, 'Request is not a RingCentralSdk::REST::Request::Base'
  end

  method = request_sdk.method.to_s.downcase
  method = 'get' if method.empty?

  res = nil

  case method
  when 'delete'
    res = @http.delete { |req| req = inflate_request(req, request_sdk) }
  when 'get'
    res = @http.get { |req| req = inflate_request(req, request_sdk) }
  when 'post'
    res = @http.post { |req| req = inflate_request(req, request_sdk) }
  when 'put'
    res = @http.put { |req| req = inflate_request(req, request_sdk) }
  else
    raise "method [#{method}] not supported"
  end

  res
end

#set_oauth2_client(client = nil) ⇒ Object



176
177
178
179
180
181
182
183
184
# File 'lib/ringcentral_sdk/rest/client.rb', line 176

def set_oauth2_client(client = nil)
  if client.nil?
    @oauth2client = new_oauth2_client
  elsif client.is_a? OAuth2::Client
    @oauth2client = client
  else
    raise ArgumentError, 'client is not an OAuth2::Client'
  end
end

#set_token(token) ⇒ Object



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/ringcentral_sdk/rest/client.rb', line 132

def set_token(token)
  if token.is_a? Hash
    token = OAuth2::AccessToken.from_hash(@oauth2client, token)
  end

  unless token.is_a? OAuth2::AccessToken
    raise 'Token is not a OAuth2::AccessToken'
  end

  @http = Faraday.new(url: api_version_url) do |conn|
    conn.request :oauth2_refresh, token
    conn.request :multipart
    conn.request :url_encoded
    conn.request :json
    conn.headers['User-Agent'] = @user_agent
    if @config.headers.is_a? Hash
      @config.headers.each do |k, v|
        conn.headers[k] = v
      end
    end
    conn.headers['RC-User-Agent'] = @user_agent
    conn.headers['SDK-User-Agent'] = @user_agent
    conn.response :json, content_type: /\bjson$/
    conn.response :logger, @config.logger
    if @config.retry
      conn.use FaradayMiddleware::Request::Retry, @config.retry_options
    end
    conn.adapter Faraday.default_adapter
  end

  token_string = MultiJson.encode token.to_hash
  @config.logger.info("SET_TOKEN: #{token_string}")
end

#tokenObject



128
129
130
# File 'lib/ringcentral_sdk/rest/client.rb', line 128

def token
  @http ? @http.builder.app.oauth2_token : nil
end