Class: LeadZeppelin::APNS::Application

Inherits:
Object
  • Object
show all
Defined in:
lib/lead_zeppelin/apns/application.rb

Constant Summary collapse

GATEWAY_POOL_SIZE =
3

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(identifier, opts = {}) ⇒ Application

Returns a new instance of Application.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/lead_zeppelin/apns/application.rb', line 8

def initialize(identifier, opts={})
  @identifier = identifier
  @opts = opts

  @gateway_pool = GatewayPool.new opts[:gateway_pool_size] || GATEWAY_POOL_SIZE

  @ssl_context = OpenSSL::SSL::SSLContext.new

  if opts[:p12]
    pem = OpenSSL::PKCS12.new opts[:p12], opts[:p12_pass]
    @ssl_context.cert = pem.certificate
    @ssl_context.key  = pem.key
  elsif opts[:pem]
    @ssl_context.cert = OpenSSL::X509::Certificate.new opts[:pem]
    @ssl_context.key  = OpenSSL::PKey::RSA.new opts[:pem], opts[:pem_pass]
  else
    raise ArgumentError, 'opts[:p12] or opts[:pem] required'
  end
end

Instance Attribute Details

#identifierObject (readonly)

Returns the value of attribute identifier.



6
7
8
# File 'lib/lead_zeppelin/apns/application.rb', line 6

def identifier
  @identifier
end

Instance Method Details

#message(device_id, message, opts = {}) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/lead_zeppelin/apns/application.rb', line 55

def message(device_id, message, opts={})
  if @gateway_pool.total < @gateway_pool.max
    @gateway_pool.total += 1
    Logger.info "adding new gateway connection for #{@identifier}"
    gateway = new_gateway
  else
    gateway = @gateway_pool.pop
  end

  return false if gateway.nil?

  gateway.write Notification.new(device_id, message, opts)
  @gateway_pool.push gateway

  true
end

#new_gatewayObject



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
# File 'lib/lead_zeppelin/apns/application.rb', line 28

def new_gateway
  begin
    gateway = Gateway.new @ssl_context, 
                          (@opts[:gateway_opts] || {}).merge(notification_error_block: @opts[:notification_error_block],
                           certificate_error_block:  @opts[:certificate_error_block],
                           application_identifier:   @identifier)

  rescue OpenSSL::SSL::SSLError => e
    if e.message =~ /alert certificate unknown/
      Logger.warn "bad certificate for #{@identifier}, failed to connect"
    end

    if e.message =~ /alert certificate expired/
      Logger.warn "expired certificate for #{@identifier}, failed to connect"
    end

    if @opts[:certificate_error_block].nil?
      Logger.warn "removing application #{@identifier} from the client due to bad/invalid/expired certificate"
      APNS.client.remove_application @identifier
    else
      @opts[:certificate_error_block].call @identifier
    end
  end
  
  gateway
end