gamja-old/webpush.js

57 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

2021-05-20 14:03:44 -04:00
import * as irc from "./lib/irc.js";
async function register(client) {
let encodedVapidPubkey = client.isupport.get("VAPID");
if (!encodedVapidPubkey) {
throw new Error("Server is missing VAPID public key");
}
let vapidPubKey = urlBase64ToUint8Array(encodedVapidPubkey);
let registration = await navigator.serviceWorker.ready;
let subscription = registration.pushManager.getSubscription();
if (subscription && !compareVapidPubkeys(subscription.options.applicationServerKey, vapidPubKey)) {
await subscription.unsubscribe();
subscription = null;
}
if (!subscription) {
subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: vapidPubKey,
});
}
var data = subscription.toJSON();
var keysStr = irc.formatTags(data.keys);
client.send({
command: "WEBPUSH",
params: ["REGISTER", data.endpoint, keysStr],
});
}
function urlBase64ToUint8Array(base64String) {
var padding = '='.repeat((4 - base64String.length % 4) % 4);
var base64 = (base64String + padding)
.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 compareVapidPubkeys(a, b) {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}