Class: EventMachine::ApnManager::Manager

Inherits:
Object
  • Object
show all
Defined in:
lib/em_apn_manager/manager.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.run(options = {}) ⇒ Object



15
16
17
18
19
# File 'lib/em_apn_manager/manager.rb', line 15

def self.run options = {}
  self.new.tap do |manager|
    manager.run options
  end
end

Instance Method Details

#run(options = {}) ⇒ Object

options = port



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/em_apn_manager/manager.rb', line 22

def run options = {}
  @redis = EM::Hiredis.connect options[:redis]

  ### launch a new connect to apple when detected any pushs.
  @redis.pubsub.subscribe('push-notification') do |msg|
    msg_hash = Yajl::Parser.parse(msg) # FIXME might be some wrong json

    # save the cert to local first, since the start_tls read from file.
    cert_filename = save_cert_to_file msg_hash["cert"]

    # cert filename is a key for connection pool
    client = $connection_pool[cert_filename]

    ### Create client connection if doesn't exist in pool.
    if client.nil?
      opts = {:env => msg_hash["env"], :cert => cert_filename}
      client = EM::ApnManager::Client.new(options.merge(opts))
      # Store the connection to pool
      $connection_pool[cert_filename] = client
    end

    ### send message directly if connection was connected.
    ### TODO you can bind on_close, on_open, on_error events.
    notification = EM::ApnManager::Notification.new(msg_hash["token"], :alert => msg_hash["message"])
    if client.connected?
      client.deliver(notification)
    else
      # if connection not connected, set callback block to deliver notification, and connect to apple server.
      client.on_open do
        client.deliver(notification)
      end
      client.connect
    end
  end
end