Module: ApplePushNotification

Defined in:
lib/apple_push_notification.rb,
lib/apple_push_notification/acts_as_pushable.rb

Defined Under Namespace

Modules: ActsAsPushable

Constant Summary collapse

APN_PORT =
2195
@@apn_cert =
nil
@@apn_host =
nil

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.apn_development?Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/apple_push_notification.rb', line 23

def self.apn_development?
  @@apn_enviroment != :production
end

.apn_enviromentObject



19
20
21
# File 'lib/apple_push_notification.rb', line 19

def self.apn_enviroment
  @@apn_enviroment
end

.apn_enviroment=(enviroment) ⇒ Object



31
32
33
34
35
36
37
38
# File 'lib/apple_push_notification.rb', line 31

def self.apn_enviroment= enviroment
  @@apn_enviroment = enviroment.to_sym
  @@apn_host = self.apn_production? ? "gateway.push.apple.com" : "gateway.sandbox.push.apple.com"
  cert = self.apn_production? ? "apn_production.pem" : "apn_development.pem"
  path = File.join(File.expand_path(RAILS_ROOT), "config", "certs", cert)
  @@apn_cert = File.exists?(path) ? File.read(path) : nil
  raise "Missing apple push notification certificate in #{path}" unless @@apn_cert
end

.apn_production?Boolean

Returns:

  • (Boolean)


27
28
29
# File 'lib/apple_push_notification.rb', line 27

def self.apn_production?
  @@apn_enviroment == :production
end

.extended(base) ⇒ Object



6
7
8
9
10
11
12
13
# File 'lib/apple_push_notification.rb', line 6

def self.extended(base)
  # Added device_token attribute if not included by acts_as_pushable
  unless base.respond_to?(:acts_as_push_options)
    base.class_eval do
      attr_accessor :device_token
    end
  end
end

.send_notification(token, options = {}) ⇒ Object



61
62
63
64
65
66
# File 'lib/apple_push_notification.rb', line 61

def self.send_notification token, options = {}
  d = Object.new
  d.extend ApplePushNotification
  d.device_token = token
  d.send_notification options
end

Instance Method Details

#send_notification(options) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/apple_push_notification.rb', line 42

def send_notification options
  raise "Missing apple push notification certificate" unless @@apn_cert

  ctx = OpenSSL::SSL::SSLContext.new
  ctx.key = OpenSSL::PKey::RSA.new(@@apn_cert)
  ctx.cert = OpenSSL::X509::Certificate.new(@@apn_cert)

  s = TCPSocket.new(@@apn_host, APN_PORT)
  ssl = OpenSSL::SSL::SSLSocket.new(s, ctx)
  ssl.sync = true
  ssl.connect

  ssl.write(self.apn_message_for_sending(options))
  ssl.close
  s.close
rescue SocketError => error
  raise "Error while sending notifications: #{error}"
end