Commit 70278fc157acf53a576286f44261e2acec972313

Authored by Rohan Rangray
1 parent 6ad6fec426

Notifications are working now sorta. Still need to send the registration id to the app server.

Showing 2 changed files with 296 additions and 282 deletions Inline Diff

scripts/SettingsController.js View file @ 70278fc
angular.module('flashy.SettingsController', ['ui.router']). 1 1 angular.module('flashy.SettingsController', ['ui.router']).
2 2
controller('SettingsController', function($scope, $http) { 3 3 controller('SettingsController', function($scope, $http) {
$scope.changePassword = function(oldPassword, newPassword, confirmedNewPassword) { 4 4 $scope.changePassword = function(oldPassword, newPassword, confirmedNewPassword) {
5 5
}; 6 6 };
console.log('checking to see if chrome'); 7 7 console.log('checking to see if chrome');
if (!chrome) { return; } 8 8 if (!chrome) { return; }
console.log('chrome'); 9 9 console.log('chrome');
$scope.registerCallback = function(registrationId) { 10 10 });
if (chrome.runtime.lastError) { 11
console.log('Registration failed'); 12
} 13
14 11
sendRegistrationId(registrationId, function(succeed) { 15 12 console.log("executing things outside of module");
if (succeed) { 16 13 var PUSH_SERVER_URL = '/app/subscribe/';
chrome.storage.local.set({registered: true}); 17 14
} 18 15 function onPushSubscription(pushSubscription) {
16 console.log('pushSubscription = ', pushSubscription.endpoint);
17 // Here we would normally send the endpoint
18 // and subscription ID to our server.
19 // In this demo we just use send these values to
20 // our server via XHR which sends a push message.
21
22 console.log('pushSubscription: ', pushSubscription);
23
24 // Code to handle the XHR
25 var formData = new FormData();
26
27 var endpoint = pushSubscription.endpoint;
28
29 if ('subscriptionId' in pushSubscription) {
30 // Make the endpoint always contain the subscriptionId
31 // so the server is always consistent
32 if (!endpoint.includes(pushSubscription.subscriptionId)) {
33 endpoint += '/' + pushSubscription.subscriptionId;
34 }
35 }
36
37 formData.append('registration_id', endpoint);
38 console.log("registration_id: ", endpoint);
39
40 console.log("tryna push");
41
42 var req = new XMLHttpRequest();
43 req.addEventListener("load", function(response) {
44 console.log("response: ", response);
45 });
46 req.addEventListener("error", function(error) {
47 console.log("error: ", error);
48 });
49 req.open("POST", PUSH_SERVER_URL);
50 req.send(formData);
51 console.log("pushed?");
52
53 }
54
55 function subscribeDevice() {
56 // We need the service worker registration to access the push manager
57 navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
58 serviceWorkerRegistration.pushManager.subscribe()
59 .then(onPushSubscription)
60 .catch(function(e) {
61 console.log("Error in subscribing");
62 // Check for a permission prompt issue
63 if ('permissions' in navigator) {
64 navigator.permissions.query({name: 'push', userVisibleOnly: true})
65 .then(function(permissionStatus) {
66 console.log('subscribe() Error: Push permission status = ',
67 permissionStatus);
68 if (permissionStatus.status === 'denied') {
69 // The user blocked the permission prompt
70 console.log('Ooops Notifications are Blocked',
71 'Unfortunately you just permanently blocked notifications. ' +
72 'Please unblock / allow them to switch on push ' +
73 'notifications.');
74 } else {
75 console.log('Ooops Push Couldn\'t Register',
76 '<p>When we tried to ' +
77 'get the subscription ID for GCM, something went wrong,' +
78 ' not sure why.</p>' +
79 '<p>Have you defined "gcm_sender_id" and ' +
80 '"gcm_user_visible_only" in the manifest?</p>' +
81 '<p>Error message: ' +
82 e.message +
83 '</p>');
84 }
85 }).catch(function(err) {
86 console.log('Ooops Push Couldn\'t Register',
87 '<p>When we tried to ' +
88 'get the subscription ID for GCM, something went wrong, not ' +
89 'sure why.</p>' +
90 '<p>Have you defined "gcm_sender_id" and ' +
91 '"gcm_user_visible_only" in the manifest?</p>' +
92 '<p>Error message: ' +
93 err.message +
94 '</p>');
}); 19 95 });
}; 20 96 } else {
97 // Use notification permission to do something
98 if (Notification.permission === 'denied') {
99 console.log('Ooops Notifications are Blocked',
100 'Unfortunately you just permanently blocked notifications. ' +
101 'Please unblock / allow them to switch on push notifications.');
102 } else {
103 console.log('Ooops Push Couldn\'t Register',
104 '<p>When we tried to ' +
105 'get the subscription ID for GCM, something went wrong, not ' +
106 'sure why.</p>' +
107 '<p>Have you defined "gcm_sender_id" and ' +
108 '"gcm_user_visible_only" in the manifest?</p>' +
109 '<p>Error message: ' +
110 e.message +
111 '</p>');
112 }
113 }
114 });
115 });
116 }
21 117
function sendRegistrationId(registrationId, callback) { 22 118 function unsubscribeDevice() {
console.log('registration id: ' + registrationId); 23 119 navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
$http.post('/api/subscribe/', JSON.stringify({ 24 120 serviceWorkerRegistration.pushManager.getSubscription().then(
'registration_id': registrationId 25 121 function(pushSubscription) {
})); 26 122 // Check we have everything we need to unsubscribe
callback(true); 27 123 if (!pushSubscription) {
124 return;
} 28 125 }
29 126
console.log("gonna try to launch service worker now"); 30 127 // TODO: Remove the device details from the server
if ('serviceWorker' in navigator) { 31 128 // i.e. the pushSubscription.subscriptionId and
129 // pushSubscription.endpoint
32 130
console.log('gonna try to launch service worker now'); 33 131 pushSubscription.unsubscribe().then(function(successful) {
navigator.serviceWorker.register('scripts/service-worker.js').then( 34 132 console.log('Unsubscribed from push: ', successful);
function(serviceWorkerRegistration) { 35 133 if (!successful) {
serviceWorkerRegistration.pushManager.subscribe().then( 36 134 // The unsubscribe was unsuccessful, but we can
function(pushSubscription) { 37 135 // remove the subscriptionId from our server
console.log('sub id: ', pushSubscription.subscriptionId); 38 136 // and notifications will stop
console.log('endpoint: ', pushSubscription.endpoint); 39 137 // This just may be in a bad state when the user returns
// The push subscription details needed by the application 40 138 console.error('We were unable to unregister from push');
// server are now available, and can be sent to it using, 41 139 }
// for example, an XMLHttpRequest. 42 140
}, function(error) { 43 141 }).catch(function(e) {
// During development it often helps to log errors to the 44 142 console.log('Unsubscribtion error: ', e);
// console. In a production environment it might make sense to 45
// also report information about errors back to the 46
// application server. 47
console.log('sub error: ', error); 48
} 49
); 50
}); 51 143 });
144 }.bind(this)).catch(function(e) {
145 console.error('Error thrown while revoking push notifications. ' +
146 'Most likely because push was never registered', e);
147 });
148 });
149 }
52 150
} else { 53 151 function permissionStatusChange(permissionStatus) {
console.log('Service workers aren\'t supported in this browser.'); 54 152 console.log('permissionStatusChange = ', permissionStatus);
} 55 153 // If the notification permission is denied, it's a permanent block
154 switch (permissionStatus.status) {
155 case 'denied':
156 console.log('Ooops Push has been Blocked',
157 'Unfortunately the user permanently blocked push. Please unblock / ' +
158 'allow them to switch on push notifications.');
159 break;
160 case 'granted':
161 // Set the state of the push switch
162 console.log("case granted");
163 break;
164 case 'prompt':
165 console.log("case prompt");
166 break;
167 }
168 }
56 169
170 function setUpPushPermission() {
171 navigator.permissions.query({name: 'push', userVisibleOnly: true})
172 .then(function(permissionStatus) {
173 // Set the initial state
174 permissionStatusChange(permissionStatus);
57 175
}); 58 176 // Handle Permission State Changes
177 permissionStatus.onchange = function() {
178 permissionStatusChange(this);
179 };
180
181 // Check if push is supported and what the current state is
182 navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
183 // Let's see if we have a subscription already
184 serviceWorkerRegistration.pushManager.getSubscription()
185 .then(function(subscription) {
186 if (!subscription) {
187 // NOOP
188 return;
189 }
190
191 // Update the current state with the
192 // subscriptionid and endpoint
193 onPushSubscription(subscription);
194 })
195 .catch(function(e) {
196 console.log('An error occured while calling getSubscription()', e);
197 });
198 });
199 }).catch(function(err) {
200 console.log('Ooops Unable to check the permission',
201 'Unfortunately the permission for push notifications couldn\'t be ' +
202 'checked. Are you on Chrome 43+?');
203 });
204 }
205
206 function setUpNotificationPermission() {
207 // If the notification permission is denied, it's a permanent block
208 if (Notification.permission === 'denied') {
209 console.log('Ooops Notifications are Blocked',
210 'Unfortunately notifications are permanently blocked. Please unblock / ' +
211 'allow them to switch on push notifications.');
212 return;
213 } else if (Notification.permission === 'default') {
214 console.log("notification permissions === default");
215 return;
216 }
217
218 // Check if push is supported and what the current state is
219 navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
220 // Let's see if we have a subscription already
221 serviceWorkerRegistration.pushManager.getSubscription()
222 .then(function(subscription) {
223 if (!subscription) {
224 // NOOP
225 console.log("not subscription");
226 return;
227 }
228
229 // Update the current state with the
230 // subscriptionid and endpoint
231 console.log("onpushsubscription should be entered");
232 onPushSubscription(subscription);
233 })
234 .catch(function(e) {
235 console.log('An error occured while calling getSubscription()', e);
236 });
237 });
238 }
239
240 // Once the service worker is registered set the initial state
241 function initialiseState() {
242 // Is the Permissions API supported
243 if ('permissions' in navigator) {
244 console.log("setting push permissions");
245 setUpPushPermission();
246 return;
247 } else {
248 console.log("setting notification permissions");
249 setUpNotificationPermission();
250 }
251 }
252 window.addEventListener('load', function() {
253 // When the toggle switch changes, enabled / disable push
254 // messaging
255 var enablePushSwitch = document.querySelector('.js-checkbox');
256 enablePushSwitch.addEventListener('change', function(e) {
257 if (e.target.checked) {
258 subscribeDevice();
259 } else {
260 unsubscribeDevice();
261 }
262 });
263
264 // Check that service workers are supported
265 if ('serviceWorker' in navigator) {
266 navigator.serviceWorker.register('scripts/service-worker.js')
267 .then(initialiseState);
268 } else {
269 // Service Workers aren't supported so you should hide the push UI
270 // If it's currently visible.
271 console.log('Ooops Service Workers aren\'t Supported',
272 'Service Workers aren\'t supported in this browser. ' +
273 'For this demo be sure to use ' +
274 '<a href="https://www.google.co.uk/chrome/browser/canary.html">Chrome Canary</a>' +
275 ' or version 42.');
276 }
277 });
278
scripts/service-worker.js View file @ 70278fc
'use strict'; 1 1 'use strict';
2 2
var PUSH_SERVER_URL = 'https://flashy.cards/app/subscribe/'; 3 3 function showNotification(title, body, icon, data) {
4 4 var notificationOptions = {
function onPushSubscription(pushSubscription) { 5 5 body: body,
console.log('pushSubscription = ', pushSubscription.endpoint); 6 6 icon: icon ? icon : 'images/touch/chrome-touch-icon-192x192.png',
// Here we would normally send the endpoint 7 7 tag: 'simple-push-demo-notification',
// and subscription ID to our server. 8 8 data: data
// In this demo we just use send these values to 9 9 };
// our server via XHR which sends a push message. 10 10 if (self.registration.showNotification) {
11 11 self.registration.showNotification(title, notificationOptions);
console.log('pushSubscription: ', pushSubscription); 12 12 return;
13 13 } else {
// Code to handle the XHR 14 14 new Notification(title, notificationOptions);
var formData = new FormData(); 15
16
var endpoint = pushSubscription.endpoint; 17
18
fetch(PUSH_SERVER_URL, { 19
method: 'post', 20
body: formData 21
}).then(function(response) { 22
console.log('Response = ', response); 23
}).catch(function(err) { 24
console.log('Fetch Error :-S', err); 25
}); 26
27
} 28
29
function subscribeDevice() { 30
// We need the service worker registration to access the push manager 31
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { 32
serviceWorkerRegistration.pushManager.subscribe() 33
.then(onPushSubscription) 34
.catch(function(e) { 35
// Check for a permission prompt issue 36
if ('permissions' in navigator) { 37
navigator.permissions.query({name: 'push', userVisibleOnly: true}) 38
.then(function(permissionStatus) { 39
console.log('subscribe() Error: Push permission status = ', 40
permissionStatus); 41
if (permissionStatus.status === 'denied') { 42
// The user blocked the permission prompt 43
console.log('Ooops Notifications are Blocked', 44
'Unfortunately you just permanently blocked notifications. ' + 45
'Please unblock / allow them to switch on push ' + 46
'notifications.'); 47
} else { 48
console.log('Ooops Push Couldn\'t Register', 49
'<p>When we tried to ' + 50
'get the subscription ID for GCM, something went wrong,' + 51
' not sure why.</p>' + 52
'<p>Have you defined "gcm_sender_id" and ' + 53
'"gcm_user_visible_only" in the manifest?</p>' + 54
'<p>Error message: ' + 55
e.message + 56
'</p>'); 57
} 58
}).catch(function(err) { 59
console.log('Ooops Push Couldn\'t Register', 60
'<p>When we tried to ' + 61
'get the subscription ID for GCM, something went wrong, not ' + 62
'sure why.</p>' + 63
'<p>Have you defined "gcm_sender_id" and ' + 64
'"gcm_user_visible_only" in the manifest?</p>' + 65
'<p>Error message: ' + 66
err.message + 67
'</p>'); 68
}); 69
} else { 70
// Use notification permission to do something 71
if (Notification.permission === 'denied') { 72
console.log('Ooops Notifications are Blocked', 73
'Unfortunately you just permanently blocked notifications. ' + 74
'Please unblock / allow them to switch on push notifications.'); 75
} else { 76
console.log('Ooops Push Couldn\'t Register', 77
'<p>When we tried to ' + 78
'get the subscription ID for GCM, something went wrong, not ' + 79
'sure why.</p>' + 80
'<p>Have you defined "gcm_sender_id" and ' + 81
'"gcm_user_visible_only" in the manifest?</p>' + 82
'<p>Error message: ' + 83
e.message + 84
'</p>'); 85
} 86
} 87
}); 88
}); 89
} 90
91
function unsubscribeDevice() { 92
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { 93
serviceWorkerRegistration.pushManager.getSubscription().then( 94
function(pushSubscription) { 95
// Check we have everything we need to unsubscribe 96
if (!pushSubscription) { 97
return; 98
} 99
100
// TODO: Remove the device details from the server 101
// i.e. the pushSubscription.subscriptionId and 102
// pushSubscription.endpoint 103
104
pushSubscription.unsubscribe().then(function(successful) { 105
console.log('Unsubscribed from push: ', successful); 106
if (!successful) { 107
// The unsubscribe was unsuccessful, but we can 108
// remove the subscriptionId from our server 109
// and notifications will stop 110
// This just may be in a bad state when the user returns 111
console.error('We were unable to unregister from push'); 112
} 113
114
}).catch(function(e) { 115
console.log('Unsubscribtion error: ', e); 116
}); 117
}.bind(this)).catch(function(e) { 118
console.error('Error thrown while revoking push notifications. ' + 119
'Most likely because push was never registered', e); 120
}); 121
}); 122
} 123
124
function permissionStatusChange(permissionStatus) { 125
console.log('permissionStatusChange = ', permissionStatus); 126
// If the notification permission is denied, it's a permanent block 127
switch (permissionStatus.status) { 128
case 'denied': 129
console.log('Ooops Push has been Blocked', 130
'Unfortunately the user permanently blocked push. Please unblock / ' + 131
'allow them to switch on push notifications.'); 132
break; 133
case 'granted': 134
// Set the state of the push switch 135
console.log("case granted"); 136
break; 137
case 'prompt': 138
console.log("case prompt"); 139
break; 140
} 141 15 }
} 142 16 }
143 17
function setUpPushPermission() { 144 18 self.addEventListener('push', function(event) {
navigator.permissions.query({name: 'push', userVisibleOnly: true}) 145 19 console.log('Received a push message', event);
.then(function(permissionStatus) { 146
// Set the initial state 147
permissionStatusChange(permissionStatus); 148
149 20
// Handle Permission State Changes 150 21 // Since this is no payload data with the first version
permissionStatus.onchange = function() { 151 22 // of Push notifications, here we'll grab some data from
permissionStatusChange(this); 152 23 // an API and use it to populate a notification
}; 153 24 var title = 'You have cards waiting to be reviewed!';
25 var message = 'check yo cards m8';
26 var icon = 'flashy.ico';
27 var notificationTag = 'simple-push-demo-notification';
154 28
// Check if push is supported and what the current state is 155 29 // Add this to the data of the notification
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { 156 30 var urlToOpen = '/api/subscribe/';
// Let's see if we have a subscription already 157
serviceWorkerRegistration.pushManager.getSubscription() 158
.then(function(subscription) { 159
if (!subscription) { 160
// NOOP 161
return; 162
} 163
164 31
// Update the current state with the 165 32 var notificationFilter = {
// subscriptionid and endpoint 166 33 tag: 'simple-push-demo-notification'
onPushSubscription(subscription); 167 34 };
}) 168 35 var notificationData = {
.catch(function(e) { 169 36 url: urlToOpen
console.log('An error occured while calling getSubscription()', e); 170 37 };
}); 171 38 return showNotification(title, message, icon, notificationData);
}); 172 39 });
}).catch(function(err) { 173
console.log('Ooops Unable to check the permission', 174
'Unfortunately the permission for push notifications couldn\'t be ' + 175
'checked. Are you on Chrome 43+?'); 176
}); 177
} 178
179 40
function setUpNotificationPermission() { 180 41 self.addEventListener('notificationclick', function(event) {
// If the notification permission is denied, it's a permanent block 181 42 console.log('On notification click: ', event);
if (Notification.permission === 'denied') { 182
console.log('Ooops Notifications are Blocked', 183
'Unfortunately notifications are permanently blocked. Please unblock / ' + 184
'allow them to switch on push notifications.'); 185
return; 186
} else if (Notification.permission === 'default') { 187
console.log("notification permissions === default"); 188
return; 189
} 190
191 43
// Check if push is supported and what the current state is 192 44 var url = event.notification.data.url;
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { 193 45 event.waitUntil(clients.openWindow(url));
// Let's see if we have a subscription already 194
serviceWorkerRegistration.pushManager.getSubscription() 195
.then(function(subscription) { 196
if (!subscription) { 197
// NOOP 198
console.log("not subscription"); 199
return; 200
} 201
202
// Update the current state with the 203
// subscriptionid and endpoint 204
onPushSubscription(subscription); 205
}) 206
.catch(function(e) { 207
console.log('An error occured while calling getSubscription()', e); 208
}); 209
}); 210
} 211
212
// Once the service worker is registered set the initial state 213
function initialiseState() { 214
// Is the Permissions API supported 215
if ('permissions' in navigator) { 216
setUpPushPermission(); 217
return; 218
} else { 219
setUpNotificationPermission(); 220
} 221
} 222
223
self.addEventListener('UIReady', function() { 224
// When the toggle switch changes, enabled / disable push 225
// messaging 226
var enablePushSwitch = document.querySelector('.js-checkbox'); 227
enablePushSwitch.addEventListener('change', function(e) { 228
if (e.target.checked) { 229
subscribeDevice(); 230
} else { 231
unsubscribeDevice(); 232
} 233
}); 234
235
// Check that service workers are supported 236
if ('serviceWorker' in navigator) { 237
navigator.serviceWorker.register('/service-worker.js', { 238
scope: './' 239
}) 240
.then(initialiseState); 241
} else { 242
// Service Workers aren't supported so you should hide the push UI 243
// If it's currently visible. 244
console.log('Ooops Service Workers aren\'t Supported', 245
'Service Workers aren\'t supported in this browser. ' + 246
'For this demo be sure to use ' + 247
'<a href="https://www.google.co.uk/chrome/browser/canary.html">Chrome Canary</a>' + 248
' or version 42.'); 249
} 250
}); 251 46 });
252 47