3 var env = require('gitter-web-env');
4 var nconf = env.config;
5 var gcm = require('node-gcm');
6 var Promise = require('bluebird');
7 var InvalidRegistrationError = require('../invalid-registration-error');
8 var androidNotificationGenerator = require('./android-notification-generator');
12 var sender = new gcm.Sender(nconf.get('gcm:apiKey'));
15 * Returns true if a notification was sent
17 function sendNotificationToDevice(notificationType, notificationDetails, device) {
18 var message = androidNotificationGenerator(notificationType, notificationDetails, device);
19 if (!message) return false;
21 return Promise.fromCallback(function(callback) {
22 sender.send(message, [device.androidToken], MAX_RETRIES, callback);
23 }).then(function(body) {
24 if (body.canonical_ids) {
25 // this registration id/token is an old duplicate which has been superceded by a canonical id,
26 // and we've probably just sent two identical messages to the same phone.
27 throw new InvalidRegistrationError('Duplicate identifier');
30 if (body.failure && body.results[0] && body.results[0].error === 'NotRegistered') {
31 // app has been uninstalled / token revoked
32 throw new InvalidRegistrationError('Not registered');
40 sendNotificationToDevice: Promise.method(sendNotificationToDevice)