Gitter migration: Point people to app.gitter.im (rollout pt. 1)
[gitter.git] / modules / push-gateways / lib / vapid / vapid-notification-gateway.js
blob014823d1e48552b246edea57763bf09ff4f9f693
1 'use strict';
3 var env = require('gitter-web-env');
4 var config = env.config;
5 var webpush = require('web-push');
6 var InvalidRegistrationError = require('../invalid-registration-error');
7 var Promise = require('bluebird');
8 var vapidNotificationGeneration = require('./vapid-notification-generator');
10 var DEFAULT_TTL_SECONDS = 86400 * 7; // 7 days
12 var setup = false;
14 function performSetup() {
15   if (setup) return;
17   webpush.setVapidDetails(
18     config.get('vapid:contact'),
19     config.get('vapid:publicKey'),
20     config.get('vapid:privateKey')
21   );
23   setup = true;
26 /**
27  * Predicate function for bluebird
28  */
29 function isVapidGoneError(err) {
30   return err && err.statusCode && String(err.statusCode) === '410';
33 function sendNotificationToDevice(notificationType, notificationDetails, device) {
34   if (!setup) performSetup();
36   var pushSubscription = {
37     endpoint: device.deviceId,
38     keys: {
39       auth: device.vapid && device.vapid.auth,
40       p256dh: device.vapid && device.vapid.p256dh
41     }
42   };
44   var payloadData = vapidNotificationGeneration(notificationType, notificationDetails, device);
45   if (!payloadData) return false;
47   return Promise.resolve(
48     webpush.sendNotification(pushSubscription, JSON.stringify(payloadData), {
49       TTL: DEFAULT_TTL_SECONDS
50     })
51   )
52     .return(true)
53     .catch(isVapidGoneError, function(err) {
54       throw new InvalidRegistrationError(err.message);
55     });
58 module.exports = {
59   sendNotificationToDevice: Promise.method(sendNotificationToDevice)