Skip to content

Commit

Permalink
switch to faraday http request agent
Browse files Browse the repository at this point in the history
  • Loading branch information
mgrishko committed Aug 29, 2024
1 parent d8626c4 commit c5d44d9
Show file tree
Hide file tree
Showing 18 changed files with 133 additions and 143 deletions.
78 changes: 33 additions & 45 deletions lib/mailjet/connection.rb
Original file line number Diff line number Diff line change
@@ -1,40 +1,32 @@
require 'rest_client'
require 'faraday'
require 'yajl'

module Mailjet
class Connection

attr_accessor :adapter, :public_operations, :read_only, :perform_api_call, :read_timeout, :open_timeout
attr_accessor :adapter, :public_operations, :read_only, :perform_api_call, :api_key, :secret_key, :options
alias :read_only? :read_only

def [](suburl, &new_block)
broken_url = url.split("/")
broken_url = uri.path.split("/")
if broken_url.include?("contactslist") && broken_url.include?("managemanycontacts") && broken_url.last.to_i > 0
self.class.new(url, options[:user], options[:password], options)
self.class.new(uri, api_key, secret_key, options)
else
self.class.new(concat_urls(url, suburl), options[:user], options[:password], options)
self.class.new(concat_urls(suburl), api_key, secret_key, options)
end
end

def initialize(end_point, api_key, secret_key, options = {})
# #charles proxy
# RestClient.proxy = "http://127.0.0.1:8888"
# #
# #Output for debugging
# RestClient.log =
# Object.new.tap do |proxy|
# def proxy.<<(message)
# Rails.logger.info message
# end
# end
# #
adapter_class = options[:adapter_class] || RestClient::Resource
self.options = options
self.api_key = api_key
self.secret_key = secret_key
self.public_operations = options[:public_operations] || []
self.read_only = options[:read_only]
self.read_timeout = options[:read_timeout]
self.open_timeout = options[:open_timeout]
# self.adapter = adapter_class.new(end_point, options.merge(user: api_key, password: secret_key, :verify_ssl => false, content_type: 'application/json'))
self.adapter = adapter_class.new(end_point, options.merge(user: api_key, password: secret_key, content_type: 'application/json', read_timeout: self.read_timeout, open_timeout: self.open_timeout))
self.adapter = Faraday.new(end_point, ssl: { verify: false }) do |conn|
conn.response :raise_error, include_request: true
conn.request :authorization, :basic, api_key, secret_key
conn.headers['Content-Type'] = 'application/json'
end
self.perform_api_call = options.key?(:perform_api_call) ? options[:perform_api_call] : true
end

Expand All @@ -54,34 +46,31 @@ def delete(additional_headers = {}, &block)
handle_api_call(:delete, additional_headers, &block)
end

def options
self.adapter.options
end

def concat_urls(*options)
self.adapter.concat_urls(*options)
def concat_urls(suburl)
self.adapter.build_url(suburl.to_s)
end

def url
self.adapter.url
def uri
self.adapter.build_url
end

private

def handle_api_call(method, additional_headers = {}, payload = {}, &block)
formatted_payload = (additional_headers[:content_type] == :json) ? Yajl::Encoder.encode(payload) : payload
formatted_payload = (additional_headers["Content-Type"] == 'application/json') ? Yajl::Encoder.encode(payload) : payload
raise Mailjet::MethodNotAllowed unless method_allowed(method)

if self.perform_api_call
if [:get, :delete].include?(method)
@adapter.send(method, additional_headers, &block)
@adapter.send(method, nil, additional_headers[:params], &block)
else
@adapter.send(method, formatted_payload, additional_headers, &block)
@adapter.send(method, nil, formatted_payload, additional_headers, &block)
end
else
return Yajl::Encoder.encode({'Count' => 0, 'Data' => [mock_api_call: true], 'Total' => 0})
end
rescue RestClient::Exception => e

rescue Faraday::Error => e
handle_exception(e, additional_headers, formatted_payload)
end

Expand All @@ -91,41 +80,41 @@ def method_allowed(method)
end

def handle_exception(e, additional_headers, payload = {})
return e.http_body if e.http_headers[:content_type].include?("text/plain")
return e.response_body if e.response_headers[:content_type].include?("text/plain")

params = additional_headers[:params] || {}
formatted_payload = (additional_headers[:content_type] == :json) ? Yajl::Parser.parse(payload) : payload
params = params.merge!(formatted_payload) if formatted_payload.is_a?(Hash)

http_body = if e.http_headers[:content_type].include?("application/json")
e.http_body
response_body = if e.response_headers[:content_type].include?("application/json")
e.response_body
else
"{}"
end

if sent_invalid_email?(e.http_body, @adapter.url)
return e.http_body
if sent_invalid_email?(e.response_body, @adapter.build_url)
return e.response_body
else
raise communication_error(e)
end
end

def communication_error(e)
if e.respond_to?(:response) && e.response
return case e.response.code
return case e.response_status
when Unauthorized::CODE
Unauthorized.new(e.message, e.response)
Unauthorized.new(e.message, e)
when BadRequest::CODE
BadRequest.new(e.message, e.response)
BadRequest.new(e.message, e)
else
CommunicationError.new(e.message, e.response)
CommunicationError.new(e.message, e)
end
end
CommunicationError.new(e.message)
end

def sent_invalid_email?(error_http_body, url)
return false unless url.include?('v3.1/send')
def sent_invalid_email?(error_http_body, uri)
return false unless uri.path.include?('v3.1/send')
return unless error_http_body

parsed_body = Yajl::Parser.parse(error_http_body)
Expand All @@ -138,6 +127,5 @@ def sent_invalid_email?(error_http_body, url)
end

class MethodNotAllowed < StandardError

end
end
6 changes: 3 additions & 3 deletions lib/mailjet/exception/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@ def initialize(message = nil, response = nil)
@code = if response.nil?
NOCODE
else
response.code
response.response_status
end

api_message = begin
Yajl::Parser.parse(response.body)['ErrorMessage']
Yajl::Parser.parse(response.response_body)['ErrorMessage']
rescue Yajl::ParseError
response.body
response.response_body
rescue NoMethodError
"Unknown API error"
rescue
Expand Down
48 changes: 24 additions & 24 deletions lib/mailjet/resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
module Mailjet
module Resource
# define here available options for filtering
OPTIONS = [:version, :url, :perform_api_call, :api_key, :secret_key, :read_timeout, :open_timeout]
OPTIONS = [:version, :url, :perform_api_call, :api_key, :secret_key]

NON_JSON_URLS = ['v3/send/message'] # urls that don't accept JSON input
DATA_URLS = ['plain', 'csv'] # url for send binary data , 'CSVError/text:csv'
Expand All @@ -39,21 +39,20 @@ def self.default_connection(options = {})
options[:secret_key] || Mailjet.config.secret_key,
public_operations: public_operations,
read_only: read_only,
perform_api_call: options[:perform_api_call],
open_timeout: options[:open_timeout],
read_timeout: options[:read_timeout])
perform_api_call: options[:perform_api_call])
end

def self.default_headers
if NON_JSON_URLS.include?(self.resource_path) # don't use JSON if Send API
default_headers = { accept: :json, accept_encoding: :deflate }
elsif DATA_URLS.any? { |data_type| default_headers = { content_type: "text/#{data_type}" } if
self.resource_path.include?(data_type)
}
default_headers = { 'Accept' =>'application/json', 'Accept-Encoding' => 'deflate' }
elsif DATA_URLS.any? do |data_type|
default_headers = { 'Content-Type' => "text/#{data_type}" } if self.resource_path.include?(data_type)
end
else
default_headers = { accept: :json, accept_encoding: :deflate, content_type: :json } #use JSON if *not* Send API
# use JSON if *not* Send API
default_headers = {'Content-Type' =>'application/json', 'Accept' =>'application/json', 'Accept-Encoding' => 'deflate'}
end
return default_headers.merge!(user_agent: "mailjet-api-v3-ruby/#{Gem.loaded_specs["mailjet"].version}")
return default_headers.merge!('User-Agent' => "mailjet-api-v3-ruby/#{Gem.loaded_specs["mailjet"].version}")
end
end
end
Expand All @@ -69,7 +68,7 @@ def all(params = {}, options = {})
opts = define_options(options)
params = format_params(params)
response = connection(opts).get(default_headers.merge!(params: params))
attribute_array = parse_api_json(response)
attribute_array = parse_api_json(response.body)
attribute_array.map{ |attributes| instanciate_from_api(attributes) }
rescue Mailjet::ApiError => error
raise error
Expand All @@ -78,7 +77,7 @@ def all(params = {}, options = {})
def count(options = {})
opts = define_options(options)
response_json = connection(opts).get(default_headers.merge!(params: {limit: 1, countrecords: 1}))
response_hash = Yajl::Parser.parse(response_json)
response_hash = Yajl::Parser.parse(response_json.body)
response_hash['Total']
rescue Mailjet::ApiError => error
raise error
Expand All @@ -95,7 +94,7 @@ def find(id, job_id = nil, options = {})
opts = define_options(options)
self.resource_path = create_action_resource_path(normalized_id, job_id) if self.action

attributes = parse_api_json(connection(opts)[normalized_id].get(default_headers)).first
attributes = parse_api_json(connection(opts)[normalized_id].get(default_headers).body).first
instanciate_from_api(attributes)

rescue Mailjet::CommunicationError => e
Expand All @@ -106,6 +105,14 @@ def find(id, job_id = nil, options = {})
end
end


def find_by_id(id, options = {})
# if action method, ammend url to appropriate id
opts = define_options(options)
self.resource_path = create_action_resource_path(id) if self.action
connection(opts).get(default_headers)
end

def create(attributes = {}, options = {})
# if action method, ammend url to appropriate id
opts = define_options(options)
Expand Down Expand Up @@ -139,19 +146,12 @@ def delete(id, options = {})
def send_data(id, binary_data = nil, options = {})
opts = define_options(options)
self.resource_path = create_action_resource_path(id) if self.action
response = connection(opts).post(binary_data, default_headers.merge({'Content-Length' => "#{binary_data.size}", 'Transfer-Encoding' => 'chunked'}))

response_hash = Yajl::Parser.parse(connection(opts).post(binary_data, default_headers))
response_hash = response.respond_to?(:body) ? Yajl::Parser.parse(response.body) : Yajl::Parser.parse(response)
response_hash['ID'] ? response_hash['ID'] : response_hash
end

def find_by_id(id, options = {})
# if action method, ammend url to appropriate id
opts = define_options(options)
self.resource_path = create_action_resource_path(id) if self.action

connection(opts).get(default_headers)
end

def instanciate_from_api(attributes = {})
self.new(attributes.merge!(persisted: true))
end
Expand Down Expand Up @@ -284,9 +284,9 @@ def save(options = {})
if opts[:perform_api_call] && !persisted?
# get attributes only for entity creation
self.attributes = if self.resource_path == 'send'
Yajl::Parser.parse(response)
Yajl::Parser.parse(response.body)
else
parse_api_json(response).first
parse_api_json(response.body).first
end
end

Expand Down
2 changes: 1 addition & 1 deletion lib/mailjet/resources/campaigndraft_detailcontent.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def self.find(id, job_id = nil, options = {})
opts = define_options(options)
self.resource_path = create_action_resource_path(id, job_id) if self.action

raw_data = parse_api_json(connection(opts)[id].get(default_headers))
raw_data = parse_api_json(connection(opts)[id].get(default_headers).body)

raw_data.map do |entity|
instanciate_from_api(entity)
Expand Down
2 changes: 1 addition & 1 deletion lib/mailjet/resources/contact_getcontactslists.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def self.find(id, job_id = nil, options = {})
opts = define_options(options)
self.resource_path = create_action_resource_path(id, job_id) if self.action

raw_data = parse_api_json(connection(opts).get(default_headers))
raw_data = parse_api_json(connection(opts).get(default_headers).body)

raw_data.map do |entity|
instanciate_from_api(entity)
Expand Down
2 changes: 1 addition & 1 deletion lib/mailjet/resources/messagehistory.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def self.find(id, job_id = nil, options = {})
opts = define_options(options)
self.resource_path = create_action_resource_path(id, job_id) if self.action

raw_data = parse_api_json(connection(opts)[id].get(default_headers))
raw_data = parse_api_json(connection(opts)[id].get(default_headers).body)

raw_data.map do |entity|
instanciate_from_api(entity)
Expand Down
2 changes: 1 addition & 1 deletion lib/mailjet/resources/messageinformation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def self.find(id, job_id = nil, options = {})
opts = define_options(options)
self.resource_path = create_action_resource_path(id, job_id) if self.action

raw_data = parse_api_json(connection(opts)[id].get(default_headers))
raw_data = parse_api_json(connection(opts)[id].get(default_headers).body)

raw_data.map do |entity|
instanciate_from_api(entity)
Expand Down
2 changes: 1 addition & 1 deletion lib/mailjet/resources/openinformation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def self.find(id, job_id = nil, options = {})
opts = define_options(options)
self.resource_path = create_action_resource_path(id, job_id) if self.action

raw_data = parse_api_json(connection(opts)[id].get(default_headers))
raw_data = parse_api_json(connection(opts)[id].get(default_headers).body)

raw_data.map do |entity|
instanciate_from_api(entity)
Expand Down
2 changes: 1 addition & 1 deletion lib/mailjet/resources/template_detailcontent.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def self.find(id, options = {})

opts = define_options(options)
response = connection(opts).get(default_headers)
attributes = parse_api_json(response).first
attributes = parse_api_json(response.body).first

instanciate_from_api(attributes)
rescue Mailjet::CommunicationError => e
Expand Down
2 changes: 1 addition & 1 deletion lib/mailjet/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module Mailjet
VERSION = "1.7.11"
VERSION = "1.8.0"
end
2 changes: 1 addition & 1 deletion mailjet.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Gem::Specification.new do |s|

s.add_dependency "activesupport", ">= 5.0.0"
s.add_dependency "rack", ">= 1.4.0"
s.add_dependency "rest-client", ">= 2.1.0"
s.add_dependency 'faraday', "~> 2.1"
s.add_dependency "yajl-ruby"
s.add_development_dependency "actionmailer", ">= 5.0.0"
s.add_development_dependency "rake"
Expand Down
4 changes: 0 additions & 4 deletions spec/mailer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,3 @@ def test_email
:template_name => 'test_email.html.erb')
end
end

email = Mailer.test_email
puts email
# email.deliver
Loading

0 comments on commit c5d44d9

Please sign in to comment.