Class: Intercom::Request

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, net_http_method) ⇒ Request

Returns a new instance of Request.


8
9
10
11
12
# File 'lib/intercom/request.rb', line 8

def initialize(path, net_http_method)
  self.path = path
  self.net_http_method = net_http_method
  self.handle_rate_limit = false
end

Instance Attribute Details

#handle_rate_limitObject

Returns the value of attribute handle_rate_limit


6
7
8
# File 'lib/intercom/request.rb', line 6

def handle_rate_limit
  @handle_rate_limit
end

#net_http_methodObject

Returns the value of attribute net_http_method


6
7
8
# File 'lib/intercom/request.rb', line 6

def net_http_method
  @net_http_method
end

#pathObject

Returns the value of attribute path


6
7
8
# File 'lib/intercom/request.rb', line 6

def path
  @path
end

#rate_limit_detailsObject

Returns the value of attribute rate_limit_details


6
7
8
# File 'lib/intercom/request.rb', line 6

def rate_limit_details
  @rate_limit_details
end

Class Method Details

.append_query_string_to_url(url, params) ⇒ Object


190
191
192
193
194
# File 'lib/intercom/request.rb', line 190

def self.append_query_string_to_url(url, params)
  return url if params.empty?
  query_string = params.map { |k, v| "#{k.to_s}=#{CGI::escape(v.to_s)}" }.join('&')
  url + "?#{query_string}"
end

.default_headersObject


45
46
47
# File 'lib/intercom/request.rb', line 45

def self.default_headers
  {'Accept-Encoding' => 'gzip, deflate', 'Accept' => 'application/vnd.intercom.3+json', 'User-Agent' => "Intercom-Ruby/#{Intercom::VERSION}"}
end

.delete(path, params) ⇒ Object


30
31
32
# File 'lib/intercom/request.rb', line 30

def self.delete(path, params)
  new(path, method_with_body(Net::HTTP::Delete, path, params))
end

.get(path, params) ⇒ Object


22
23
24
# File 'lib/intercom/request.rb', line 22

def self.get(path, params)
  new(path, Net::HTTP::Get.new(append_query_string_to_url(path, params), default_headers))
end

.method_with_body(http_method, path, params) ⇒ Object


38
39
40
41
42
43
# File 'lib/intercom/request.rb', line 38

def self.method_with_body(http_method, path, params)
  request = http_method.send(:new, path, default_headers)
  request.body = params.to_json
  request["Content-Type"] = "application/json"
  request
end

.post(path, form_data) ⇒ Object


26
27
28
# File 'lib/intercom/request.rb', line 26

def self.post(path, form_data)
  new(path, method_with_body(Net::HTTP::Post, path, form_data))
end

.put(path, form_data) ⇒ Object


34
35
36
# File 'lib/intercom/request.rb', line 34

def self.put(path, form_data)
  new(path, method_with_body(Net::HTTP::Put, path, form_data))
end

Instance Method Details

#client(uri) ⇒ Object


49
50
51
52
53
54
55
56
57
58
59
# File 'lib/intercom/request.rb', line 49

def client(uri)
  net = Net::HTTP.new(uri.host, uri.port)
  if uri.is_a?(URI::HTTPS)
    net.use_ssl = true
    net.verify_mode = OpenSSL::SSL::VERIFY_PEER
    net.ca_file = File.join(File.dirname(__FILE__), '../data/cacert.pem')
  end
  net.read_timeout = 90
  net.open_timeout = 30
  net
end

#decode(content_encoding, body) ⇒ Object


117
118
119
120
# File 'lib/intercom/request.rb', line 117

def decode(content_encoding, body)
  return body if (!body) || body.empty? || content_encoding != 'gzip'
  Zlib::GzipReader.new(StringIO.new(body)).read.force_encoding("utf-8")
end

#decode_body(response) ⇒ Object


92
93
94
# File 'lib/intercom/request.rb', line 92

def decode_body(response)
  decode(response['content-encoding'], response.body)
end

#execute(target_base_url = nil, username:, secret: nil) ⇒ Object


61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/intercom/request.rb', line 61

def execute(target_base_url=nil, username:, secret: nil)
  retries = 3
  base_uri = URI.parse(target_base_url)
  set_common_headers(net_http_method, base_uri)
  set_basic_auth(net_http_method, username, secret)
  begin
    client(base_uri).start do |http|
      begin
        response = http.request(net_http_method)
        set_rate_limit_details(response)
        decoded_body = decode_body(response)
        parsed_body = parse_body(decoded_body, response)
        raise_errors_on_failure(response)
        parsed_body
      rescue Intercom::RateLimitExceeded => e
        if @handle_rate_limit
          seconds_to_retry = (@rate_limit_details[:reset_at] - Time.now.utc).ceil
          sleep seconds_to_retry unless seconds_to_retry < 0
          retry unless (retries -=1).zero?
        else
          raise e
        end
      rescue Timeout::Error
        raise Intercom::ServiceUnavailableError.new('Service Unavailable [request timed out]')
      end
    end
  rescue Timeout::Error
    raise Intercom::ServiceConnectionError.new('Failed to connect to service [connection attempt timed out]')
  end
end

#message_for_unexpected_error_with_type(error_details, parsed_http_code) ⇒ Object


182
183
184
# File 'lib/intercom/request.rb', line 182

def message_for_unexpected_error_with_type(error_details, parsed_http_code)
  "The error of type '#{error_details['type']}' is not recognized. It occurred with the message: #{error_details['message']} and http_code: '#{parsed_http_code}'. Please contact Intercom with these details."
end

#message_for_unexpected_error_without_type(error_details, parsed_http_code) ⇒ Object


186
187
188
# File 'lib/intercom/request.rb', line 186

def message_for_unexpected_error_without_type(error_details, parsed_http_code)
  "An unexpected error occured. It occurred with the message: #{error_details['message']} and http_code: '#{parsed_http_code}'. Please contact Intercom with these details."
end

#parse_body(decoded_body, response) ⇒ Object


96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/intercom/request.rb', line 96

def parse_body(decoded_body, response)
  parsed_body = nil
  return parsed_body if decoded_body.nil? || decoded_body.strip.empty?
  begin
    parsed_body = JSON.parse(decoded_body)
  rescue JSON::ParserError => _
    raise_errors_on_failure(response)
  end
  raise_errors_on_failure(response) if parsed_body.nil?
  raise_application_errors_on_failure(parsed_body, response.code.to_i) if parsed_body['type'] == 'error.list'
  parsed_body
end

#raise_application_errors_on_failure(error_list_details, http_code) ⇒ Object


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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/intercom/request.rb', line 140

def raise_application_errors_on_failure(error_list_details, http_code)
  # Currently, we don't support multiple errors
  error_details = error_list_details['errors'].first
  error_code = error_details['type'] || error_details['code']
  error_field = error_details['field']
  parsed_http_code = (http_code > 0 ? http_code : nil)
  error_context = {
    :http_code => parsed_http_code,
    :application_error_code => error_code,
    :field => error_field,
    :request_id => error_list_details['request_id']
  }
  case error_code
  when 'unauthorized', 'forbidden', 'token_not_found'
    raise Intercom::AuthenticationError.new(error_details['message'], error_context)
  when 'token_suspended'
    raise Intercom::AppSuspendedError.new(error_details['message'], error_context)
  when 'token_revoked'
    raise Intercom::TokenRevokedError.new(error_details['message'], error_context)
  when 'token_unauthorized'
    raise Intercom::TokenUnauthorizedError.new(error_details['message'], error_context)
  when "bad_request", "missing_parameter", 'parameter_invalid', 'parameter_not_found'
    raise Intercom::BadRequestError.new(error_details['message'], error_context)
  when "not_restorable"
    raise Intercom::BlockedUserError.new(error_details['message'], error_context)
  when "not_found"
    raise Intercom::ResourceNotFound.new(error_details['message'], error_context)
  when "rate_limit_exceeded"
    raise Intercom::RateLimitExceeded.new(error_details['message'], error_context)
  when 'service_unavailable'
    raise Intercom::ServiceUnavailableError.new(error_details['message'], error_context)
  when 'conflict', 'unique_user_constraint'
    raise Intercom::MultipleMatchingUsersError.new(error_details['message'], error_context)
  when 'resource_conflict'
    raise Intercom::ResourceNotUniqueError.new(error_details['message'], error_context)
  when nil, ''
    raise Intercom::UnexpectedError.new(message_for_unexpected_error_without_type(error_details, parsed_http_code), error_context)
  else
    raise Intercom::UnexpectedError.new(message_for_unexpected_error_with_type(error_details, parsed_http_code), error_context)
  end
end

#raise_errors_on_failure(res) ⇒ Object


122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/intercom/request.rb', line 122

def raise_errors_on_failure(res)
  if res.code.to_i.eql?(404)
    raise Intercom::ResourceNotFound.new('Resource Not Found')
  elsif res.code.to_i.eql?(401)
    raise Intercom::AuthenticationError.new('Unauthorized')
  elsif res.code.to_i.eql?(403)
    raise Intercom::AuthenticationError.new('Forbidden')
  elsif res.code.to_i.eql?(429)
    raise Intercom::RateLimitExceeded.new('Rate Limit Exceeded')
  elsif res.code.to_i.eql?(500)
    raise Intercom::ServerError.new('Server Error')
  elsif res.code.to_i.eql?(502)
    raise Intercom::BadGatewayError.new('Bad Gateway Error')
  elsif res.code.to_i.eql?(503)
    raise Intercom::ServiceUnavailableError.new('Service Unavailable')
  end
end

#set_basic_auth(method, username, secret) ⇒ Object


18
19
20
# File 'lib/intercom/request.rb', line 18

def set_basic_auth(method, username, secret)
  method.basic_auth(CGI.unescape(username), CGI.unescape(secret))
end

#set_common_headers(method, base_uri) ⇒ Object


14
15
16
# File 'lib/intercom/request.rb', line 14

def set_common_headers(method, base_uri)
  method.add_field('AcceptEncoding', 'gzip, deflate')
end

#set_rate_limit_details(response) ⇒ Object


109
110
111
112
113
114
115
# File 'lib/intercom/request.rb', line 109

def set_rate_limit_details(response)
  rate_limit_details = {}
  rate_limit_details[:limit] = response['X-RateLimit-Limit'].to_i if response['X-RateLimit-Limit']
  rate_limit_details[:remaining] = response['X-RateLimit-Remaining'].to_i if response['X-RateLimit-Remaining']
  rate_limit_details[:reset_at] = Time.at(response['X-RateLimit-Reset'].to_i) if response['X-RateLimit-Reset']
  @rate_limit_details = rate_limit_details
end