2023-01-01 13:06:01 -08:00
|
|
|
import { post, destroy } from '@rails/request.js';
|
2022-10-21 13:37:52 -07:00
|
|
|
import { showErrorNotification, showNotification } from "utilities/notifications";
|
|
|
|
import I18n from "retrospring/i18n";
|
|
|
|
|
2022-10-23 07:00:21 -07:00
|
|
|
export function unsubscribeHandler(): void {
|
|
|
|
navigator.serviceWorker.getRegistration()
|
|
|
|
.then(registration => registration.pushManager.getSubscription())
|
|
|
|
.then(subscription => unsubscribeClient(subscription))
|
|
|
|
.then(subscription => unsubscribeServer(subscription))
|
|
|
|
.catch(error => {
|
2022-10-21 13:37:52 -07:00
|
|
|
showErrorNotification(I18n.translate("frontend.push_notifications.unsubscribe.error"));
|
|
|
|
console.error(error);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-01-01 13:06:01 -08:00
|
|
|
export function checkSubscription(subscription: PushSubscription): void {
|
|
|
|
post('/ajax/webpush/check', {
|
|
|
|
body: {
|
|
|
|
endpoint: subscription.endpoint
|
|
|
|
},
|
|
|
|
contentType: 'application/json'
|
|
|
|
}).then(async response => {
|
|
|
|
const data = await response.json();
|
|
|
|
|
|
|
|
if (data.status == 'subscribed') return;
|
|
|
|
if (data.status == 'failed') await unsubscribeServer(subscription);
|
|
|
|
await unsubscribeClient(subscription);
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-10-23 07:00:21 -07:00
|
|
|
async function unsubscribeClient(subscription?: PushSubscription): Promise<PushSubscription|null> {
|
|
|
|
subscription?.unsubscribe().then(success => {
|
|
|
|
if (!success) {
|
|
|
|
throw new Error("Failed to unsubscribe.");
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return subscription;
|
|
|
|
}
|
|
|
|
|
|
|
|
async function unsubscribeServer(subscription?: PushSubscription): Promise<void> {
|
|
|
|
const body = subscription != null ? { endpoint: subscription.endpoint } : undefined;
|
|
|
|
|
|
|
|
return destroy('/ajax/webpush', {
|
|
|
|
body,
|
|
|
|
contentType: 'application/json',
|
|
|
|
}).then(async response => {
|
|
|
|
const data = await response.json;
|
|
|
|
|
|
|
|
if (data.success) {
|
|
|
|
showNotification(I18n.translate("frontend.push_notifications.unsubscribe.success"));
|
|
|
|
|
|
|
|
document.getElementById('subscription-count').textContent = data.message;
|
|
|
|
|
|
|
|
if (data.count == 0) {
|
|
|
|
document.querySelectorAll<HTMLButtonElement>('button[data-action="push-disable"], button[data-action="push-remove-all"]')
|
|
|
|
.forEach(button => button.classList.add('d-none'));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (document.body.classList.contains('cap-service-worker') && document.body.classList.contains('cap-notification')) {
|
|
|
|
document.querySelector<HTMLButtonElement>('button[data-action="push-enable"]')?.classList.remove('d-none');
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
showErrorNotification(I18n.translate("frontend.push_notifications.unsubscribe.fail"));
|
|
|
|
}
|
|
|
|
})
|
2022-10-21 13:37:52 -07:00
|
|
|
}
|