Permalink
Find file
Fetching contributors…
Cannot retrieve contributors at this time
79 lines (68 sloc) 2.38 KB
require 'sinatra'
require 'json'
module Campmoxey
class App < Sinatra::Base
# http://www.campaignmonitor.com/api/method/subscribers-getactive/
get("/Subscribers/GetActive") do
proxy_on(params) do
subscribers = Campaigning::List.new(list_id).get_all_active_subscribers.reverse
limit = limit_as_range(params.delete("limit"))
subscribers = subscribers[limit] if limit
subscribers = subscribers.map do |s|
always = {"name" => s.name, "email" => s.emailAddress}
s.customFields.inject(always) { |acc, field| append_value(acc, field.key, field.value) }
end
{"success" => "Nice job, mate", "subscribers" => subscribers}
end
end
# Need to be paranoid about who can call these actions. Check HTTP_REFERRER?
# http://www.campaignmonitor.com/api/method/subscriber-add/
get("/Subscriber/Add") do
proxy_on(params) do
email = params.delete("email")
name = params.delete("name") || ""
custom_fields = params
response = Campaigning::Subscriber.new(email, name).add!(list_id, custom_fields)
{"success" => "Nice job, mate"}
end
end
private
# Your block should return the json to be sent back on success. This will handle errors and require a
# :callback param
def proxy_on(params, &block)
callback = enforce(params, "callback")
content_type 'text/javascript', :charset => 'utf-8'
status 200
begin
json = yield
rescue RuntimeError => e
code, message = e.message.split("-")
json = {"error" => message, "code" => code}
rescue SocketError => e
json = {"error" => "Whoops! We had a big problem. We're working on it though", "code" => "500"}
end
%Q{#{callback}(#{json.to_json})}
end
def enforce(hash, key)
value = hash.delete(key)
halt 403, "Expecting #{key.inspect}" unless value
value
end
def list_id; Campmoxey::Configuration.default_list_id; end
def append_value(hash, key, value)
(hash[key] = hash[key] ? Array(hash[key]) : "") << value
hash
end
def limit_as_range(limit)
return nil unless limit
if limit =~ /^\d+\.\.\d+$/
rangers = limit.split("..").map(&:to_i)
(rangers.first..rangers.last)
elsif limit =~ /^\d+$/
limit.to_i
else
nil
end
end
end # App
end # Campmoxey