class Rapnd::Daemon

Attributes

apple[RW]
cert[RW]
connected[RW]
host[RW]
logger[RW]
queue[RW]
redis[RW]

Public Class Methods

new(options = {}) click to toggle source
# File lib/rapnd/daemon.rb, line 13
def initialize(options = {})
  options[:redis_host]  ||= 'localhost'
  options[:redis_port]  ||= '6379'
  options[:host]        ||= 'gateway.sandbox.push.apple.com'
  options[:queue]       ||= 'rapnd_queue'
  options[:password]    ||= ''
  raise 'No cert provided!' unless options[:cert]
  
  redis_options = { :host => options[:redis_host], :port => options[:redis_port] }
  redis_options[:password] = options[:redis_password] if options.has_key?(:redis_password)
  
  @redis = Redis.new(redis_options)
  @queue = options[:queue]
  @cert = options[:cert]
  @host = options[:host]
  @logger = Logger.new("#{options[:dir]}/log/#{options[:queue]}.log")
  @logger.info "Listening on queue: #{self.queue}"
end

Public Instance Methods

connect!() click to toggle source
# File lib/rapnd/daemon.rb, line 32
def connect!
  @logger.info 'Connecting...'
  @context      = OpenSSL::SSL::SSLContext.new
  @context.cert = OpenSSL::X509::Certificate.new(File.read(@cert))
  @context.key  = OpenSSL::PKey::RSA.new(File.read(@cert), @password)

  @sock         = TCPSocket.new(@host, 2195)
  self.apple    = OpenSSL::SSL::SSLSocket.new(@sock, @context)
  self.apple.sync = true
  self.apple.connect
  
  self.connected = true
  @logger.info 'Connected!'
  
  return @sock, @ssl
end
run!() click to toggle source
# File lib/rapnd/daemon.rb, line 49
def run!
  loop do
    begin
      message = @redis.blpop(self.queue, 1)
      if message
        notification = Rapnd::Notification.new(Marshal.load(message.last))
        self.connect! unless self.connected
        @logger.info "Sending #{notification.device_token}: #{notification.json_payload}"
        self.apple.write(notification.to_bytes)
      end
    rescue Exception => e
      if e.class == Interrupt || e.class == SystemExit
        @logger.info "Shutting down..."
        exit(0)
      end
      self.connect!
      if notification
        @logger.info "Trying again for: #{notification.json_payload}"
        self.apple.write(notification.to_bytes)
      end
      @logger.error "Encountered error: #{e}"
    end
  end
end