forked from phpbb/phpbb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebpush.js
More file actions
300 lines (259 loc) · 7.54 KB
/
webpush.js
File metadata and controls
300 lines (259 loc) · 7.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/* global phpbb */
'use strict';
function PhpbbWebpush() {
/** @type {string} URL to service worker */
let serviceWorkerUrl = '';
/** @type {string} URL to subscribe to push */
let subscribeUrl = '';
/** @type {string} URL to unsubscribe from push */
let unsubscribeUrl = '';
/** @type { {creationTime: number, formToken: string} } Form tokens */
this.formTokens = {
creationTime: 0,
formToken: '',
};
/** @type {{endpoint: string, expiration: string}[]} Subscriptions */
let subscriptions;
/** @type {string} Title of error message */
let ajaxErrorTitle = '';
/** @type {string} VAPID public key */
let vapidPublicKey = '';
/** @type {HTMLElement} Subscribe button */
let subscribeButton;
/** @type {HTMLElement} Unsubscribe button */
let unsubscribeButton;
/**
* Init function for phpBB Web Push
* @type {array} options
*/
this.init = function(options) {
serviceWorkerUrl = options.serviceWorkerUrl;
subscribeUrl = options.subscribeUrl;
unsubscribeUrl = options.unsubscribeUrl;
this.formTokens = options.formTokens;
subscriptions = options.subscriptions;
ajaxErrorTitle = options.ajaxErrorTitle;
vapidPublicKey = options.vapidPublicKey;
subscribeButton = document.querySelector('#subscribe_webpush');
unsubscribeButton = document.querySelector('#unsubscribe_webpush');
// Service workers are only supported in secure context
if (window.isSecureContext !== true) {
subscribeButton.disabled = true;
return;
}
if ('serviceWorker' in navigator && 'PushManager' in window) {
navigator.serviceWorker.register(serviceWorkerUrl)
.then(() => {
subscribeButton.addEventListener('click', subscribeButtonHandler);
unsubscribeButton.addEventListener('click', unsubscribeButtonHandler);
updateButtonState();
})
.catch(error => {
console.info(error);
// Service worker could not be registered
subscribeButton.disabled = true;
});
} else {
subscribeButton.disabled = true;
}
};
/**
* Update button state depending on notifications state
*
* @return void
*/
function updateButtonState() {
if (Notification.permission === 'granted') {
navigator.serviceWorker.getRegistration(serviceWorkerUrl)
.then(registration => {
if (typeof registration === 'undefined') {
return;
}
registration.pushManager.getSubscription()
.then(subscribed => {
if (isValidSubscription(subscribed)) {
setSubscriptionState(true);
}
});
});
}
}
/**
* Check whether subscription is valid
*
* @param {PushSubscription} subscription
* @returns {boolean}
*/
const isValidSubscription = subscription => {
if (!subscription) {
return false;
}
if (subscription.expirationTime && subscription.expirationTime <= Date.now()) {
return false;
}
for (const curSubscription of subscriptions) {
if (subscription.endpoint === curSubscription.endpoint) {
return true;
}
}
// Subscription is not in valid subscription list for user
return false;
};
/**
* Set subscription state for buttons
*
* @param {boolean} subscribed True if subscribed, false if not
*/
function setSubscriptionState(subscribed) {
if (subscribed) {
subscribeButton.classList.add('hidden');
unsubscribeButton.classList.remove('hidden');
} else {
subscribeButton.classList.remove('hidden');
unsubscribeButton.classList.add('hidden');
}
}
/**
* Handler for pushing subscribe button
*
* @param {Object} event Subscribe button push event
* @returns {Promise<void>}
*/
async function subscribeButtonHandler(event) {
event.preventDefault();
subscribeButton.addEventListener('click', subscribeButtonHandler);
// Prevent the user from clicking the subscribe button multiple times.
const result = await Notification.requestPermission();
if (result === 'denied') {
return;
}
const registration = await navigator.serviceWorker.getRegistration(serviceWorkerUrl);
// We might already have a subscription that is unknown to this instance of phpBB.
// Unsubscribe before trying to subscribe again.
if (typeof registration !== 'undefined') {
const subscribed = await registration.pushManager.getSubscription();
if (subscribed) {
await subscribed.unsubscribe();
}
}
const newSubscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlB64ToUint8Array(vapidPublicKey),
});
const loadingIndicator = phpbb.loadingIndicator();
fetch(subscribeUrl, {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
body: getFormData(newSubscription),
})
.then(response => {
loadingIndicator.fadeOut(phpbb.alertTime);
return response.json();
})
.then(handleSubscribe)
.catch(error => {
loadingIndicator.fadeOut(phpbb.alertTime);
phpbb.alert(ajaxErrorTitle, error);
});
}
/**
* Handler for pushing unsubscribe button
*
* @param {Object} event Unsubscribe button push event
* @returns {Promise<void>}
*/
async function unsubscribeButtonHandler(event) {
event.preventDefault();
const registration = await navigator.serviceWorker.getRegistration(serviceWorkerUrl);
if (typeof registration === 'undefined') {
return;
}
const subscription = await registration.pushManager.getSubscription();
const loadingIndicator = phpbb.loadingIndicator();
fetch(unsubscribeUrl, {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
body: getFormData({ endpoint: subscription.endpoint }),
})
.then(() => {
loadingIndicator.fadeOut(phpbb.alertTime);
return subscription.unsubscribe();
})
.then(unsubscribed => {
if (unsubscribed) {
setSubscriptionState(false);
}
})
.catch(error => {
loadingIndicator.fadeOut(phpbb.alertTime);
phpbb.alert(ajaxErrorTitle, error);
});
}
/**
* Handle subscribe response
*
* @param {Object} response Response from subscription endpoint
*/
function handleSubscribe(response) {
if (response.success) {
setSubscriptionState(true);
if ('form_tokens' in response) {
updateFormTokens(response.form_tokens);
}
}
}
/**
* Get form data object including form tokens
*
* @param {Object} data Data to create form data from
* @returns {FormData} Form data
*/
function getFormData(data) {
const formData = new FormData();
formData.append('form_token', phpbb.webpush.formTokens.formToken);
formData.append('creation_time', phpbb.webpush.formTokens.creationTime.toString());
formData.append('data', JSON.stringify(data));
return formData;
}
/**
* Update form tokens with supplied ones
*
* @param {Object} formTokens
*/
function updateFormTokens(formTokens) {
phpbb.webpush.formTokens.creationTime = formTokens.creation_time;
phpbb.webpush.formTokens.formToken = formTokens.form_token;
}
/**
* Convert a base64 string to Uint8Array
*
* @param base64String
* @returns {Uint8Array}
*/
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
}
function domReady(callBack) {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', callBack);
} else {
callBack();
}
}
phpbb.webpush = new PhpbbWebpush();
domReady(() => {
/* global phpbbWebpushOptions */
phpbb.webpush.init(phpbbWebpushOptions);
});