summaryrefslogtreecommitdiff
path: root/examples/lib/okpush/apn.js
blob: 5e13e157c1ea011ba99a59a9db368f70ca4c3483 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
var apn = require('apn')
var db = require('./db')
var apnProvider, apnFeedback

function init (config) {
  config.apn.connection.key = config.apn.key
  config.apn.connection.cert = config.apn.cert
  apnProvider = new apn.Provider(config.apn.connection)
}

function push (tokens, note) {
  tokens.forEach(function(token){
    connection.send(note, token).then( function (response) {
      response.sent.forEach( function (token) {
        // notificationSent(user, token)
      })
      response.failed.forEach( function (failure) {
        if (failure.error) {
          // A transport-level error occurred (e.g. network problem)
          // notificationError(user, token, failure.error);
        } else {
          // `failure.status` is the HTTP status code
          // `failure.response` is the JSON payload 
          // notificationFailed(token, failure.status, failure.response);
          db.removeDevice(token)
        }
      })
    })
  })
}

function buildPayload (options, bundleId) {
  var note = new apn.Notification()
  note.topic = bundleId
  if (options.expiry)
    note.expiry = Math.floor(Date.now() / 1000) + options.expiry
  if (options.alert)
    note.alert = options.alert
  if (options.badge)
    note.badge = options.badge
  if (options.payload)
    note.payload = options.payload
  if (options.sound)
    note.sound = options.sound
  return note
}

module.exports = {
  init: init,
  push: push,
  buildPayload: buildPayload
}