Moved some files around, improved how notifications are being requested, and improved activation and installation-flow of serviceworker

This commit is contained in:
Kasper Rynning-Tønnesen
2020-02-21 14:36:27 +01:00
parent ac1e73ee09
commit 8b1d86bd9b
8 changed files with 291 additions and 113 deletions

View File

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
<path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/>
</svg>

After

Width:  |  Height:  |  Size: 267 B

View File

@@ -1,188 +0,0 @@
var version = "v1.0" + __DATE__;
var cacheName = "vinlottis";
var CACHE_NAME = cacheName;
var CACHE_NAME_API = cacheName + "::api";
var STATIC_CACHE_URLS = ["/"];
console.log("Nåværende versjon:", version);
self.addEventListener("activate", event => {
console.log("Aktiverer");
event.waitUntil(removeCache(CACHE_NAME));
event.waitUntil(removeCache(CACHE_NAME_API));
event.waitUntil(addCache(CACHE_NAME, STATIC_CACHE_URLS));
event.waitUntil(
new Promise((resolve, reject) => {
const applicationServerKey = urlB64ToUint8Array(__PUBLICKEY__);
const options = { applicationServerKey, userVisibleOnly: true };
self.registration.pushManager
.subscribe(options)
.then(subscription =>
saveSubscription(subscription)
.then(() => {
resolve();
})
.catch(() => {
resolve();
})
)
.catch(() => {
console.log("Kunne ikke legge til pushnotifications");
resolve();
});
})
);
});
self.addEventListener("message", event => {
if (event.data === "updatePush") {
event.waitUntil(
new Promise((resolve, reject) => {
const applicationServerKey = urlB64ToUint8Array(__PUBLICKEY__);
const options = { applicationServerKey, userVisibleOnly: true };
self.registration.pushManager
.subscribe(options)
.then(subscription =>
saveSubscription(subscription)
.then(() => {
const channel = new BroadcastChannel("updatePush");
channel.postMessage({ success: true });
resolve();
})
.catch(() => {
resolve();
})
)
.catch(() => {
console.log("Kunne ikke legge til pushnotifications");
reject();
});
})
);
}
});
self.addEventListener("push", function(event) {
if (event.data) {
var message = JSON.parse(event.data.text());
showLocalNotification(message.title, message.message, self.registration);
} else {
}
});
self.addEventListener("install", event => {
console.log("Arbeids arbeideren installerer seg.");
self.skipWaiting();
event.waitUntil(addCache(CACHE_NAME, STATIC_CACHE_URLS));
});
self.addEventListener("fetch", event => {
if (
event.request.url.includes("/login") ||
event.request.url.includes("/update") ||
event.request.url.includes("/register") ||
event.request.method == "POST" ||
event.request.url.includes("/api/wines/prelottery")
) {
event.respondWith(fetch(event.request));
return;
}
if (event.request.url.includes("/api/")) {
event.respondWith(
fetch(event.request)
.then(response => cache(event.request, response))
.catch(function() {
return caches.match(event.request);
})
);
} else {
event.respondWith(
caches
.match(event.request) // check if the request has already been cached
.then(cached => cached || fetch(event.request)) // otherwise request network
.then(
response =>
staticCache(event.request, response) // put response in cache
.then(() => response) // resolve promise with the network response
)
);
}
});
function showLocalNotification(title, body, swRegistration) {
const options = {
body,
icon: "https://lottis.vin/public/assets/images/favicon.png",
image: "https://lottis.vin/public/assets/images/favicon.png",
vibrate: [300]
};
swRegistration.showNotification(title, options);
}
async function saveSubscription(subscription) {
const SERVER_URL = "https://lottis.vin/subscription/save-subscription";
const response = await fetch(SERVER_URL, {
method: "post",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(subscription)
});
return response.json();
}
const urlB64ToUint8Array = base64String => {
const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, "+")
.replace(/_/g, "/");
const rawData = atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
};
function addCache(cacheKey, cacheUrls) {
return caches.open(cacheKey).then(cache => {
console.log("Legger til cache", cache);
return cache.addAll(cacheUrls);
});
}
function removeCache(cacheKey) {
return caches
.keys()
.then(keys => keys.filter(key => key !== cacheKey))
.then(keys =>
Promise.all(
keys.map(key => {
console.log(`Sletter mellom-lager på nøkkel ${key}`);
return caches.delete(key);
})
)
);
}
function staticCache(request, response) {
if (response.type === "error" || response.type === "opaque") {
return Promise.resolve(); // do not put in cache network errors
}
return caches
.open(CACHE_NAME)
.then(cache => cache.put(request, response.clone()));
}
function cache(request, response) {
if (response.type === "error" || response.type === "opaque") {
return response;
}
return caches.open(CACHE_NAME_API).then(cache => {
cache.put(request, response.clone());
return response;
});
}