lib/rhosync/ping/android.rb in rhosync-2.1.7 vs lib/rhosync/ping/android.rb in rhosync-2.1.10

- old
+ new

@@ -1,25 +1,43 @@ -require 'net/https' +require 'rest_client' require 'uri' + module Rhosync class Android + class StaleAuthToken < Exception; end + class InvalidAuthToken < Exception; end + class AndroidPingError < Exception; end + def self.ping(params) begin settings = get_config(Rhosync.base_directory)[Rhosync.environment] authtoken = settings[:authtoken] - - url = URI.parse('https://android.apis.google.com/c2dm/send') - - req = Net::HTTP::Post.new url.path, 'Authorization' => "GoogleLogin auth=#{authtoken}" - req.set_form_data c2d_message(params) - - http = Net::HTTP.new(url.host, url.port) - http.use_ssl = true - http.verify_mode = OpenSSL::SSL::VERIFY_NONE - res = http.request(req) - + + RestClient.post( + 'https://android.apis.google.com/c2dm/send', c2d_message(params), + :authorization => "GoogleLogin auth=#{authtoken}" + ) do |response, request, result, &block| + # return exceptions based on response code & body + case response.code + when 200 + # TODO: Automate authtoken updates + if response[:update_client_auth] + raise StaleAuthToken.new( + "Stale auth token, please update :authtoken: in settings.yml." + ) + # body will contain the exception class + elsif response.body =~ /^Error=(.*)$/ + raise AndroidPingError.new("Android ping error: #{$1 || ''}") + else + response.return!(request, result, &block) + end + when 401, 403 + raise InvalidAuthToken.new("Invalid auth token, please update :authtoken: in settings.yml.") + end + end rescue Exception => error - log "Error while sending ping: #{error}" + log error + log error.backtrace.join("\n") raise error end end def self.c2d_message(params)