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
14 function performSetup() {
17 webpush.setVapidDetails(
18 config.get('vapid:contact'),
19 config.get('vapid:publicKey'),
20 config.get('vapid:privateKey')
27 * Predicate function for bluebird
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,
39 auth: device.vapid && device.vapid.auth,
40 p256dh: device.vapid && device.vapid.p256dh
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
53 .catch(isVapidGoneError, function(err) {
54 throw new InvalidRegistrationError(err.message);
59 sendNotificationToDevice: Promise.method(sendNotificationToDevice)