mirror of
https://github.com/phpbb/phpbb.git
synced 2025-08-06 16:56:44 +02:00
[ticket/17010] Handle already existing subscriptions
PHPBB3-17010
This commit is contained in:
@@ -18,6 +18,13 @@ function PhpbbWebpush() {
|
||||
formToken: '{{ FORM_TOKENS.form_token }}'
|
||||
};
|
||||
|
||||
/** @type [{endpoint: string, expiration: string}[]] Subscriptions */
|
||||
let subscriptions = [
|
||||
{% for sub in SUBSCRIPTIONS %}
|
||||
{endpoint: '{{ sub.endpoint }}', expiration: '{{ sub.expiration }}' },
|
||||
{% endfor %}
|
||||
];
|
||||
|
||||
/** @type {string} VAPID public key */
|
||||
const VAPID_PUBLIC_KEY = '{{ VAPID_PUBLIC_KEY }}';
|
||||
|
||||
@@ -70,7 +77,7 @@ function PhpbbWebpush() {
|
||||
|
||||
registration.pushManager.getSubscription()
|
||||
.then((subscribed) => {
|
||||
if (subscribed) {
|
||||
if (isValidSubscription(subscribed)) {
|
||||
setSubscriptionState(true);
|
||||
}
|
||||
})
|
||||
@@ -78,6 +85,31 @@ function PhpbbWebpush() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
@@ -111,16 +143,19 @@ function PhpbbWebpush() {
|
||||
}
|
||||
|
||||
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) {
|
||||
setSubscriptionState(true);
|
||||
return;
|
||||
await subscribed.unsubscribe();
|
||||
}
|
||||
}
|
||||
const newSubscription = await registration.pushManager.subscribe({
|
||||
|
||||
let newSubscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: urlB64ToUint8Array(VAPID_PUBLIC_KEY)
|
||||
applicationServerKey: urlB64ToUint8Array(VAPID_PUBLIC_KEY),
|
||||
});
|
||||
|
||||
const loadingIndicator = phpbb.loadingIndicator();
|
||||
|
Reference in New Issue
Block a user