Created
December 15, 2009 21:18
-
-
Save spiceee/257317 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
module Telephone | |
module Push | |
class Config | |
class FileNotFoundException < StandardError;end | |
class MissingKeyException < StandardError;end | |
attr_accessor :params | |
def initialize | |
path = RAILS_ROOT + '/config/urbanairship.yml' | |
unless File.exist? path | |
raise FileNotFoundException.new("File #{path} not found.") | |
else | |
@params = YAML::load(ERB.new(IO.read(path)).result)[Rails.env] | |
@params.symbolize_keys! | |
if self.params.keys.to_set != Set.new([:app_key, :app_secret, :app_master_secret]) | |
raise MissingKeyException.new("#{path} does not include one necessary key.") | |
end | |
end | |
end | |
end | |
class Notification | |
attr_accessor :token, :response | |
def initialize(token=nil) | |
@token = token | |
end | |
def method_missing(method_id, *args) | |
if method_id.id2name =~ /^do_(get|post|put|delete|head)$/ | |
do_request($1, args) | |
elsif method_id.id2name =~ /^notify_(registration|push|batch)$/ | |
self.send("do_#{api_method($1)}", $1, args) | |
else | |
super | |
end | |
end | |
def respond_to?(method_symbol, include_private = false) | |
matches_dynamic_method?(method_symbol) || super | |
end | |
def do_request(*args) | |
type, resource, payload = args.flatten.each {} | |
request = Net::HTTP.module_eval("#{type.capitalize}.new '#{path_to(resource)}'") | |
request.basic_auth(PUSH_CONFIG[:app_key], secret(resource)) | |
request.content_type = 'application/json' | |
request.body = payload.to_json if payload | |
conn = Net::HTTP.new('go.urbanairship.com', 443) | |
conn.use_ssl = true | |
conn.start {|http| @response = http.request request } | |
end | |
private | |
def api_method(resource) | |
if resource == 'registration' | |
"put" | |
elsif resource == 'push' | |
"post" | |
elsif resource == 'batch' | |
"post" | |
end | |
end | |
def secret(resource) | |
resource == 'push' ? PUSH_CONFIG[:app_master_secret] : PUSH_CONFIG[:app_secret] | |
end | |
def path_to(resource) | |
if resource == 'registration' | |
"/api/device_tokens/" << @token | |
elsif resource == 'push' | |
"/api/push/" | |
elsif resource == 'batch' | |
"/api/push/batch/" | |
end | |
end | |
def matches_dynamic_method?(method_name) | |
method_name.to_s =~ /^notify_(registration|push|batch)$/ | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment