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