messagebus_ruby_api 1.0.11 → 3.0.6

Sign up to get free protection for your applications and to get access to all the features.
data/Gemfile CHANGED
@@ -2,11 +2,13 @@ source "http://rubygems.org"
2
2
 
3
3
  gem 'activesupport'
4
4
 
5
+ gem 'multipart-post'
6
+
5
7
  group :test, :development do
6
8
  gem 'rspec', '2.5.0'
7
9
  gem 'rr', '1.0.2'
8
10
  gem 'fakeweb'
9
- gem 'multipart-post'
11
+ gem 'actionmailer'
10
12
  end
11
13
 
12
14
  # Specify your gem's dependencies in messagebus.gemspec
data/README.rdoc CHANGED
@@ -44,6 +44,15 @@
44
44
  - list recent email statistics
45
45
  - list recent delivery errors
46
46
 
47
+ == ActionMailer
48
+
49
+ If you are using ActionMailer (ex. in Rails,) you can leverage the Messagebus API via the following to send emails. You can add the following lines to your environmental configuration such as ./rails_project/config/environments/production.rb
50
+
51
+ ActionMailer::Base.add_delivery_method :messagebus, MessagebusApi::Messagebus, "<APIKEY>"
52
+ config.action_mailer.delivery_method = :messagebus
53
+
54
+ Be sure to replace <APIKEY> with your APIKEY.
55
+
47
56
  == SSL Certificates
48
57
 
49
58
  If you encounter SSL certificate problems, use the cacert_info() method to specify a
@@ -23,8 +23,7 @@ module MessagebusApi
23
23
 
24
24
  def initialize(api_key)
25
25
  @api_key = api_key
26
- init_http_connection
27
- @user_agent = "MessagebusAPI:#{MessagebusApi::VERSION}-Ruby:#{RUBY_VERSION}"
26
+ init_http_connection(domain)
28
27
 
29
28
  @msg_buffer_size = 20
30
29
  @msg_buffer = []
@@ -84,7 +83,7 @@ module MessagebusApi
84
83
 
85
84
  json = json_message_from_list(@msg_buffer)
86
85
  if (@last_init_time < Time.now.utc - 60)
87
- init_http_connection
86
+ init_http_connection(domain)
88
87
  end
89
88
  @results=make_api_post_call(endpoint, json)
90
89
  @msg_buffer.clear
@@ -106,6 +105,16 @@ module MessagebusApi
106
105
  check_response(@results)
107
106
  end
108
107
 
108
+ def overwrite_mailing_list(file_name, file_path, mailing_list_key)
109
+ path = @rest_endpoints[:mailing_list_overwrite].gsub("%KEY%", mailing_list_key)
110
+ File.open(file_path) do |f|
111
+ headers = common_http_headers.merge(rest_upload_headers)
112
+ req = Net::HTTP::Post::Multipart.new path, {:jsonData => "{\"name\":\"#{file_name}\"}", "fileData" => UploadIO.new(f, "text/plain", file_path)}, headers
113
+ @results = @http.request(req)
114
+ end
115
+ check_response(@results)
116
+ end
117
+
109
118
  def mailing_list_delete(mailing_list_key)
110
119
  path = @rest_endpoints[:mailing_list_delete].gsub("%KEY%", mailing_list_key)
111
120
  @results = make_api_delete_call(path)
@@ -181,9 +190,55 @@ module MessagebusApi
181
190
  time.strftime("%Y-%m-%dT%H:%M:%SZ")
182
191
  end
183
192
 
193
+ #used by ActionMailer
194
+ def deliver!(message)
195
+ #minimum required headers
196
+
197
+ if message.to.first.nil? ||message.subject.nil? || message.from.first.nil? then
198
+ raise "Messagebus API error=Missing required header: :toEmail => #{message.to.first} :subject => #{message.subject} :fromEmail => #{message.from.first}"
199
+ end
200
+
201
+ message_from_email = from_email_with_name(message.header[:from].to_s)
202
+
203
+ from_name = ""
204
+ from_email = message.from.first
205
+ if !message_from_email.nil?
206
+ from_name = message_from_email[1]
207
+ end
208
+
209
+ if !well_formed_address?(from_email)
210
+ raise "Messagebus API error=From Address is invalid :toEmail => #{message.to.first} :subject => #{message.subject} :fromEmail => #{message.from.first}"
211
+ end
212
+
213
+ msg = {
214
+ :toEmail => message.to.first,
215
+ :subject => message.subject,
216
+ :fromEmail => from_email,
217
+ :fromName => from_name
218
+ }
219
+
220
+ message.header.fields.delete_if { |k|
221
+ ( k.name.casecmp('bcc') == 0 ||
222
+ k.name.casecmp('cc') == 0 )
223
+ }
224
+
225
+ msg[:plaintextBody] = ( message.body ) ? "#{message.body}" : "No plaintext version was supplied."
226
+
227
+ if message.multipart?
228
+ msg[:plaintextBody] = (message.text_part) ? message.text_part.body.to_s : "No plaintext version was supplied."
229
+ msg[:htmlBody] = message.html_part.body.to_s if message.html_part
230
+ end
231
+
232
+ begin
233
+ add_message(msg, true)
234
+ rescue => message_bus_api_error
235
+ raise "Messagebus API error=#{message_bus_api_error}, message=#{msg.inspect}"
236
+ end
237
+ end
238
+
184
239
  private
185
240
 
186
- def init_http_connection(target_server=DEFAULT_API_ENDPOINT_STRING)
241
+ def init_http_connection(target_server)
187
242
  if (@http and @http.started?)
188
243
  @http.finish
189
244
  end
@@ -194,8 +249,12 @@ module MessagebusApi
194
249
  @http
195
250
  end
196
251
 
252
+ def domain
253
+ DEFAULT_API_ENDPOINT_STRING
254
+ end
255
+
197
256
  def common_http_headers
198
- {'User-Agent' => @user_agent, 'X-MessageBus-Key' => @api_key}
257
+ {'User-Agent' => MessagebusApi::Info.get_user_agent, 'X-MessageBus-Key' => @api_key}
199
258
  end
200
259
 
201
260
  def rest_post_headers
@@ -242,6 +301,14 @@ module MessagebusApi
242
301
  format_iso_time(Time.now.utc - (days_ago*86400))
243
302
  end
244
303
 
304
+ def from_email_with_name(address)
305
+ address.match(/^(.*)\s<(.*?)>/)
306
+ end
307
+
308
+ def well_formed_address?(address)
309
+ !address.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i).nil?
310
+ end
311
+
245
312
  def json_message_from_list(messages)
246
313
  {:messages => messages}.to_json
247
314
  end
@@ -279,9 +346,9 @@ module MessagebusApi
279
346
  rescue JSON::ParserError
280
347
  nil
281
348
  end
282
- raise MessagebusApi::RemoteServerError.new("#{response.code.to_s}:#{rest_http_error_message(response.code.to_s)}")
349
+ raise MessagebusApi::RemoteServerError.new("#{response.code.to_s}:#{rest_http_error_message(response)}")
283
350
  else
284
- raise MessagebusApi::RemoteServerError.new("#{response.code.to_s}:#{rest_http_error_message(response.code.to_s)}")
351
+ raise MessagebusApi::RemoteServerError.new("#{response.code.to_s}:#{rest_http_error_message(response)}")
285
352
  end
286
353
  else
287
354
  raise "Unexpected HTTP Response: #{response.class.name}"
@@ -293,9 +360,16 @@ module MessagebusApi
293
360
  @rest_http_errors.key?(status_code)
294
361
  end
295
362
 
296
- def rest_http_error_message(status_code)
363
+ def rest_http_error_message(response)
297
364
  message = "Unknown Error Code"
298
- message = @rest_http_errors[status_code] if rest_http_error?(status_code)
365
+ message = @rest_http_errors[response.code.to_s] if rest_http_error?(response.code.to_s)
366
+ if (response.body.size > 0)
367
+ values = JSON.parse(response.body)
368
+
369
+ if (values['statusMessage'])
370
+ message += " - " + values['statusMessage']
371
+ end
372
+ end
299
373
  message
300
374
  end
301
375
 
@@ -309,6 +383,7 @@ module MessagebusApi
309
383
  :feedbackloops => "/api/v3/feedbackloops",
310
384
  :mailing_lists => "/api/v3/mailing_lists",
311
385
  :mailing_lists_upload => "/api/v3/mailing_lists/upload",
386
+ :mailing_list_overwrite => "/api/v3/mailing_list/%KEY%/upload",
312
387
  :mailing_list_delete => "/api/v3/mailing_list/%KEY%",
313
388
  :mailing_lists_entries => "/api/v3/mailing_list/%KEY%/entries",
314
389
  :mailing_lists_entry_email => "/api/v3/mailing_list/%KEY%/entry/%EMAIL%",
@@ -13,5 +13,15 @@
13
13
  # under the License.
14
14
 
15
15
  module MessagebusApi
16
- VERSION = "1.0.11"
16
+ VERSION = "3.0.6"
17
+
18
+ class Info
19
+ @@ClientVersion = MessagebusApi::VERSION
20
+ @@RubyVersion = RUBY_VERSION
21
+ @@UserAgent = "MessagebusAPI:#{@@ClientVersion}-Ruby:#{@@RubyVersion}";
22
+
23
+ def self.get_user_agent
24
+ return @@UserAgent
25
+ end
26
+ end
17
27
  end
@@ -324,6 +324,32 @@ describe MessagebusApi::Messagebus do
324
324
  end.should_not raise_error
325
325
  end
326
326
 
327
+ it "overwrites a mailing list" do
328
+ name = 'mylist'
329
+ filename = File.dirname(__FILE__) + '/../../examples/example_maillist.txt'
330
+ overwritefilename = File.dirname(__FILE__) + '/../../examples/overwritelist.txt'
331
+
332
+ begin
333
+ FileUtils.cp filename, overwritefilename
334
+ rescue Exception=>e
335
+ puts(e)
336
+ end
337
+
338
+ open(overwritefilename, 'a') do |f|
339
+ f.puts "test@nowhere.example.com,test,tester"
340
+ end
341
+
342
+ expected_request="https://api.messagebus.com/api/v3/mailing_list/392d08c0694811e1a7dd4040f34d0a26/upload"
343
+
344
+ FakeWeb.register_uri(:post, expected_request, :body => json_mailing_list_overwrite)
345
+
346
+ expect do
347
+ response = client.overwrite_mailing_list(name,overwritefilename, '392d08c0694811e1a7dd4040f34d0a26')
348
+ response[:mailingListKey].should == '392d08c0694811e1a7dd4040f34d0a26'
349
+ response
350
+ end.should_not raise_error
351
+ end
352
+
327
353
  it "deletes a mailing list" do
328
354
  mailing_list_key = "7215ee9c7d9dc229d2921a40e899ec5f"
329
355
  expected_request="https://api.messagebus.com/api/v3/mailing_list/7215ee9c7d9dc229d2921a40e899ec5f"
@@ -358,6 +384,30 @@ describe MessagebusApi::Messagebus do
358
384
  end.should_not raise_error
359
385
  end
360
386
 
387
+ it "raises an error with an error message when the mailingListKey is not found" do
388
+
389
+ campaign_params = {:campaignName => 'MessageBus Test Campaign',
390
+ :fromName => 'Message Bus',
391
+ :fromEmail => 'do.not.reply@messagebus.com',
392
+ :subject => 'This is a test campaign',
393
+ :mailingListKey => '7215ee9c7d9dc229d2921a40e899ec5f',
394
+ :htmlBody => "<html><body>This message is only a test sent by the Ruby Message Bus client library.</body></html>",
395
+ :plaintextBody => 'This message is only a test sent by the Ruby Message Bus client library.',
396
+ :tags => ['RUBY', 'Unit Test Ruby'],
397
+ :customHeaders => {"sender"=>"apitest1@messagebus.com"}}
398
+
399
+ expected_request="https://api.messagebus.com/api/v3/campaigns/send"
400
+
401
+ FakeWeb.register_uri(:post, expected_request, :body => json_response_404)
402
+
403
+ expect do
404
+ response = client.campaigns_send(campaign_params)
405
+ response[:statusCode].should == 404
406
+ response[:statusMessage].should == "Invalid URL - Mailing list key not found."
407
+ end.should_not raise_error
408
+
409
+ end
410
+
361
411
  it "retrieves completed status with campaign key" do
362
412
  campaign_key="7215ee9c7d9dc229d2921a40e899ec5f"
363
413
 
@@ -401,6 +451,37 @@ describe MessagebusApi::Messagebus do
401
451
  end
402
452
  end
403
453
 
454
+ describe "#version" do
455
+ it "Confirm API version string" do
456
+ MessagebusApi::Info.get_user_agent.should =~ /MessagebusAPI:3\.\d\.\d-Ruby:\d+.\d+.\d+/
457
+ end
458
+ end
459
+
460
+ describe "#deliver!" do
461
+ it "works with action mailer" do
462
+ to_email = "hello@example.com"
463
+ message = MessageBusActionMailerTest.new_message(to_email)
464
+
465
+ FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/emails/send", :body => json_valid_send)
466
+ client.deliver!(message)
467
+
468
+ message_body = JSON.parse(FakeWeb.last_request.body)
469
+ message_body["messages"][0]["fromName"].should == ""
470
+ message_body["messages"][0]["fromEmail"].should == to_email
471
+ end
472
+
473
+ it "works with from with nice name in address" do
474
+ to_email = "Joe Mail <hello_joe@example.com>"
475
+ message = MessageBusActionMailerTest.new_message(to_email)
476
+
477
+ FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/emails/send", :body => json_valid_send)
478
+ client.deliver!(message)
479
+
480
+ message_body = JSON.parse(FakeWeb.last_request.body)
481
+ message_body["messages"][0]["fromName"].should == "Joe Mail"
482
+ message_body["messages"][0]["fromEmail"].should == "hello_joe@example.com"
483
+ end
484
+ end
404
485
 
405
486
  end
406
487
 
data/spec/spec_helper.rb CHANGED
@@ -18,7 +18,7 @@ require 'rubygems'
18
18
  require 'fakeweb'
19
19
  require 'rr'
20
20
  require 'json'
21
-
21
+ require 'action_mailer'
22
22
  require "#{dir}/spec_core_extensions"
23
23
  require "#{dir}/../lib/messagebus_ruby_api"
24
24
 
@@ -58,6 +58,13 @@ JAVASCRIPT
58
58
  json
59
59
  end
60
60
 
61
+ def json_mailing_list_overwrite
62
+ json = <<JAVASCRIPT
63
+ {"invalidCount":0,"invalidLines":[0],"mailingListKey":"392d08c0694811e1a7dd4040f34d0a26","statusCode":201,"statusMessage":"","statusTime":"2012-03-08T17:57:51.596Z","validCount":3}
64
+ JAVASCRIPT
65
+ json
66
+ end
67
+
61
68
  def json_mailing_list_create
62
69
  json = <<JAVASCRIPT
63
70
  {"statusCode":201,"statusMessage":"","statusTime":"2011-10-10T21:32:14.195Z","key":"51efcf00f38711e0a93640405cc99fee"}
@@ -113,3 +120,22 @@ def json_response_200
113
120
  JAVASCRIPT
114
121
  json
115
122
  end
123
+
124
+ def json_response_404
125
+ json = <<JAVASCRIPT
126
+ {"statusCode":404,"statusMessage":"Invalid URL - Mailing list key not found.","statusTime":"2011-10-10T21:32:14.195Z"}
127
+ JAVASCRIPT
128
+ json
129
+ end
130
+
131
+ ActionMailer::Base.add_delivery_method :messagebus, MessagebusApi::Messagebus, @api_key
132
+ class MessageBusActionMailerTest < ActionMailer::Base
133
+ default :to => "someone@example.com",
134
+ :from => "no-reply@messagebus.com",
135
+ :body => "This is a test",
136
+ :subject => "Unit Test"
137
+
138
+ def new_message(from_email)
139
+ mail(:from => from_email)
140
+ end
141
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: messagebus_ruby_api
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.11
4
+ version: 3.0.6
5
5
  prerelease:
6
6
  platform: ruby
7
7
  authors:
@@ -9,8 +9,19 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2012-03-26 00:00:00.000000000Z
13
- dependencies: []
12
+ date: 2012-08-23 00:00:00.000000000Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: multipart-post
16
+ requirement: &70268165864740 !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: '0'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: *70268165864740
14
25
  description: ! 'Allows you to use the Message Bus API '
15
26
  email:
16
27
  - messagebus@googlegroups.com
@@ -51,7 +62,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
51
62
  version: '0'
52
63
  requirements: []
53
64
  rubyforge_project: messagebus_ruby_api
54
- rubygems_version: 1.8.19
65
+ rubygems_version: 1.8.10
55
66
  signing_key:
56
67
  specification_version: 3
57
68
  summary: Send email through the Message Bus service