Wallet/src/js/services/pushNotificationsService.js

87 lines
2.7 KiB
JavaScript
Raw Normal View History

2016-01-04 14:11:24 -03:00
'use strict';
angular.module('copayApp.services')
.factory('pushNotificationsService', function($log, platformInfo, storageService, configService, lodash) {
2016-01-04 14:11:24 -03:00
var root = {};
var isCordova = platformInfo.isCordova;
var isWP = platformInfo.isWP;
var isIOS = platformInfo.isIOS;
var isAndroid = platformInfo.isAndroid;
var usePushNotifications = isCordova && !isWP;
2015-12-23 12:29:46 -03:00
root.init = function(walletsClients) {
var defaults = configService.getDefaults();
2016-10-10 13:45:43 -03:00
try {
var push = PushNotification.init(defaults.pushNotifications.config);
} catch(e) {
$log.error(e);
return;
};
push.on('registration', function(data) {
$log.debug('Starting push notification registration');
root.token = data.registrationId;
var config = configService.getSync();
if (config.pushNotifications.enabled) root.enableNotifications(walletsClients);
});
return push;
}
root.enableNotifications = function(walletsClients) {
2016-01-20 16:06:15 -03:00
if (!usePushNotifications) return;
2016-01-26 15:42:07 -03:00
var config = configService.getSync();
if (!config.pushNotifications.enabled) return;
if (!root.token) {
$log.warn('No token available for this device. Cannot set push notifications. Needs registration.');
return;
}
2016-02-22 19:32:24 -03:00
lodash.forEach(walletsClients, function(walletClient) {
var opts = {};
opts.type = isIOS ? "ios" : isAndroid ? "android" : null;
opts.token = root.token;
root.subscribe(opts, walletClient, function(err, response) {
if (err) $log.warn('Subscription error: ' + err.message + ': ' + JSON.stringify(opts));
else $log.debug('Subscribed to push notifications service: ' + JSON.stringify(response));
2016-01-04 14:11:24 -03:00
});
});
}
root.disableNotifications = function(walletsClients) {
2016-01-20 16:06:15 -03:00
if (!usePushNotifications) return;
lodash.forEach(walletsClients, function(walletClient) {
root.unsubscribe(walletClient, function(err) {
2016-01-25 11:50:08 -03:00
if (err) $log.warn('Unsubscription error: ' + err.message);
2016-01-20 16:25:06 -03:00
else $log.debug('Unsubscribed from push notifications service');
});
2016-01-04 14:11:24 -03:00
});
}
root.subscribe = function(opts, walletClient, cb) {
if (!usePushNotifications) return cb();
2016-01-20 16:06:15 -03:00
2016-01-26 15:42:07 -03:00
var config = configService.getSync();
if (!config.pushNotifications.enabled) return;
walletClient.pushNotificationsSubscribe(opts, function(err, resp) {
if (err) return cb(err);
return cb(null, resp);
2016-01-04 16:35:34 -03:00
});
}
root.unsubscribe = function(walletClient, cb) {
if (!usePushNotifications) return cb();
2016-01-20 16:06:15 -03:00
2016-01-20 16:25:06 -03:00
walletClient.pushNotificationsUnsubscribe(function(err) {
if (err) return cb(err);
2016-01-20 16:25:06 -03:00
return cb(null);
2016-01-04 14:11:24 -03:00
});
}
return root;
});