Class: Pling::GCM::Gateway

Inherits:
Pling::Gateway show all
Defined in:
lib/pling/gcm/gateway.rb

Overview

Pling gateway to communicate with Google’s Android GCM service.

The gateway is implemented using Faraday. It defaults to Faraday’s :net_http adapter. You can customize the adapter by passing the :adapter configuration.

Examples:


Pling::GCM::Gateway.new({
  :key                => 'your-api-key', # Your google account's api key (Required)
  :push_url           => 'http://...',   # The push url to use (Optional, Default: GCM default authentication url)
  :adapter            => :net_http,      # The Faraday adapter you want to use (Optional, Default: :net_http)
  :connection         => {}              # Options you want to pass to Faraday (Optional, Default: {})
})

Instance Method Summary collapse

Methods inherited from Pling::Gateway

#deliver, discover, handled_types, handles, #handles?, #setup!, #teardown!

Constructor Details

#initialize(configuration) ⇒ Gateway

Initializes a new gateway to Apple’s Push Notification service

Parameters:

  • configuration (Hash)

Options Hash (configuration):

  • :key (String)

    Your google account’s api key (Required)

  • :push_url (String)

    The URL to push to (Optional)

  • :adapter (Symbol)

    The Faraday adapter to use (Optional)

  • :connection (String)

    Any options for Faraday (Optional)

Raises:

  • Pling::AuthenticationFailed



34
35
36
37
# File 'lib/pling/gcm/gateway.rb', line 34

def initialize(configuration)
  super
  require_configuration([:key])
end

Instance Method Details

#deliver!(message, device) ⇒ Object

Sends the given message to the given device.

Parameters:

  • message (#to_pling_message)
  • device (#to_pling_device)

Raises:

  • Pling::DeliveryFailed



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/pling/gcm/gateway.rb', line 45

def deliver!(message, device)
  data = {
    :registration_ids => [device.identifier],
    :data => {
      :body  => message.body,
      :badge => message.badge,
      :sound => message.sound,
      :subject => message.subject
    }.delete_if { |_, value| value.nil? },
    :collapse_key => "collapse-#{message.body.hash}"
  }

  data[:data].merge!(message.payload) if configuration[:payload] && message.payload

  response = connection.post(configuration[:push_url], data, { :Authorization => "key=#{configuration[:key]}"})

  if !response.success? || response.body['failure'].to_i > 0
    error_class = Pling::GCM.const_get(response.body['results'][0]['error']) rescue Pling::DeliveryFailed
    raise error_class.new("GCM Delivery failed: [#{response.status}] #{response.body}", message, device)
  end
end