Class: Rhoconnect::Gcm

Inherits:
Object
  • Object
show all
Defined in:
lib/rhoconnect/ping/gcm.rb

Defined Under Namespace

Classes: GCMPingError, InvalidApiKey

Class Method Summary collapse

Class Method Details

.gcm_message(params) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rhoconnect/ping/gcm.rb', line 44

def self.gcm_message(params)
  params.reject! {|k,v| v.nil? || v.length == 0}
  data = {}
  data['registration_ids'] = [params['device_pin'].to_s]
  data['collapse_key'] = (rand * 100000000).to_i.to_s
  data['data'] = {}
  data['data']['do_sync'] = params['sources'] ? params['sources'].join(',') : ''
  data['data']['alert'] = params['message'] if params['message']
  data['data']['vibrate'] = params['vibrate'] if params['vibrate']
  data['data']['sound'] = params['sound'] if params['sound']
  data['data']['phone_id'] = params['phone_id'] if params['phone_id']
  data
end

.ping(params) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/rhoconnect/ping/gcm.rb', line 8

def self.ping(params)
  begin
    gcm_api_key = Rhoconnect.settings[:gcm_api_key]
    raise InvalidApiKey.new("Missing `:gcm_api_key:` option in settings/settings.yml") unless gcm_api_key

    send_ping_to_device(gcm_api_key, params)
  rescue InvalidApiKey => error
    log error
    log error.backtrace.join("\n")
    raise error
  rescue Exception => error
    log error
    log error.backtrace.join("\n")
    raise error
  end
end

.send_ping_to_device(api_key, params) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/rhoconnect/ping/gcm.rb', line 25

def self.send_ping_to_device(api_key,params)
  RestClient.post(
    'https://android.googleapis.com/gcm/send', gcm_message(params).to_json,
    :authorization => "key=#{api_key}",
    :content_type => :json
  ) do |response, request, result, &block|
    # return exceptions based on response code & body
    case response.code
    when 200
      if response.body =~ /^Error=(.*)$/
        raise GCMPingError.new("GCM ping error: #{$1 || ''}")
      end
      response.return!(request, result, &block)
    when 401, 403
      raise InvalidApiKey.new("Invalid GCM api key. Obtain new api key from GCM service.")
    end
  end
end