module APND
  #
  # Daemon::Protocol handles incoming APNs
  #
  class Daemon::Protocol < ::EventMachine::Connection

    #
    # Queue should be the EventMachine queue, see APND::Daemon
    #
    attr_accessor :queue

    #
    # Called when a client connection is opened
    #
    def post_init
      @address = Socket.unpack_sockaddr_in(self.get_peername)
      ohai "#{@address.last}:#{@address.first} opened connection"
    end

    #
    # Called when a client connection is closed
    #
    def unbind
      ohai "#{@address.last}:#{@address.first} closed connection"
    end

    #
    # Add incoming notification to the queue if it is valid
    #
    def receive_data(data)
      (@buffer ||= "") << data
      if notification = APND::Notification.valid?(@buffer)
        ohai "#{@address.last}:#{@address.first} added new Notification to queue"
        queue.push(notification)
      else
        ohai "#{@address.last}:#{@address.first} submitted invalid Notification"
      end
    end
  end
end

module APND
  #
  # Daemon::Protocol handles incoming APNs
  #
  class Daemon::Protocol < ::EventMachine::Connection

    #
    # Queue should be the EventMachine queue, see APND::Daemon
    #
    attr_accessor :queue

    #
    # Called when a client connection is opened
    #
    def post_init
      @address = Socket.unpack_sockaddr_in(self.get_peername)
      ohai "#{@address.last}:#{@address.first} opened connection"
    end

    #
    # Called when a client connection is closed
    #
    def unbind
      ohai "#{@address.last}:#{@address.first} closed connection"
    end

    #
    # Add incoming notification to the queue if it is valid
    #
    def receive_data(data)
      (@buffer ||= "") << data
      @buffer.each_line do |line|
        if notification = APND::Notification.valid?(line)
          ohai "#{@address.last}:#{@address.first} added new Notification to queue"
          queue.push(notification)
        else
          ohai "#{@address.last}:#{@address.first} submitted invalid Notification"
        end
      end
    end
  end
end

Support multiple APNs per packet (see details below)
Support multiple APNs per packet (see details below)

Versions of APND prior to 0.1.4 had a bug in APND::Daemon::Protocol which
allowed only one APN to be sent per packet.

Ex:

    APND::Notification.open_upstream_socket do |sock|
      sock.write(notification1.to_bytes)
      sock.write(notification2.to_bytes)
    end

This code would cause both notifications to be sent to the APND::Daemon in
a single packet (separated by new lines \n). The first notification would be
parsed from the packet, and then the others were discarded.

This commit fixes the issue by searching each line in a received packet for
APNs to queue.
