messagebus-ruby-api-1.0.3/0000755000076400007640000000000012570556603014444 5ustar pravipravimessagebus-ruby-api-1.0.3/spec/0000755000076400007640000000000012570556603015376 5ustar pravipravimessagebus-ruby-api-1.0.3/spec/spec_helper.rb0000644000076400007640000000515612570556603020223 0ustar pravipravi# Copyright 2012 Mail Bypass, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. dir = File.dirname(__FILE__) require 'rubygems' require 'fakeweb' require 'rr' require 'json' require "#{dir}/spec_core_extensions" require "#{dir}/../lib/messagebus_ruby_api" def json_valid_send json = < 'apitest1@messagebus.com', :toName => 'EmailUser', :fromEmail => 'api@messagebus.com', :fromName => 'API', :subject => 'Unit Test Message', :customHeaders => ["sender"=>"apitest1@messagebus.com"], :plaintextBody => 'This message is only a test sent by the Ruby Message Bus client library.', :htmlBody => "This message is only a test sent by the Ruby Message Bus client library.", :tags => ['RUBY', 'Unit Test Ruby'] } end def default_template_message_params {:toEmail => 'apitest1@messagebus.com', :toName => 'John Smith', :templateKey => '66f6181bcb4cff4cd38fbc804a036db6', :customHeaders => ["reply-to"=>"apitest1@messagebus.com"], :mergeFields => ["%NAME%" => "John"] } end def create_success_result(num_result) list=[] num_result.times do list << @success_message end success_result = { "statusMessage" => "OK", "successCount" => num_result, "failureCount" => 0, "results" => list } success_result end def create_results_array results = { "statusMessage" => "OK", "results" => [] } results end def json_parse(data) JSON.parse(data, :symbolize_names => true) end before do FakeWeb.allow_net_connect = false @api_key = "7215ee9c7d9dc229d2921a40e899ec5f" @client = MessagebusTest.new(@api_key) @success_message={ "status" => 200, "messageId" => "abcdefghijklmnopqrstuvwxyz012345" } @simple_success_result = create_success_result(1) end describe "messagebus object set up correctly" do it "has correct headers set for api calls" do client = MessagebusApi::Messagebus.new(@api_key) end end describe "add cacert file to http communitcations" do it "raises error if cert file does not exist" do client = MessagebusApi::Messagebus.new(@api_key) cert_file_path = File.join(File.dirname(__FILE__), "nofile.pem") expect do client.cacert_info(cert_file_path) end.should raise_error end it "accepts a cert file that exists" do client = MessagebusApi::Messagebus.new(@api_key) cert_file_path = File.join(File.dirname(__FILE__), "cacert.pem") expect do client.cacert_info(cert_file_path) end.should_not raise_error end end describe "#add_message" do it "buffered send that adds to empty buffer" do client.add_message(default_message_params) client.flushed?.should be_false end it "buffered send that adds to empty buffer and sends with flush_buffer flag" do FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/emails/send", :body => json_valid_send) client.add_message(default_message_params, true) client.flushed?.should be_true end it "should have user-agent and x-messagebus-key set in request headers" do FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/emails/send", :body => json_valid_send) client.add_message(default_message_params, true) client.flushed?.should be_true FakeWeb.last_request.get_fields("X-MessageBus-Key").should_not be_nil FakeWeb.last_request.get_fields("User-Agent").should_not be_nil FakeWeb.last_request.get_fields("Content-Type").should_not be_nil end it "buffered send that adds to a buffer and auto-flushes" do FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/emails/send", :body => create_success_result(client.message_buffer_size).to_json) (client.message_buffer_size-1).times do |idx| client.add_message(default_message_params) client.flushed?.should be_false end client.add_message(default_message_params) client.flushed?.should be_true client.results[:results].size.should == client.message_buffer_size end it "buffered send that adds templates to a buffer and auto-flushes" do FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/templates/send", :body => create_success_result(client.message_buffer_size).to_json) (client.message_buffer_size-1).times do |idx| client.add_message(default_template_message_params) client.flushed?.should be_false end client.add_message(default_template_message_params) client.flushed?.should be_true client.results[:results].size.should == client.message_buffer_size end end describe "#flush" do it "flush called on empty buffer" do client.flush client.flushed?.should be_false end it "flush called on partially filled buffer" do message_count = 9 FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/emails/send", :body => create_success_result(message_count).to_json) (message_count).times do |idx| client.add_message(default_message_params) client.flushed?.should be_false end client.flush client.flushed?.should be_true client.results[:results].size.should == message_count end it "doesnt reset connection if under a minute old" do current_init_time=client.last_init_time current_init_time.should be > Time.now.utc-5 FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/emails/send", :body => create_success_result(1).to_json) client.add_message(default_message_params) client.flush client.flushed?.should be_true client.results[:results].size.should == 1 client.last_init_time.should == current_init_time end it "resets connection if over a minute old" do client.last_init_time=Time.now.utc-60 current_init_time=client.last_init_time current_init_time.should be < Time.now.utc-59 FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/emails/send", :body => create_success_result(1).to_json) client.add_message(default_message_params) client.flush client.flushed?.should be_true client.results[:results].size.should == 1 client.last_init_time.should be > current_init_time end end describe "#message_buffer_size=" do it "can set the buffer size" do client.message_buffer_size=(10) client.message_buffer_size.should == 10 end it "cannot set an invalid buffer size" do default_buffer_size = 20 client.message_buffer_size=(-1) client.message_buffer_size.should == default_buffer_size client.message_buffer_size=(0) client.message_buffer_size.should == default_buffer_size client.message_buffer_size=(101) client.message_buffer_size.should == default_buffer_size client.message_buffer_size=(1) client.message_buffer_size.should == 1 client.message_buffer_size=(100) client.message_buffer_size.should == 100 end end describe "#delivery_errors" do it "request delivery errors list" do start_date_str="2011-01-01" end_date_str="2011-01-02" FakeWeb.register_uri(:get, "https://api.messagebus.com/api/v3/delivery_errors?startDate=#{start_date_str}&endDate=#{end_date_str}&tag=", :body => json_delivery_errors) expect do response = client.delivery_errors(start_date_str, end_date_str) FakeWeb.last_request.body.should be_nil response.should == json_parse(json_delivery_errors) end.should_not raise_error end end describe "#unsubscribes" do it "request blocked emails list" do start_date_str="2011-01-01T04:30:00+00:00" end_date_str="2011-01-02T04:30:00+00:00" expected_request="https://api.messagebus.com/api/v3/unsubscribes?startDate=#{URI.escape(start_date_str)}&endDate=#{URI.escape(end_date_str)}" FakeWeb.register_uri(:get, expected_request, :body => json_unsubscribes) expect do response = client.unsubscribes(start_date_str, end_date_str) FakeWeb.last_request.body.should be_nil response.should == json_parse(json_unsubscribes) end.should_not raise_error end end describe "#delete_mailing_list_entry" do it "remove from mailing list" do mailing_list_key="test_key" to_email="test@example.com" expected_request="https://api.messagebus.com/api/v3/mailing_list/test_key/entry/test@example.com" FakeWeb.register_uri(:delete, expected_request, :body => json_response_200) expect do response = client.delete_mailing_list_entry(mailing_list_key, to_email) FakeWeb.last_request.body.should be_nil response[:statusCode].should == 200 end.should_not raise_error end end describe "#add_mailing_list_entry" do it "add to mailing list" do mailing_list_key="test_key" merge_fields={"%EMAIL%"=>"test@example.com", "%PARAM1%"=>"test value"} expected_request="https://api.messagebus.com/api/v3/mailing_list/test_key/entries" FakeWeb.register_uri(:post, expected_request, :body => json_response_200) expect do response = client.add_mailing_list_entry(mailing_list_key, merge_fields) FakeWeb.last_request.body.should =~ /mergeField/ response[:statusCode].should == 200 end.should_not raise_error end end describe "#mailing_lists" do it "get mailing lists" do expected_request="https://api.messagebus.com/api/v3/mailing_lists" FakeWeb.register_uri(:get, expected_request, :body => json_mailing_lists) expect do response = client.mailing_lists response.should == json_parse(json_mailing_lists) end.should_not raise_error end end describe "#create_mailing_lists" do it "create a new mailing list" do expected_request="https://api.messagebus.com/api/v3/mailing_lists" FakeWeb.register_uri(:post, expected_request, :body => json_mailing_list_create) expect do response = client.create_mailing_lists("Test List", ["%EMAIL%", "%SOME_TOKEN%"]) response.should == json_parse(json_mailing_list_create) end.should_not raise_error end end describe "#stats" do it "stats" do start_date_str="2011-01-01" end_date_str="2011-01-02" expected_request="https://api.messagebus.com/api/v3/stats?startDate=#{start_date_str}&endDate=#{end_date_str}&tag=" FakeWeb.register_uri(:get, expected_request, :body => json_stats) expect do response = client.stats(start_date_str, end_date_str) response.should == json_parse(json_stats) end.should_not raise_error end end describe "#format_iso_time" do it "formats ISO time in format YYYY-MM-DDTHH:mm:ssZ" do client.format_iso_time(Time.now).should =~ /2\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ/ end end end messagebus-ruby-api-1.0.3/spec/messagebus_ruby_api/cacert.pem0000644000076400007640000000003212570556603023365 0ustar pravipravi# THIS IS ONLY FOR TESTINGmessagebus-ruby-api-1.0.3/spec/spec_core_extensions.rb0000644000076400007640000000122612570556603022145 0ustar pravipravi# Copyright 2012 Mail Bypass, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class Hash def without(key) self.dup.tap{|hash| hash.delete(key)} end end messagebus-ruby-api-1.0.3/.rvmrc0000755000076400007640000000007512570556603015603 0ustar pravipravirvm use ruby-1.9.2-p180-patched@messagebus_ruby_api --create messagebus-ruby-api-1.0.3/README.rdoc0000644000076400007640000000503212570556603016252 0ustar pravipravi= Message Bus Ruby API == Installation gem install messagebus_ruby_api == Basic Use === Start by requiring MessabusApi: require 'messagebus_ruby_api' === Then create an instance of the Messagebus class with your account information client = MessagebusApi::Messagebus.new("") === Sending a single message ==== Create Required Parameters params = { :toEmail => 'apitest1@messagebus.com', :toName => 'EmailUser', :fromEmail => 'api@messagebus.com', :fromName => 'API', :subject => 'Unit Test Message', :customHeaders => ["sender"=>"apitest1@messagebus.com"], :plaintextBody => 'This message is only a test sent by the Ruby Message Bus client library.', :htmlBody => "This message is only a test sent by the Ruby Message Bus client library.", :tags => ['RUBY'] } ==== Send the message client.add_message(params) == Examples The provided examples illustrate how to: - send a single email message in the simplest way - send one or more emails (where the email body is passed with the api call) - send one or more templated emails (where a key referencing a previously stored email body is passed with the api call) - create a mailing list, add and delete mailing list entries and list the existing mailing lists - list recent email unsubscribes - list recent email statistics - list recent delivery errors == SSL Certificates If you encounter SSL certificate problems, use the cacert_info() method to specify a cacert.pem file (remember to specify the full path). The curl site has an up to date version of the file: http://curl.haxx.se/ca/cacert.pem == Tests To run the tests, issue the following command from the root of the project: bundle exec rspec spec/messagebus_ruby_api/client_spec.rb == License Copyright 2012 Mail Bypass, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. == More info Contact Message Bus if you have questions or problems (https://www.messagebus.com/contact) messagebus-ruby-api-1.0.3/Gemfile0000644000076400007640000000032012570556603015732 0ustar pravipravisource "http://rubygems.org" gem 'activesupport' group :test, :development do gem 'rspec', '2.5.0' gem 'rr', '1.0.2' gem 'fakeweb' end # Specify your gem's dependencies in messagebus.gemspec gemspec messagebus-ruby-api-1.0.3/metadata.yml0000644000076400007640000000266312570556603016756 0ustar pravipravi--- !ruby/object:Gem::Specification name: messagebus_ruby_api version: !ruby/object:Gem::Version version: 1.0.3 prerelease: platform: ruby authors: - Message Bus dev team autorequire: bindir: bin cert_chain: [] date: 2012-01-20 00:00:00.000000000Z dependencies: [] description: ! 'Allows you to use the Message Bus API ' email: - messagebus@googlegroups.com executables: [] extensions: [] extra_rdoc_files: [] files: - lib/messagebus_ruby_api/errors.rb - lib/messagebus_ruby_api/messagebus.rb - lib/messagebus_ruby_api/version.rb - lib/messagebus_ruby_api.rb - spec/messagebus_ruby_api/cacert.pem - spec/messagebus_ruby_api/messagebus_spec.rb - spec/spec_core_extensions.rb - spec/spec_helper.rb - README.rdoc - Gemfile - Rakefile - .rvmrc homepage: '' licenses: - APACHE2 post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' required_rubygems_version: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' requirements: [] rubyforge_project: messagebus_ruby_api rubygems_version: 1.8.10 signing_key: specification_version: 3 summary: Send email through the Message Bus service test_files: - spec/messagebus_ruby_api/cacert.pem - spec/messagebus_ruby_api/messagebus_spec.rb - spec/spec_core_extensions.rb - spec/spec_helper.rb messagebus-ruby-api-1.0.3/lib/0000755000076400007640000000000012570556603015212 5ustar pravipravimessagebus-ruby-api-1.0.3/lib/messagebus_ruby_api.rb0000644000076400007640000000143412570556603021571 0ustar pravipravi# Copyright 2012 Mail Bypass, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. dir = File.dirname(__FILE__) require 'net/https' require 'uri' require 'cgi' require "#{dir}/messagebus_ruby_api/errors" require "#{dir}/messagebus_ruby_api/messagebus" require "#{dir}/messagebus_ruby_api/version" messagebus-ruby-api-1.0.3/lib/messagebus_ruby_api/0000755000076400007640000000000012570556603021242 5ustar pravipravimessagebus-ruby-api-1.0.3/lib/messagebus_ruby_api/errors.rb0000644000076400007640000000201612570556603023102 0ustar pravipravi# Copyright 2012 Mail Bypass, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. module MessagebusApi class APIParameterError < StandardError def initialize(problematic_parameter="") super("missing or malformed parameter #{problematic_parameter}") end end class BadAPIKeyError < StandardError end class MissingFileError = 1 && size <= 100) end def message_buffer_size @msg_buffer_size end def flushed? @msg_buffer_flushed end def api_version make_api_get_call(@rest_endpoints[:version]) end def add_message(params, flush_buffer = false) if params.key?(:templateKey) add_template_message(params) else add_email_message(params) end @msg_buffer_flushed = false if flush_buffer || @msg_buffer.size >= @msg_buffer_size flush end return end def flush if (@msg_buffer.size==0) @results=@empty_send_results return end if @msg_type == TEMPLATE endpoint = @rest_endpoints[:templates_send] else endpoint = @rest_endpoints[:emails_send] end json = json_message_from_list(@msg_buffer) if (@last_init_time < Time.now.utc - 60) init_http_connection end @results=make_api_post_call(endpoint, json) @msg_buffer.clear @msg_buffer_flushed = true return end def mailing_lists make_api_get_call(@rest_endpoints[:mailing_lists]) end def create_mailing_lists(list_name, merge_field_keys) json = {:name => list_name, :mergeFieldKeys => merge_field_keys}.to_json @results = make_api_post_call(@rest_endpoints[:mailing_lists], json) @results end def delete_mailing_list_entry(mailing_list_key, email) path = @rest_endpoints[:mailing_lists_entry_email].gsub("%KEY%", mailing_list_key).gsub("%EMAIL%", email) @results = make_api_delete_call(path) @results end def add_mailing_list_entry(mailing_list_key, merge_fields) path = @rest_endpoints[:mailing_lists_entries].gsub("%KEY%", mailing_list_key) json = {:mergeFields => merge_fields}.to_json @results = make_api_post_call(path, json) @results end def unsubscribes(start_date = '', end_date = '') path = "#{@rest_endpoints[:unsubscribes]}?#{date_range(start_date, end_date)}" @results = make_api_get_call(path) @results end def delivery_errors(start_date = '', end_date = '', tag='') path = "#{@rest_endpoints[:delivery_errors]}?#{date_range(start_date, end_date)}&tag=#{URI.escape(tag)}" @results = make_api_get_call(path) @results end def stats(start_date = '', end_date = '', tag = '') path = "#{@rest_endpoints[:stats]}?#{date_range(start_date, end_date)}&tag=#{URI.escape(tag)}" @results = make_api_get_call(path) @results end def cacert_info(cert_file) @http.verify_mode = OpenSSL::SSL::VERIFY_PEER if !File.exists?(cert_file) raise MessagebusApi::MissingFileError.new("Unable to read file #{cert_file}") end @http.ca_file = File.join(cert_file) end def format_iso_time(time) time.strftime("%Y-%m-%dT%H:%M:%SZ") end private def init_http_connection(target_server=DEFAULT_API_ENDPOINT_STRING) if (@http and @http.started?) @http.finish end @last_init_time = Time.now.utc endpoint_url = URI.parse(target_server) @http = Net::HTTP.new(endpoint_url.host, endpoint_url.port) @http.use_ssl = true @http end def common_http_headers {'User-Agent' => @user_agent, 'X-MessageBus-Key' => @api_key} end def rest_post_headers {"Content-Type" => "application/json; charset=utf-8"} end def add_email_message(params) @msg_type = EMAIL if @msg_type == nil @msg_buffer << base_message_params.merge!(params) end def add_template_message(params) @msg_type = TEMPLATE if @msg_type == nil @msg_buffer << base_template_params.merge!(params) end def date_range(start_date, end_date) date_range_str="" if (start_date!="") date_range_str+="startDate=#{start_date}" end if (end_date!="") if (date_range_str!="") date_range_str+="&" end date_range_str+="endDate=#{end_date}" end date_range_str end def set_date(date_string, days_ago) if date_string.length == 0 return date_str_for_time_range(days_ago) end date_string end def date_str_for_time_range(days_ago) format_iso_time(Time.now.utc - (days_ago*86400)) end def json_message_from_list(messages) {:messages => messages}.to_json end def make_api_post_call(path, data) headers = common_http_headers.merge(rest_post_headers) response = @http.request_post(path, data, headers) check_response(response) end def make_api_get_call(path) headers = common_http_headers response = @http.request_get(path, headers) check_response(response) end def make_api_delete_call(path) headers = common_http_headers response = @http.delete(path, headers) check_response(response) end def check_response(response, symbolize_names=true) case response when Net::HTTPSuccess begin return JSON.parse(response.body, :symbolize_names => symbolize_names) rescue JSON::ParserError => e raise MessagebusApi::RemoteServerError.new("JSON parsing error. Response started with #{response.body.slice(0..9)}") end when Net::HTTPClientError, Net::HTTPServerError if (response.body && response.body.size > 0) result = begin JSON.parse(response.body, :symbolize_names => symbolize_names) rescue JSON::ParserError nil end raise MessagebusApi::RemoteServerError.new("#{response.code.to_s}:#{rest_http_error_message(response.code.to_s)}") else raise MessagebusApi::RemoteServerError.new("#{response.code.to_s}:#{rest_http_error_message(response.code.to_s)}") end else raise "Unexpected HTTP Response: #{response.class.name}" end raise "Could not determine response" end def rest_http_error?(status_code) @rest_http_errors.key?(status_code) end def rest_http_error_message(status_code) message = "Unknown Error Code" message = @rest_http_errors[status_code] if rest_http_error?(status_code) message end def define_rest_endpoints { :emails_send => "/api/v3/emails/send", :templates_send => "/api/v3/templates/send", :stats => "/api/v3/stats", :delivery_errors => "/api/v3/delivery_errors", :unsubscribes => "/api/v3/unsubscribes", :mailing_lists => "/api/v3/mailing_lists", :mailing_lists_entries => "/api/v3/mailing_list/%KEY%/entries", :mailing_lists_entry_email => "/api/v3/mailing_list/%KEY%/entry/%EMAIL%", :version => "/api/version" } end def define_rest_http_errors { "400" => "Invalid Request", "401" => "Unauthorized-Missing API Key", "403" => "Unauthorized-Invalid API Key", "404" => "Incorrect URL", "405" => "Method not allowed", "406" => "Format not acceptable", "408" => "Request Timeout", "409" => "Conflict", "410" => "Object missing or deleted", "413" => "Too many messages in request", "415" => "POST JSON data invalid", "422" => "Unprocessable Entity", "500" => "Internal Server Error", "501" => "Not Implemented", "503" => "Service Unavailable", "507" => "Insufficient Storage" } end def base_response_params {:statusCode => 0, :statusMessage => "", :statusTime => "1970-01-01T00:00:00.000Z"} end def base_message_params {:toEmail => '', :fromEmail => '', :subject => '', :toName => '', :fromName => '', :plaintextBody => '', :htmlBody => '', :customHeaders => {}, :tags => []} end def base_template_params {:toEmail => '', :toName => '', :templateKey => '', :mergeFields => {}, :customHeaders => {}} end end end messagebus-ruby-api-1.0.3/Rakefile0000644000076400007640000000006312570556603016110 0ustar pravipravirequire 'bundler' Bundler::GemHelper.install_tasks