summaryrefslogtreecommitdiff
path: root/examples/lib/okpush/apn.js
blob: 050a4663f06e688e7c4f36b1e17cf4dcb1950721 (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
54
55
56
57
58
var config = require('./Config')
var apn = require('apn')
var db = require('./db')
var apnConnection, apnFeedback

function init (config) {
  apnConnection = new apn.Connection(config.apn.connection)
  apnConnection.on('transmissionError', onTransmissionError)

  apnFeedback = new apn.Feedback(config.apn.feedback)
  apnFeedback.on('feedback', onFeedback)

  return apnConnection
}

function onTransmissionError (errorCode, notification, recipient) {
  console.error('Error while pushing to APN: ' + errorCode)

  if (errorCode === 8 && recipient.token) {
    var token = recipient.token.toString('hex').toUpperCase()

    console.log('Invalid token: removing device ' + token)
    db.remove(token)
  }
}

function onFeedback (deviceInfos) {
  console.log('Feedback service, number of devices to remove: ' + deviceInfos.length)

  if (deviceInfos.length > 0) {
    db.removeDevices(deviceInfos.map(function (deviceInfo) {
      return deviceInfo.device.token.toString('hex')
    })
  }
}

function push (tokens, payload) {
  apnConnection.pushNotification(payload, tokens)
}

function buildPayload (options) {
  var notif = new apn.Notification()

  notif.expiry = options.expiry || 0
  notif.alert = options.alert
  notif.badge = options.badge
  notif.payload = options.payload
  notif.sound = options.sound

  return notif
}

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