FIX: Don't ask for notification permission until first one

This commit is contained in:
riking 2015-05-02 12:03:08 -07:00
parent 83b7620cb2
commit 6ea2051c4e
1 changed files with 68 additions and 47 deletions

View File

@ -1,6 +1,7 @@
let primaryTab = false;
let liveEnabled = false;
let havePermission = null;
let mbClientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
let lastAction = -1;
@ -15,25 +16,37 @@ let notificationTagName; // "discourse-notification-popup-" + Discourse.SiteSett
function init(messageBus) {
liveEnabled = false;
mbClientId = messageBus.clientId;
requestPermission().then(function() {
if (!Discourse.User.current()) {
return;
}
try {
localStorage.getItem(focusTrackerKey);
} catch (e) {
Em.Logger.info('Discourse desktop notifications are disabled - localStorage denied.');
return;
}
if (!Notification) {
Em.Logger.info('Discourse desktop notifications are disabled - not supported by browser');
return;
}
if (Notification.permission === "granted") {
havePermission = true;
} else if (Notification.permission === "denied") {
havePermission = false;
return;
}
liveEnabled = true;
Em.Logger.info('Discourse desktop notifications are enabled.');
try {
// Permission is granted, continue with setup
// Preliminary checks passed, continue with setup
setupNotifications();
} catch (e) {
Em.Logger.error(e);
}
}).catch(function() {
liveEnabled = false;
//Em.Logger.debug('Discourse desktop notifications are disabled - permission denied.');
});
}
// This function is only called if permission was granted
@ -139,6 +152,7 @@ function onNotification(currentUser) {
const notificationBody = bodyParts.join("\n");
const notificationIcon = Discourse.SiteSettings.logo_small_url || Discourse.SiteSettings.logo_url;
requestPermission().then(function() {
// This shows the notification!
const notification = new Notification(notificationTitle, {
body: notificationBody,
@ -150,7 +164,7 @@ function onNotification(currentUser) {
function clickEventHandler() {
Discourse.URL.routeTo(_notificationUrl(firstUnseen));
// Cannot delay this until the page renders :(
// Cannot delay this until the page renders
// due to trigger-based permissions
window.focus();
}
@ -161,6 +175,7 @@ function onNotification(currentUser) {
notification.removeEventListener('click', clickEventHandler);
}, 10 * 1000);
});
});
}
}
@ -191,6 +206,11 @@ function updateSeenNotificationDatesFrom(notifications) {
// Utility function
// Wraps Notification.requestPermission in a Promise
function requestPermission() {
if (havePermission === true) {
return Ember.RSVP.resolve();
} else if (havePermission === false) {
return Ember.RSVP.reject();
} else {
return new Ember.RSVP.Promise(function(resolve, reject) {
Notification.requestPermission(function(status) {
if (status === "granted") {
@ -200,6 +220,7 @@ function requestPermission() {
}
});
});
}
}
function i18nKey(notification) {