Matteo Scandolo | b585d38 | 2016-06-15 14:53:33 -0700 | [diff] [blame] | 1 | /* eslint-disable angular/ng_window_service*/ |
Matteo Scandolo | 1a5bf20 | 2016-05-31 14:26:26 -0700 | [diff] [blame] | 2 | (function() { |
| 3 | 'use strict'; |
| 4 | |
Matteo Scandolo | 1a5bf20 | 2016-05-31 14:26:26 -0700 | [diff] [blame] | 5 | angular |
| 6 | .module('xos.helpers') |
| 7 | .factory('Notification', function(){ |
| 8 | return window.Notification; |
| 9 | }) |
| 10 | /** |
| 11 | * @ngdoc service |
| 12 | * @name xos.helpers.xosNotification |
| 13 | * @description This factory define a set of helper function to trigger desktop notification |
| 14 | **/ |
| 15 | .service('xosNotification', function($q, $log, Notification) { |
| 16 | |
| 17 | this.checkPermission = () => { |
| 18 | const deferred = $q.defer(); |
| 19 | Notification.requestPermission() |
| 20 | .then(permission => { |
| 21 | if (permission === 'granted') { |
| 22 | deferred.resolve(permission); |
| 23 | } |
| 24 | else { |
| 25 | deferred.reject(permission); |
| 26 | } |
| 27 | }); |
| 28 | return deferred.promise; |
| 29 | }; |
| 30 | |
| 31 | this.sendNotification = (title, options) => { |
| 32 | const notification = new Notification(title, options); |
| 33 | notification.onerror = function(err){ |
| 34 | $log.error(err); |
| 35 | }; |
| 36 | }; |
| 37 | |
| 38 | /** |
| 39 | * @ngdoc method |
| 40 | * @name xos.helpers.xosNotification#notify |
| 41 | * @methodOf xos.helpers.xosNotification |
| 42 | * @description |
| 43 | * This method will check for user permission and if granted will send a browser notification. |
| 44 | * @param {string} title The notification title |
| 45 | * @param {object} options The notification options: `{icon: 'url', body: 'Notification body'}` |
| 46 | **/ |
| 47 | |
| 48 | this.notify = (title, options) => { |
| 49 | if (!('Notification' in window)) { |
| 50 | $log.info('This browser does not support desktop notification'); |
| 51 | } |
| 52 | else if (Notification.permission !== 'granted') { |
| 53 | this.checkPermission() |
| 54 | .then(() => this.sendNotification(title, options)); |
| 55 | } |
| 56 | else if (Notification.permission === 'granted') { |
| 57 | this.sendNotification(title, options); |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | }) |
| 62 | })(); |