Class: ApnMachine::Notification

Inherits:
Object
  • Object
show all
Defined in:
lib/apnmachine/notification.rb

Defined Under Namespace

Classes: NoDeviceToken, PayloadTooLarge

Constant Summary collapse

PAYLOAD_MAX_BYTES =
256

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#alertObject

Returns the value of attribute alert.



4
5
6
# File 'lib/apnmachine/notification.rb', line 4

def alert
  @alert
end

#badgeObject

Returns the value of attribute badge.



4
5
6
# File 'lib/apnmachine/notification.rb', line 4

def badge
  @badge
end

#customObject

Returns the value of attribute custom.



4
5
6
# File 'lib/apnmachine/notification.rb', line 4

def custom
  @custom
end

#device_tokenObject

Returns the value of attribute device_token.



4
5
6
# File 'lib/apnmachine/notification.rb', line 4

def device_token
  @device_token
end

#soundObject

Returns the value of attribute sound.



4
5
6
# File 'lib/apnmachine/notification.rb', line 4

def sound
  @sound
end

Class Method Details

.to_bytes(encoded_payload) ⇒ Object

Raises:



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/apnmachine/notification.rb', line 31

def self.to_bytes(encoded_payload)
  notif_hash = ActiveSupport::JSON.decode(encoded_payload)
  
  device_token = notif_hash.delete('device_token')
  bin_token = [device_token].pack('H*')
  raise NoDeviceToken.new("No device token") unless device_token
  
  j = ActiveSupport::JSON.encode(notif_hash)
  raise PayloadTooLarge.new("The payload is larger than allowed: #{j.length}") if j.size > PAYLOAD_MAX_BYTES
  
  Config.logger.debug "TOKEN:#{device_token} | ALERT:#{notif_hash.inspect}"
  
  [0, 0, bin_token.size, bin_token, 0, j.size, j].pack("ccca*cca*")
end

Instance Method Details

#encode_payloadObject

Raises:



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/apnmachine/notification.rb', line 10

def encode_payload
  p = {:aps => Hash.new}
  [:badge, :alert, :sound].each do |k|
    p[:aps][k] = send(k) if send(k)
  end
  p.merge!(custom) if send(:custom)
  
  j = ActiveSupport::JSON.encode(p)
  raise PayloadTooLarge.new("The payload is larger than allowed: #{j.length}") if j.size > PAYLOAD_MAX_BYTES
  
  p[:device_token] = device_token
  raise NoDeviceToken.new("No device token") unless device_token
  
  ActiveSupport::JSON.encode(p)
end

#pushObject



26
27
28
29
# File 'lib/apnmachine/notification.rb', line 26

def push
  raise 'No Redis client' if Config.redis.nil?
  socket = Config.redis.rpush "apnmachine.queue", encode_payload
end