Created
October 6, 2010 08:41
-
-
Save cyx/613032 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'uri' | |
require 'net/http' | |
require 'net/https' | |
class MadMimi | |
class MadMimiError < StandardError; end | |
BASE_URL = 'api.madmimi.com' | |
NEW_LISTS_PATH = '/audience_lists' | |
AUDIENCE_MEMBERS_PATH = '/audience_members' | |
AUDIENCE_LISTS_PATH = '/audience_lists/lists.xml' | |
MEMBERSHIPS_PATH = '/audience_members/%email%/lists.xml' | |
SUPPRESSED_SINCE_PATH = '/audience_members/suppressed_since/%timestamp%.txt' | |
PROMOTIONS_PATH = '/promotions.xml' | |
MAILING_STATS_PATH = '/promotions/%promotion_id%/mailings/%mailing_id%.xml' | |
SEARCH_PATH = '/audience_members/search.xml' | |
MAILER_PATH = '/mailer' | |
MAILER_TO_LIST_PATH = '/mailer/to_list' | |
def initialize(username, api_key) | |
@api_settings = { :username => username, :api_key => api_key } | |
end | |
def username | |
@api_settings[:username] | |
end | |
def api_key | |
@api_settings[:api_key] | |
end | |
def default_opt | |
{ :username => username, :api_key => api_key } | |
end | |
def send_mail(opt, yaml_body) | |
options = opt.dup | |
options[:body] = yaml_body.to_yaml | |
if !options[:list_name].nil? | |
do_request(MAILER_TO_LIST_PATH, :post, options, true) | |
else | |
do_request(MAILER_PATH, :post, options, true) | |
end | |
end | |
private | |
# Refactor this method asap | |
def do_request(path, req_type = :get, options = {}, transactional = false) | |
options = options.merge(default_opt) | |
form_data = options.inject({}) { |m, (k, v)| m[k.to_s] = v; m } | |
resp = href = "" | |
case req_type | |
when :get then | |
begin | |
http = Net::HTTP.new(BASE_URL, 80) | |
http.start do |http| | |
req = Net::HTTP::Get.new(path) | |
req.set_form_data(form_data) | |
response = http.request(req) | |
resp = response.body.strip | |
end | |
resp | |
rescue SocketError | |
raise "Host unreachable." | |
end | |
when :post then | |
begin | |
if transactional == true | |
http = Net::HTTP.new(BASE_URL, 443) | |
http.use_ssl = true | |
http.verify_mode = OpenSSL::SSL::VERIFY_NONE | |
else | |
http = Net::HTTP.new(BASE_URL, 80) | |
end | |
http.start do |http| | |
req = Net::HTTP::Post.new(path) | |
req.set_form_data(form_data) | |
response = http.request(req) | |
resp = response.body.strip | |
end | |
rescue SocketError | |
raise "Host unreachable." | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment