Class: P8Pusher::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/p8_pusher/client.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



26
27
28
29
30
31
32
33
# File 'lib/p8_pusher/client.rb', line 26

def initialize
  @private_key = File.read(ENV['APN_PRIVATE_KEY'])
  @team_id = ENV['APN_TEAM_ID']
  @key_id = ENV['APN_KEY_ID']
  @timeout = Float(ENV['APN_TIMEOUT'] || 2.0)
rescue StandardError => e
  raise "#{e.message}: invalid keys, make sure you have the required keys in .env file"
end

Instance Attribute Details

#jwt_uriObject

Returns the value of attribute jwt_uri.



11
12
13
# File 'lib/p8_pusher/client.rb', line 11

def jwt_uri
  @jwt_uri
end

Class Method Details

.developmentObject



13
14
15
16
17
# File 'lib/p8_pusher/client.rb', line 13

def development
  client = new
  client.jwt_uri = APPLE_DEVELOPMENT_JWT_URI
  client
end

.productionObject



19
20
21
22
23
# File 'lib/p8_pusher/client.rb', line 19

def production
  client = new
  client.jwt_uri = APPLE_PRODUCTION_JWT_URI
  client
end

Instance Method Details

#jwt_http2_post(topic, payload, token) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/p8_pusher/client.rb', line 35

def jwt_http2_post(topic, payload, token)
  ec_key = OpenSSL::PKey::EC.new(@private_key)
  jwt_token = JWT.encode({iss: @team_id, iat: Time.now.to_i}, ec_key, 'ES256', {kid: @key_id})

  client = NetHttp2::Client.new(@jwt_uri)
  h = {}
  h['content-type'] = 'application/json'
  h['apns-expiration'] = '0'
  h['apns-priority'] = '10'
  h['apns-topic'] = topic
  h['authorization'] = "bearer #{jwt_token}"

  res = client.call(:post, '/3/device/'+token,
                    body: payload.to_json,
                    timeout: @timeout,
                    headers: h)
  client.close
  return nil if res.status.to_i == 200

  res.body
end

#push(*notifications) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/p8_pusher/client.rb', line 57

def push(*notifications)
  return if notifications.empty?

  notifications.flatten!

  notifications.each_with_index do |notification, index|
    next unless notification.kind_of?(Notification)
    next if notification.sent?
    next unless notification.valid?

    notification.id = index

    err = jwt_http2_post(notification.topic,
                         notification.payload,
                         notification.token)
    if err.nil?
      notification.mark_as_sent!
    else
      puts err
      notification.apns_error_code = err
      notification.mark_as_unsent!
    end
  end
end