From 70278fc157acf53a576286f44261e2acec972313 Mon Sep 17 00:00:00 2001 From: Rohan Rangray Date: Tue, 2 Jun 2015 10:54:24 -0700 Subject: [PATCH] Notifications are working now sorta. Still need to send the registration id to the app server. --- scripts/SettingsController.js | 299 ++++++++++++++++++++++++++++++++++++------ scripts/service-worker.js | 279 ++++++--------------------------------- 2 files changed, 296 insertions(+), 282 deletions(-) diff --git a/scripts/SettingsController.js b/scripts/SettingsController.js index 8394772..54963f5 100644 --- a/scripts/SettingsController.js +++ b/scripts/SettingsController.js @@ -7,52 +7,271 @@ angular.module('flashy.SettingsController', ['ui.router']). console.log('checking to see if chrome'); if (!chrome) { return; } console.log('chrome'); - $scope.registerCallback = function(registrationId) { - if (chrome.runtime.lastError) { - console.log('Registration failed'); - } + }); + +console.log("executing things outside of module"); +var PUSH_SERVER_URL = '/app/subscribe/'; + +function onPushSubscription(pushSubscription) { + console.log('pushSubscription = ', pushSubscription.endpoint); + // Here we would normally send the endpoint + // and subscription ID to our server. + // In this demo we just use send these values to + // our server via XHR which sends a push message. + + console.log('pushSubscription: ', pushSubscription); + + // Code to handle the XHR + var formData = new FormData(); + + var endpoint = pushSubscription.endpoint; + + if ('subscriptionId' in pushSubscription) { + // Make the endpoint always contain the subscriptionId + // so the server is always consistent + if (!endpoint.includes(pushSubscription.subscriptionId)) { + endpoint += '/' + pushSubscription.subscriptionId; + } + } - sendRegistrationId(registrationId, function(succeed) { - if (succeed) { - chrome.storage.local.set({registered: true}); - } + formData.append('registration_id', endpoint); + console.log("registration_id: ", endpoint); + + console.log("tryna push"); + + var req = new XMLHttpRequest(); + req.addEventListener("load", function(response) { + console.log("response: ", response); + }); + req.addEventListener("error", function(error) { + console.log("error: ", error); + }); + req.open("POST", PUSH_SERVER_URL); + req.send(formData); + console.log("pushed?"); + +} + +function subscribeDevice() { + // We need the service worker registration to access the push manager + navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { + serviceWorkerRegistration.pushManager.subscribe() + .then(onPushSubscription) + .catch(function(e) { + console.log("Error in subscribing"); + // Check for a permission prompt issue + if ('permissions' in navigator) { + navigator.permissions.query({name: 'push', userVisibleOnly: true}) + .then(function(permissionStatus) { + console.log('subscribe() Error: Push permission status = ', + permissionStatus); + if (permissionStatus.status === 'denied') { + // The user blocked the permission prompt + console.log('Ooops Notifications are Blocked', + 'Unfortunately you just permanently blocked notifications. ' + + 'Please unblock / allow them to switch on push ' + + 'notifications.'); + } else { + console.log('Ooops Push Couldn\'t Register', + '

When we tried to ' + + 'get the subscription ID for GCM, something went wrong,' + + ' not sure why.

' + + '

Have you defined "gcm_sender_id" and ' + + '"gcm_user_visible_only" in the manifest?

' + + '

Error message: ' + + e.message + + '

'); + } + }).catch(function(err) { + console.log('Ooops Push Couldn\'t Register', + '

When we tried to ' + + 'get the subscription ID for GCM, something went wrong, not ' + + 'sure why.

' + + '

Have you defined "gcm_sender_id" and ' + + '"gcm_user_visible_only" in the manifest?

' + + '

Error message: ' + + err.message + + '

'); }); - }; + } else { + // Use notification permission to do something + if (Notification.permission === 'denied') { + console.log('Ooops Notifications are Blocked', + 'Unfortunately you just permanently blocked notifications. ' + + 'Please unblock / allow them to switch on push notifications.'); + } else { + console.log('Ooops Push Couldn\'t Register', + '

When we tried to ' + + 'get the subscription ID for GCM, something went wrong, not ' + + 'sure why.

' + + '

Have you defined "gcm_sender_id" and ' + + '"gcm_user_visible_only" in the manifest?

' + + '

Error message: ' + + e.message + + '

'); + } + } + }); + }); +} - function sendRegistrationId(registrationId, callback) { - console.log('registration id: ' + registrationId); - $http.post('/api/subscribe/', JSON.stringify({ - 'registration_id': registrationId - })); - callback(true); +function unsubscribeDevice() { + navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { + serviceWorkerRegistration.pushManager.getSubscription().then( + function(pushSubscription) { + // Check we have everything we need to unsubscribe + if (!pushSubscription) { + return; } - console.log("gonna try to launch service worker now"); - if ('serviceWorker' in navigator) { - - console.log('gonna try to launch service worker now'); - navigator.serviceWorker.register('scripts/service-worker.js').then( - function(serviceWorkerRegistration) { - serviceWorkerRegistration.pushManager.subscribe().then( - function(pushSubscription) { - console.log('sub id: ', pushSubscription.subscriptionId); - console.log('endpoint: ', pushSubscription.endpoint); - // The push subscription details needed by the application - // server are now available, and can be sent to it using, - // for example, an XMLHttpRequest. - }, function(error) { - // During development it often helps to log errors to the - // console. In a production environment it might make sense to - // also report information about errors back to the - // application server. - console.log('sub error: ', error); - } - ); + // TODO: Remove the device details from the server + // i.e. the pushSubscription.subscriptionId and + // pushSubscription.endpoint + + pushSubscription.unsubscribe().then(function(successful) { + console.log('Unsubscribed from push: ', successful); + if (!successful) { + // The unsubscribe was unsuccessful, but we can + // remove the subscriptionId from our server + // and notifications will stop + // This just may be in a bad state when the user returns + console.error('We were unable to unregister from push'); + } + + }).catch(function(e) { + console.log('Unsubscribtion error: ', e); }); + }.bind(this)).catch(function(e) { + console.error('Error thrown while revoking push notifications. ' + + 'Most likely because push was never registered', e); + }); + }); +} + +function permissionStatusChange(permissionStatus) { + console.log('permissionStatusChange = ', permissionStatus); + // If the notification permission is denied, it's a permanent block + switch (permissionStatus.status) { + case 'denied': + console.log('Ooops Push has been Blocked', + 'Unfortunately the user permanently blocked push. Please unblock / ' + + 'allow them to switch on push notifications.'); + break; + case 'granted': + // Set the state of the push switch + console.log("case granted"); + break; + case 'prompt': + console.log("case prompt"); + break; + } +} + +function setUpPushPermission() { + navigator.permissions.query({name: 'push', userVisibleOnly: true}) + .then(function(permissionStatus) { + // Set the initial state + permissionStatusChange(permissionStatus); + + // Handle Permission State Changes + permissionStatus.onchange = function() { + permissionStatusChange(this); + }; + + // Check if push is supported and what the current state is + navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { + // Let's see if we have a subscription already + serviceWorkerRegistration.pushManager.getSubscription() + .then(function(subscription) { + if (!subscription) { + // NOOP + return; + } + + // Update the current state with the + // subscriptionid and endpoint + onPushSubscription(subscription); + }) + .catch(function(e) { + console.log('An error occured while calling getSubscription()', e); + }); + }); + }).catch(function(err) { + console.log('Ooops Unable to check the permission', + 'Unfortunately the permission for push notifications couldn\'t be ' + + 'checked. Are you on Chrome 43+?'); + }); +} + +function setUpNotificationPermission() { + // If the notification permission is denied, it's a permanent block + if (Notification.permission === 'denied') { + console.log('Ooops Notifications are Blocked', + 'Unfortunately notifications are permanently blocked. Please unblock / ' + + 'allow them to switch on push notifications.'); + return; + } else if (Notification.permission === 'default') { + console.log("notification permissions === default"); + return; + } + + // Check if push is supported and what the current state is + navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { + // Let's see if we have a subscription already + serviceWorkerRegistration.pushManager.getSubscription() + .then(function(subscription) { + if (!subscription) { + // NOOP + console.log("not subscription"); + return; + } - } else { - console.log('Service workers aren\'t supported in this browser.'); - } + // Update the current state with the + // subscriptionid and endpoint + console.log("onpushsubscription should be entered"); + onPushSubscription(subscription); + }) + .catch(function(e) { + console.log('An error occured while calling getSubscription()', e); + }); + }); +} +// Once the service worker is registered set the initial state +function initialiseState() { + // Is the Permissions API supported + if ('permissions' in navigator) { + console.log("setting push permissions"); + setUpPushPermission(); + return; + } else { + console.log("setting notification permissions"); + setUpNotificationPermission(); + } +} +window.addEventListener('load', function() { + // When the toggle switch changes, enabled / disable push + // messaging + var enablePushSwitch = document.querySelector('.js-checkbox'); + enablePushSwitch.addEventListener('change', function(e) { + if (e.target.checked) { + subscribeDevice(); + } else { + unsubscribeDevice(); + } + }); - }); \ No newline at end of file + // Check that service workers are supported + if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('scripts/service-worker.js') + .then(initialiseState); + } else { + // Service Workers aren't supported so you should hide the push UI + // If it's currently visible. + console.log('Ooops Service Workers aren\'t Supported', + 'Service Workers aren\'t supported in this browser. ' + + 'For this demo be sure to use ' + + 'Chrome Canary' + + ' or version 42.'); + } +}); diff --git a/scripts/service-worker.js b/scripts/service-worker.js index d174753..42afc50 100644 --- a/scripts/service-worker.js +++ b/scripts/service-worker.js @@ -1,251 +1,46 @@ 'use strict'; -var PUSH_SERVER_URL = 'https://flashy.cards/app/subscribe/'; - -function onPushSubscription(pushSubscription) { - console.log('pushSubscription = ', pushSubscription.endpoint); - // Here we would normally send the endpoint - // and subscription ID to our server. - // In this demo we just use send these values to - // our server via XHR which sends a push message. - - console.log('pushSubscription: ', pushSubscription); - - // Code to handle the XHR - var formData = new FormData(); - - var endpoint = pushSubscription.endpoint; - - fetch(PUSH_SERVER_URL, { - method: 'post', - body: formData - }).then(function(response) { - console.log('Response = ', response); - }).catch(function(err) { - console.log('Fetch Error :-S', err); - }); - -} - -function subscribeDevice() { - // We need the service worker registration to access the push manager - navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { - serviceWorkerRegistration.pushManager.subscribe() - .then(onPushSubscription) - .catch(function(e) { - // Check for a permission prompt issue - if ('permissions' in navigator) { - navigator.permissions.query({name: 'push', userVisibleOnly: true}) - .then(function(permissionStatus) { - console.log('subscribe() Error: Push permission status = ', - permissionStatus); - if (permissionStatus.status === 'denied') { - // The user blocked the permission prompt - console.log('Ooops Notifications are Blocked', - 'Unfortunately you just permanently blocked notifications. ' + - 'Please unblock / allow them to switch on push ' + - 'notifications.'); - } else { - console.log('Ooops Push Couldn\'t Register', - '

When we tried to ' + - 'get the subscription ID for GCM, something went wrong,' + - ' not sure why.

' + - '

Have you defined "gcm_sender_id" and ' + - '"gcm_user_visible_only" in the manifest?

' + - '

Error message: ' + - e.message + - '

'); - } - }).catch(function(err) { - console.log('Ooops Push Couldn\'t Register', - '

When we tried to ' + - 'get the subscription ID for GCM, something went wrong, not ' + - 'sure why.

' + - '

Have you defined "gcm_sender_id" and ' + - '"gcm_user_visible_only" in the manifest?

' + - '

Error message: ' + - err.message + - '

'); - }); - } else { - // Use notification permission to do something - if (Notification.permission === 'denied') { - console.log('Ooops Notifications are Blocked', - 'Unfortunately you just permanently blocked notifications. ' + - 'Please unblock / allow them to switch on push notifications.'); - } else { - console.log('Ooops Push Couldn\'t Register', - '

When we tried to ' + - 'get the subscription ID for GCM, something went wrong, not ' + - 'sure why.

' + - '

Have you defined "gcm_sender_id" and ' + - '"gcm_user_visible_only" in the manifest?

' + - '

Error message: ' + - e.message + - '

'); - } - } - }); - }); -} - -function unsubscribeDevice() { - navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { - serviceWorkerRegistration.pushManager.getSubscription().then( - function(pushSubscription) { - // Check we have everything we need to unsubscribe - if (!pushSubscription) { - return; - } - - // TODO: Remove the device details from the server - // i.e. the pushSubscription.subscriptionId and - // pushSubscription.endpoint - - pushSubscription.unsubscribe().then(function(successful) { - console.log('Unsubscribed from push: ', successful); - if (!successful) { - // The unsubscribe was unsuccessful, but we can - // remove the subscriptionId from our server - // and notifications will stop - // This just may be in a bad state when the user returns - console.error('We were unable to unregister from push'); - } - - }).catch(function(e) { - console.log('Unsubscribtion error: ', e); - }); - }.bind(this)).catch(function(e) { - console.error('Error thrown while revoking push notifications. ' + - 'Most likely because push was never registered', e); - }); - }); -} - -function permissionStatusChange(permissionStatus) { - console.log('permissionStatusChange = ', permissionStatus); - // If the notification permission is denied, it's a permanent block - switch (permissionStatus.status) { - case 'denied': - console.log('Ooops Push has been Blocked', - 'Unfortunately the user permanently blocked push. Please unblock / ' + - 'allow them to switch on push notifications.'); - break; - case 'granted': - // Set the state of the push switch - console.log("case granted"); - break; - case 'prompt': - console.log("case prompt"); - break; - } -} - -function setUpPushPermission() { - navigator.permissions.query({name: 'push', userVisibleOnly: true}) - .then(function(permissionStatus) { - // Set the initial state - permissionStatusChange(permissionStatus); - - // Handle Permission State Changes - permissionStatus.onchange = function() { - permissionStatusChange(this); - }; - - // Check if push is supported and what the current state is - navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { - // Let's see if we have a subscription already - serviceWorkerRegistration.pushManager.getSubscription() - .then(function(subscription) { - if (!subscription) { - // NOOP - return; - } - - // Update the current state with the - // subscriptionid and endpoint - onPushSubscription(subscription); - }) - .catch(function(e) { - console.log('An error occured while calling getSubscription()', e); - }); - }); - }).catch(function(err) { - console.log('Ooops Unable to check the permission', - 'Unfortunately the permission for push notifications couldn\'t be ' + - 'checked. Are you on Chrome 43+?'); - }); -} - -function setUpNotificationPermission() { - // If the notification permission is denied, it's a permanent block - if (Notification.permission === 'denied') { - console.log('Ooops Notifications are Blocked', - 'Unfortunately notifications are permanently blocked. Please unblock / ' + - 'allow them to switch on push notifications.'); - return; - } else if (Notification.permission === 'default') { - console.log("notification permissions === default"); - return; - } - - // Check if push is supported and what the current state is - navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { - // Let's see if we have a subscription already - serviceWorkerRegistration.pushManager.getSubscription() - .then(function(subscription) { - if (!subscription) { - // NOOP - console.log("not subscription"); - return; - } - - // Update the current state with the - // subscriptionid and endpoint - onPushSubscription(subscription); - }) - .catch(function(e) { - console.log('An error occured while calling getSubscription()', e); - }); - }); -} - -// Once the service worker is registered set the initial state -function initialiseState() { - // Is the Permissions API supported - if ('permissions' in navigator) { - setUpPushPermission(); +function showNotification(title, body, icon, data) { + var notificationOptions = { + body: body, + icon: icon ? icon : 'images/touch/chrome-touch-icon-192x192.png', + tag: 'simple-push-demo-notification', + data: data + }; + if (self.registration.showNotification) { + self.registration.showNotification(title, notificationOptions); return; } else { - setUpNotificationPermission(); + new Notification(title, notificationOptions); } } -self.addEventListener('UIReady', function() { - // When the toggle switch changes, enabled / disable push - // messaging - var enablePushSwitch = document.querySelector('.js-checkbox'); - enablePushSwitch.addEventListener('change', function(e) { - if (e.target.checked) { - subscribeDevice(); - } else { - unsubscribeDevice(); - } - }); +self.addEventListener('push', function(event) { + console.log('Received a push message', event); + + // Since this is no payload data with the first version + // of Push notifications, here we'll grab some data from + // an API and use it to populate a notification + var title = 'You have cards waiting to be reviewed!'; + var message = 'check yo cards m8'; + var icon = 'flashy.ico'; + var notificationTag = 'simple-push-demo-notification'; + + // Add this to the data of the notification + var urlToOpen = '/api/subscribe/'; + + var notificationFilter = { + tag: 'simple-push-demo-notification' + }; + var notificationData = { + url: urlToOpen + }; + return showNotification(title, message, icon, notificationData); +}); - // Check that service workers are supported - if ('serviceWorker' in navigator) { - navigator.serviceWorker.register('/service-worker.js', { - scope: './' - }) - .then(initialiseState); - } else { - // Service Workers aren't supported so you should hide the push UI - // If it's currently visible. - console.log('Ooops Service Workers aren\'t Supported', - 'Service Workers aren\'t supported in this browser. ' + - 'For this demo be sure to use ' + - 'Chrome Canary' + - ' or version 42.'); - } +self.addEventListener('notificationclick', function(event) { + console.log('On notification click: ', event); + + var url = event.notification.data.url; + event.waitUntil(clients.openWindow(url)); }); -- 1.9.1