Class: APND::Daemon::AppleConnection

Inherits:
Object
  • Object
show all
Defined in:
lib/apnd/daemon/apple_connection.rb

Overview

Daemon::AppleConnection handles the persistent connection between APND and Apple

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ AppleConnection

Setup a new connection



15
16
17
18
19
20
21
22
# File 'lib/apnd/daemon/apple_connection.rb', line 15

def initialize(params = {})
  @options = {
    :cert      => APND.settings.apple.cert,
    :cert_pass => APND.settings.apple.cert_pass,
    :host      => APND.settings.apple.host,
    :port      => APND.settings.apple.port.to_i
  }.merge(params)
end

Instance Attribute Details

#sockObject (readonly)

Returns the value of attribute sock.



10
11
12
# File 'lib/apnd/daemon/apple_connection.rb', line 10

def sock
  @sock
end

#sslObject (readonly)

Returns the value of attribute ssl.



10
11
12
# File 'lib/apnd/daemon/apple_connection.rb', line 10

def ssl
  @ssl
end

Instance Method Details

#connect!Object

Connect to Apple over SSL



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/apnd/daemon/apple_connection.rb', line 34

def connect!
  cert         = File.read(@options[:cert])
  context      = OpenSSL::SSL::SSLContext.new
  context.key  = OpenSSL::PKey::RSA.new(cert, @options[:cert_pass])
  context.cert = OpenSSL::X509::Certificate.new(cert)

  @sock = TCPSocket.new(@options[:host], @options[:port])
  @ssl  = OpenSSL::SSL::SSLSocket.new(@sock, context)
  @ssl.sync = true
  @ssl.connect
end

#connected?Boolean

Returns true if the connection to Apple is open

Returns:

  • (Boolean)


27
28
29
# File 'lib/apnd/daemon/apple_connection.rb', line 27

def connected?
  ! @ssl.nil?
end

#disconnect!Object

Close connection



49
50
51
52
53
54
# File 'lib/apnd/daemon/apple_connection.rb', line 49

def disconnect!
  @ssl.close
  @sock.close
  @ssl = nil
  @sock = nil
end

#open {|@ssl| ... } ⇒ Object

Establishes a connection if needed and yields it

Ex: open { |conn| conn.write(‘write to socket’) }

Yields:



69
70
71
72
73
74
75
# File 'lib/apnd/daemon/apple_connection.rb', line 69

def open(&block)
  unless connected?
    connect!
  end

  yield @ssl
end

#reconnect!Object

Disconnect/connect to Apple



59
60
61
62
# File 'lib/apnd/daemon/apple_connection.rb', line 59

def reconnect!
  disconnect!
  connect!
end

#write(raw) ⇒ Object

Write to the connection socket



80
81
82
# File 'lib/apnd/daemon/apple_connection.rb', line 80

def write(raw)
  open { |conn| conn.write(raw) }
end