messagemedia_webhooks_sdk 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (29) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +28 -0
  3. data/README.md +132 -0
  4. data/lib/message_media_webhooks.rb +39 -0
  5. data/lib/message_media_webhooks/api_helper.rb +272 -0
  6. data/lib/message_media_webhooks/configuration.rb +28 -0
  7. data/lib/message_media_webhooks/controllers/base_controller.rb +55 -0
  8. data/lib/message_media_webhooks/controllers/webhooks_controller.rb +369 -0
  9. data/lib/message_media_webhooks/exceptions/api_exception.rb +16 -0
  10. data/lib/message_media_webhooks/exceptions/create_webhook_400_response_exception.rb +25 -0
  11. data/lib/message_media_webhooks/exceptions/retrieve_webhook_400_response_exception.rb +26 -0
  12. data/lib/message_media_webhooks/exceptions/update_webhook_400_response_exception.rb +25 -0
  13. data/lib/message_media_webhooks/http/auth/basic_auth.rb +20 -0
  14. data/lib/message_media_webhooks/http/faraday_client.rb +54 -0
  15. data/lib/message_media_webhooks/http/http_call_back.rb +20 -0
  16. data/lib/message_media_webhooks/http/http_client.rb +90 -0
  17. data/lib/message_media_webhooks/http/http_context.rb +16 -0
  18. data/lib/message_media_webhooks/http/http_method_enum.rb +9 -0
  19. data/lib/message_media_webhooks/http/http_request.rb +46 -0
  20. data/lib/message_media_webhooks/http/http_response.rb +19 -0
  21. data/lib/message_media_webhooks/message_media_webhooks_client.rb +26 -0
  22. data/lib/message_media_webhooks/models/base_model.rb +32 -0
  23. data/lib/message_media_webhooks/models/create_webhook_request.rb +76 -0
  24. data/lib/message_media_webhooks/models/update_webhook_request.rb +67 -0
  25. data/test/controllers/controller_test_base.rb +30 -0
  26. data/test/controllers/test_webhooks_controller.rb +56 -0
  27. data/test/http_response_catcher.rb +16 -0
  28. data/test/test_helper.rb +91 -0
  29. metadata +155 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 9927701b5cbe6a65e500841d8fab5e5d232db51f
4
+ data.tar.gz: 2d493415a68f09ff555371c20515d8e0a9ae7bd9
5
+ SHA512:
6
+ metadata.gz: 180bc2cfbcb15e9cbc5849d84746fba27016b5f632c3758f6fbe6cfd7f7747dac0c65f64003074ebd0c53806bd616880a2a209c5bb892a829c1b14b7411b1051
7
+ data.tar.gz: 31ed43df6cee695b070a0b3b03fd44ed4ff82e21bcc49d9786a6f72f69885f286b6029c6ab2c300541ad7c121ccb82eaec838c3309e164ddd4b0102d6e8291f5
data/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ License:
2
+ ========
3
+ The MIT License (MIT)
4
+ http://opensource.org/licenses/MIT
5
+
6
+ Copyright (c) 2014 - 2016 APIMATIC Limited
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ of this software and associated documentation files (the "Software"), to deal
10
+ in the Software without restriction, including without limitation the rights
11
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ copies of the Software, and to permit persons to whom the Software is
13
+ furnished to do so, subject to the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be included in
16
+ all copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
+ THE SOFTWARE.
25
+
26
+ Trade Mark:
27
+ ==========
28
+ APIMATIC is a trade mark for APIMATIC Limited
data/README.md ADDED
@@ -0,0 +1,132 @@
1
+ # MessageMedia Webhooks NodeJS SDK
2
+ [![Travis Build Status](https://api.travis-ci.org/messagemedia/webhooks-ruby-sdk.svg?branch=master)](https://travis-ci.org/messagemedia/webhooks-ruby-sdk)
3
+ [![gems version](https://badge.fury.io/js/messagemedia-webhooks-sdk.svg)](https://badge.fury.io/js/messagemedia-webhooks-sdk)
4
+
5
+ The MessageMedia Webhooks allows you to subscribe to one or several events and when one of those events is triggered, an HTTP request is sent to the URL of your choice along with the message or payload. In simpler terms, it allows applications to "speak" to one another and get notified automatically when something new happens.
6
+
7
+ ## ⭐️ Installing via RubyGems
8
+ Run the following command to install the SDK via RubyGems:
9
+ * `gem install messagemedia-webhooks-sdk`
10
+
11
+ ## 🎬 Get Started
12
+ It's easy to get started. Simply enter the API Key and secret you obtained from the [MessageMedia Developers Portal](https://developers.messagemedia.com) into the code snippet below and a mobile number you wish to send to.
13
+
14
+ ### 🚀 Create a webhook
15
+ ```ruby
16
+ require 'message_media_webhooks'
17
+ require 'pp'
18
+
19
+ # Configuration parameters and credentials
20
+ basic_auth_user_name = 'API_KEY' # The username to use with basic authentication
21
+ basic_auth_password = 'API_SECRET' # The password to use with basic authentication
22
+
23
+ client = MessageMediaWebhooks::MessageMediaWebhooksClient.new(
24
+ basic_auth_user_name: basic_auth_user_name,
25
+ basic_auth_password: basic_auth_password
26
+ )
27
+
28
+ webhooks_controller = client.webhooks
29
+
30
+ body = MessageMediaWebhooks::CreateWebhookRequest.new("http://webhook2.com",
31
+ "POST",
32
+ "JSON",
33
+ nil,
34
+ ["ENROUTE_DR"],
35
+ "{\"id\":\"$mtId\",\"status\":\"$statusCode\"}"
36
+ )
37
+
38
+ result = webhooks_controller.create_webhook(body)
39
+ pp result
40
+
41
+ ```
42
+
43
+ ### 📥 Retrieve all webhooks
44
+ ```ruby
45
+ require 'message_media_webhooks'
46
+ require 'pp'
47
+
48
+ # Configuration parameters and credentials
49
+ basic_auth_user_name = 'API_KEY' # The username to use with basic authentication
50
+ basic_auth_password = 'API_SECRET' # The password to use with basic authentication
51
+
52
+ client = MessageMediaWebhooks::MessageMediaWebhooksClient.new(
53
+ basic_auth_user_name: basic_auth_user_name,
54
+ basic_auth_password: basic_auth_password
55
+ )
56
+
57
+ webhooks_controller = client.webhooks
58
+
59
+ page = 0
60
+ page_size = 0
61
+
62
+ result = webhooks_controller.retrieve_webhook(page, page_size)
63
+ pp result
64
+
65
+ ```
66
+
67
+ ### 🔄 Update a webhook
68
+ You can get a webhook ID by looking at the `id` of each webhook created from the response of the above example.
69
+ ```ruby
70
+ require 'message_media_webhooks'
71
+ require 'pp'
72
+
73
+ # Configuration parameters and credentials
74
+ basic_auth_user_name = 'API_KEY' # The username to use with basic authentication
75
+ basic_auth_password = 'API_SECRET' # The password to use with basic authentication
76
+
77
+ client = MessageMediaWebhooks::MessageMediaWebhooksClient.new(
78
+ basic_auth_user_name: basic_auth_user_name,
79
+ basic_auth_password: basic_auth_password
80
+ )
81
+
82
+ webhooks_controller = client.webhooks
83
+
84
+ webhook_id = "WEBHOOK_ID"
85
+
86
+ body_value = "{
87
+ \"url\": \"https://myurl.com\",
88
+ \"method\": \"POST\",
89
+ \"encoding\": \"FORM_ENCODED\",
90
+ \"events\": [\"ENROUTE_DR\"],
91
+ \"template\": \"{\\\"id\\\":\\\"$mtId\\\", \\\"status\\\":\\\"$statusCode\\\"}\"
92
+ }";
93
+
94
+ body = JSON.parse(body_value);
95
+
96
+ result = webhooks_controller.update_webhook(webhook_id, body)
97
+ pp result
98
+
99
+ ```
100
+
101
+ ### ❌ Delete a webhook
102
+ You can get a webhook ID by looking at the `id` of each webhook created from the response of the retrieve webhooks example.
103
+ ```ruby
104
+ require 'message_media_webhooks'
105
+ require 'pp'
106
+
107
+ # Configuration parameters and credentials
108
+ basic_auth_user_name = 'API_KEY' # The username to use with basic authentication
109
+ basic_auth_password = 'API_SECRET' # The password to use with basic authentication
110
+
111
+ client = MessageMediaWebhooks::MessageMediaWebhooksClient.new(
112
+ basic_auth_user_name: basic_auth_user_name,
113
+ basic_auth_password: basic_auth_password
114
+ )
115
+
116
+ webhooks_controller = client.webhooks
117
+
118
+ webhook_id = "WEBHOOK_ID"
119
+
120
+ webhooks_controller.delete_webhook(webhook_id)
121
+ pp result
122
+
123
+ ```
124
+
125
+ ## 📕 Documentation
126
+ Check out the [full API documentation](DOCUMENTATION.md) for more detailed information.
127
+
128
+ ## 😕 Need help?
129
+ Please contact developer support at developers@messagemedia.com or check out the developer portal at [developers.messagemedia.com](https://developers.messagemedia.com/)
130
+
131
+ ## 📃 License
132
+ Apache License. See the [LICENSE](LICENSE) file.
@@ -0,0 +1,39 @@
1
+
2
+ require 'date'
3
+ require 'json'
4
+ require 'faraday'
5
+ require 'certifi'
6
+ require 'logging'
7
+
8
+ require_relative 'message_media_webhooks/api_helper.rb'
9
+ require_relative 'message_media_webhooks/message_media_webhooks_client.rb'
10
+
11
+ # Http
12
+ require_relative 'message_media_webhooks/http/http_call_back.rb'
13
+ require_relative 'message_media_webhooks/http/http_client.rb'
14
+ require_relative 'message_media_webhooks/http/http_method_enum.rb'
15
+ require_relative 'message_media_webhooks/http/http_request.rb'
16
+ require_relative 'message_media_webhooks/http/http_response.rb'
17
+ require_relative 'message_media_webhooks/http/http_context.rb'
18
+ require_relative 'message_media_webhooks/http/faraday_client.rb'
19
+ require_relative 'message_media_webhooks/http/auth/basic_auth.rb'
20
+
21
+ # Models
22
+ require_relative 'message_media_webhooks/models/base_model.rb'
23
+ require_relative 'message_media_webhooks/models/create_webhook_request.rb'
24
+ require_relative 'message_media_webhooks/models/update_webhook_request.rb'
25
+
26
+ # Exceptions
27
+ require_relative 'message_media_webhooks/exceptions/api_exception.rb'
28
+ require_relative 'message_media_webhooks/exceptions/update_webhook_400' \
29
+ '_response_exception.rb'
30
+ require_relative 'message_media_webhooks/exceptions/retrieve_webhook_400' \
31
+ '_response_exception.rb'
32
+ require_relative 'message_media_webhooks/exceptions/create_webhook_400' \
33
+ '_response_exception.rb'
34
+
35
+ require_relative 'message_media_webhooks/configuration.rb'
36
+
37
+ # Controllers
38
+ require_relative 'message_media_webhooks/controllers/base_controller.rb'
39
+ require_relative 'message_media_webhooks/controllers/webhooks_controller.rb'
@@ -0,0 +1,272 @@
1
+
2
+
3
+ module MessageMediaWebhooks
4
+ # API utility class
5
+ class APIHelper
6
+ # Serializes an array parameter (creates key value pairs).
7
+ # @param [String] The name of the parameter.
8
+ # @param [Array] The value of the parameter.
9
+ # @param [String] The format of the serialization.
10
+ def self.serialize_array(key, array, formatting: 'indexed')
11
+ tuples = []
12
+
13
+ if formatting == 'unindexed'
14
+ tuples += array.map { |element| ["#{key}[]", element] }
15
+ elsif formatting == 'indexed'
16
+ tuples += array.map.with_index do |element, index|
17
+ ["#{key}[#{index}]", element]
18
+ end
19
+ elsif formatting == 'plain'
20
+ tuples += array.map { |element| [key, element] }
21
+ else
22
+ raise ArgumentError, 'Invalid format provided.'
23
+ end
24
+ tuples
25
+ end
26
+
27
+ # Replaces template parameters in the given url.
28
+ # @param [String] The query string builder to replace the template
29
+ # parameters.
30
+ # @param [Hash] The parameters to replace in the url.
31
+ def self.append_url_with_template_parameters(query_builder, parameters)
32
+ # perform parameter validation
33
+ unless query_builder.instance_of? String
34
+ raise ArgumentError, 'Given value for parameter \"query_builder\" is
35
+ invalid.'
36
+ end
37
+
38
+ # Return if there are no parameters to replace.
39
+ return query_builder if parameters.nil?
40
+
41
+ # Iterate and append parameters.
42
+ parameters.each do |key, value|
43
+ replace_value = ''
44
+
45
+ if value.nil?
46
+ replace_value = ''
47
+ elsif value.instance_of? Array
48
+ value.map! { |element| CGI.escape(element.to_s) }
49
+ replace_value = value.join('/')
50
+ else
51
+ replace_value = CGI.escape(value.to_s)
52
+ end
53
+
54
+ # Find the template parameter and replace it with its value.
55
+ query_builder = query_builder.gsub('{' + key.to_s + '}', replace_value)
56
+ end
57
+ query_builder
58
+ end
59
+
60
+ # Appends the given set of parameters to the given query string.
61
+ # @param [String] The query string builder to add the query parameters to.
62
+ # @param [Hash] The parameters to append.
63
+ # @param [String] The format of array parameter serialization.
64
+ def self.append_url_with_query_parameters(query_builder, parameters,
65
+ array_serialization: 'indexed')
66
+ # Perform parameter validation.
67
+ unless query_builder.instance_of? String
68
+ raise ArgumentError, 'Given value for parameter \"query_builder\"
69
+ is invalid.'
70
+ end
71
+
72
+ # Return if there are no parameters to replace.
73
+ return query_builder if parameters.nil?
74
+
75
+ parameters.each do |key, value|
76
+ seperator = query_builder.include?('?') ? '&' : '?'
77
+ unless value.nil?
78
+ if value.instance_of? Array
79
+ value.compact!
80
+ query_builder += if array_serialization == 'csv'
81
+ "#{seperator}#{key}=#{value.map do |element|
82
+ CGI.escape(element.to_s)
83
+ end.join(',')}"
84
+ elsif array_serialization == 'psv'
85
+ "#{seperator}#{key}=#{value.map do |element|
86
+ CGI.escape(element.to_s)
87
+ end.join('|')}"
88
+ elsif array_serialization == 'tsv'
89
+ "#{seperator}#{key}=#{value.map do |element|
90
+ CGI.escape(element.to_s)
91
+ end.join("\t")}"
92
+ else
93
+ "#{seperator}#{APIHelper.serialize_array(
94
+ key, value, formatting: array_serialization
95
+ ).map { |k, v| "#{k}=#{CGI.escape(v.to_s)}" }
96
+ .join('&')}"
97
+ end
98
+ else
99
+ query_builder += "#{seperator}#{key}=#{CGI.escape(value.to_s)}"
100
+ end
101
+ end
102
+ end
103
+ query_builder
104
+ end
105
+
106
+ # Validates and processes the given Url.
107
+ # @param [String] The given Url to process.
108
+ # @return [String] Pre-processed Url as string.
109
+ def self.clean_url(url)
110
+ # Perform parameter validation.
111
+ raise ArgumentError, 'Invalid Url.' unless url.instance_of? String
112
+
113
+ # Ensure that the urls are absolute.
114
+ matches = url.match(%r{^(https?:\/\/[^\/]+)})
115
+ raise ArgumentError, 'Invalid Url format.' if matches.nil?
116
+
117
+ # Get the http protocol match.
118
+ protocol = matches[1]
119
+
120
+ # Check if parameters exist.
121
+ index = url.index('?')
122
+
123
+ # Remove redundant forward slashes.
124
+ query = url[protocol.length...(!index.nil? ? index : url.length)]
125
+ query.gsub!(%r{\/\/+}, '/')
126
+
127
+ # Get the parameters.
128
+ parameters = !index.nil? ? url[url.index('?')...url.length] : ''
129
+
130
+ # Return processed url.
131
+ protocol + query + parameters
132
+ end
133
+
134
+ # Parses JSON string.
135
+ # @param [String] A JSON string.
136
+ def self.json_deserialize(json)
137
+ return JSON.parse(json)
138
+ rescue StandardError
139
+ raise TypeError, 'Server responded with invalid JSON.'
140
+ end
141
+
142
+ # Removes elements with empty values from a hash.
143
+ # @param [Hash] The hash to clean.
144
+ def self.clean_hash(hash)
145
+ hash.delete_if { |_key, value| value.to_s.strip.empty? }
146
+ end
147
+
148
+ # Form encodes a hash of parameters.
149
+ # @param [Hash] The hash of parameters to encode.
150
+ # @return [Hash] A hash with the same parameters form encoded.
151
+ def self.form_encode_parameters(form_parameters)
152
+ encoded = {}
153
+ form_parameters.each do |key, value|
154
+ encoded.merge!(APIHelper.form_encode(value, key, formatting:
155
+ Configuration.array_serialization))
156
+ end
157
+ encoded
158
+ end
159
+
160
+ def self.custom_merge(a, b)
161
+ x = {}
162
+ a.each do |key, value_a|
163
+ b.each do |k, value_b|
164
+ next unless key == k
165
+ x[k] = []
166
+ if value_a.instance_of? Array
167
+ value_a.each do |v|
168
+ x[k].push(v)
169
+ end
170
+ else
171
+ x[k].push(value_a)
172
+ end
173
+ if value_b.instance_of? Array
174
+ value_b.each do |v|
175
+ x[k].push(v)
176
+ end
177
+ else
178
+ x[k].push(value_b)
179
+ end
180
+ a.delete(k)
181
+ b.delete(k)
182
+ end
183
+ end
184
+ x.merge!(a)
185
+ x.merge!(b)
186
+ x
187
+ end
188
+
189
+ # Form encodes an object.
190
+ # @param [Dynamic] An object to form encode.
191
+ # @param [String] The name of the object.
192
+ # @return [Hash] A form encoded representation of the object in the form
193
+ # of a hash.
194
+ def self.form_encode(obj, instance_name, formatting: 'indexed')
195
+ retval = {}
196
+
197
+ serializable_types = [String, Numeric, TrueClass,
198
+ FalseClass, Date, DateTime]
199
+
200
+ # If this is a structure, resolve it's field names.
201
+ obj = obj.to_hash if obj.is_a? BaseModel
202
+
203
+ # Create a form encoded hash for this object.
204
+ if obj.nil?
205
+ nil
206
+ elsif obj.instance_of? Array
207
+ if formatting == 'indexed'
208
+ obj.each_with_index do |value, index|
209
+ retval.merge!(APIHelper.form_encode(value, instance_name + '[' +
210
+ index.to_s + ']'))
211
+ end
212
+ elsif serializable_types.map { |x| obj[0].is_a? x }.any?
213
+ obj.each do |value|
214
+ abc = if formatting == 'unindexed'
215
+ APIHelper.form_encode(value, instance_name + '[]',
216
+ formatting: formatting)
217
+ else
218
+ APIHelper.form_encode(value, instance_name,
219
+ formatting: formatting)
220
+ end
221
+ retval = APIHelper.custom_merge(retval, abc)
222
+ # print retval
223
+ end
224
+ else
225
+ obj.each_with_index do |value, index|
226
+ retval.merge!(APIHelper.form_encode(value, instance_name + '[' +
227
+ index.to_s + ']', formatting: formatting))
228
+ end
229
+ end
230
+ elsif obj.instance_of? Hash
231
+ obj.each do |key, value|
232
+ retval.merge!(APIHelper.form_encode(value, instance_name + '[' +
233
+ key + ']', formatting: formatting))
234
+ end
235
+ else
236
+ retval[instance_name] = obj
237
+ end
238
+ retval
239
+ end
240
+
241
+ # Safely converts a string into an rfc3339 DateTime object
242
+ # @param [String] The datetime string
243
+ # @return [DateTime] A DateTime object of rfc3339 format
244
+ def self.rfc3339(date_time)
245
+ # missing timezone information
246
+ if date_time.end_with?('Z') || date_time.index('+')
247
+ DateTime.rfc3339(date_time)
248
+ else
249
+ DateTime.rfc3339(date_time + 'Z')
250
+ end
251
+ end
252
+ end
253
+ end
254
+
255
+ # Extend types to support to_bool.
256
+ module ToBoolean
257
+ def to_bool
258
+ return true if self == true || to_s.strip =~ /^(true|yes|y|1)$/i
259
+ false
260
+ end
261
+ end
262
+
263
+ # Extend NilClass type to support to_bool.
264
+ class NilClass; include ToBoolean; end
265
+ # Extend TrueClass type to support to_bool.
266
+ class TrueClass; include ToBoolean; end
267
+ # Extend FalseClass type to support to_bool.
268
+ class FalseClass; include ToBoolean; end
269
+ # Extend Numeric type to support to_bool.
270
+ class Numeric; include ToBoolean; end
271
+ # Extend String type to support to_bool.
272
+ class String; include ToBoolean; end