combo-plugin-gnm/combo_plugin_gnm/static/combo_plugin_gnm/webpush.js

239 lines
6.8 KiB
JavaScript

// Based On https://raw.githubusercontent.com/safwanrahman/django-webpush/aed8d5213d76857bfb3a020c1c6b8af18cad0f12/webpush/static/webpush/webpush.js
// combo-plugin-gnm - Combo GNM plugin
// Copyright (C) 2018 Entr'ouvert
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
var subBtn,
messageBox,
registration;
var activateTextMessage = 'Activez les notifications';
var stopTextMessage = 'Stoppez les notifications';
var incompatibleMessage = 'Ce navigateur n&#39;est pas compatible avec les notifications push.';
var browserShortName = navigator.userAgent.match(/(firefox|msie|chrome|safari|trident)/ig)[0].toLowerCase();
$(window).load(function () {
subBtn = $('#webpush-subscribe-checkbox');
messageBox = $('#webpush-subscribe-message');
function set_btn_activate() {
subBtn.attr('disabled', false);
subBtn.attr('checked', false);
subBtn.removeClass("checked");
messageBox.text(activateTextMessage);
}
function set_btn_cancel() {
subBtn.attr('disabled', false);
subBtn.attr('checked', true);
subBtn.addClass("checked");
messageBox.text(stopTextMessage);
}
var user_subscription_browser_list = subBtn.data('userSubscriptionBrowserList').split("=#=#");
if (user_subscription_browser_list.indexOf(browserShortName) >= 0) {
set_btn_cancel();
} else {
set_btn_activate();
}
// show warning to the message box and disabled the input
if (!('serviceWorker' in navigator)) {
messageBox.text(incompatibleMessage);
subBtn.attr('checked', false);
subBtn.attr('disabled', true);
return;
}
subBtn.click(
function (evt) {
subBtn.attr('disabled', true);
// if the Browser Supports Service Worker
// registered the worker and the click event hanlder
if ('serviceWorker' in navigator) {
var serviceWorker = document.getElementById('service-worker-js').src;
navigator.serviceWorker.register(serviceWorker)
.then(
function (reg) {
messageBox.text('Connexion au serveur en cours...');
registration = reg;
initialiseState(reg);
}
);
}
}
);
// Once the service worker is registered set the initial state
function initialiseState(reg) {
// Check if PushManager, Notification is supported in the browser
if (!('PushManager' in window) || !(reg.showNotification)) {
messageBox.text(incompatibleMessage);
subBtn.attr('checked', false);
subBtn.attr('disabled', true);
return;
}
// Check the current Notification permission.
// If its denied, it's a permanent block until the
// user changes the permission
if (Notification.permission === 'denied') {
// Show a message and activate the button
set_btn_activate();
return;
}
if (subBtn.filter(':checked')
.length > 0) {
return subscribe(reg);
} else {
return unsubscribe(reg);
}
}
function subscribe(reg) {
// Get the Subscription or register one
getSubscription(reg)
.then(
function (subscription) {
postSubscribeObj('subscribe', subscription);
}
)
.catch(
function (error) {
messageBox.text('Impossible de communiquer avec le serveur, veuillez r&eacute;essayer dans quelques minutes (Debug = '+ error +')');
}
);
}
function urlB64ToUint8Array(base64String) {
var b64padding = '='.repeat((4 - base64String.length % 4) % 4);
var base64 = (base64String + b64padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
var rawData = window.atob(base64);
var outputArray = new Uint8Array(rawData.length);
for (var i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
function getSubscription(reg) {
return reg.pushManager.getSubscription()
.then(
function (subscription) {
var metaObj, applicationServerKey, options;
// Check if Subscription is available
if (subscription) {
return subscription;
}
metaObj = document.querySelector('meta[name="django-webpush-vapid-key"]');
applicationServerKey = metaObj.content;
options = {
userVisibleOnly: true
};
if (applicationServerKey) {
options.applicationServerKey = urlB64ToUint8Array(applicationServerKey)
}
// If not, register one
return registration.pushManager.subscribe(options)
}
)
}
function unsubscribe() {
// Get the Subscription to unregister
registration.pushManager.getSubscription()
.then(
function (subscription) {
// Check we have a subscription to unsubscribe
if (!subscription) {
// No subscription object, so set the state
// to allow the user to subscribe to push
set_btn_activate();
return;
}
postSubscribeObj('unsubscribe', subscription);
}
)
}
function postSubscribeObj(statusType, subscription) {
// Send the information to the server with fetch API.
// the type of the request, the name of the user subscribing,
// and the push subscription endpoint + key the server needs
// to send push messages
// Each subscription is different for each of these navigator userAgent short name
var data = {
status_type: statusType,
subscription: subscription.toJSON(),
browser: browserShortName
// group: subBtn.dataset.group
};
fetch(subBtn.data('url'), {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
credentials: 'include'
})
.then(
function (response) {
// Check the information is saved successfully into server
if ((response.status == 201) && (statusType == 'subscribe')) {
// Show unsubscribe button instead
set_btn_cancel();
}
// Check if the information is deleted from server
if ((response.status == 202) && (statusType == 'unsubscribe')) {
// Get the Subscription
getSubscription(registration)
.then(
function (subscription) {
// Remove the subscription
subscription.unsubscribe()
.then(
function () {
set_btn_activate();
}
)
}
)
.catch(
function (error) {
subBtn.attr('disabled', false);
subBtn.attr('checked', false);
subBtn.removeClass("checked");
messageBox.text('Erreur lors de la requête, veuillez r&eacute;essayer dans quelques minutes (Debug = '+ error +')');
}
);
}
}
)
}
});