2017-07-13 23:15:32 +03:00
|
|
|
import './web_push_notifications';
|
2017-07-18 01:19:17 +03:00
|
|
|
|
2018-03-18 16:14:38 +02:00
|
|
|
function openCache() {
|
|
|
|
return caches.open('mastodon-web');
|
|
|
|
}
|
|
|
|
|
2018-03-17 13:35:13 +02:00
|
|
|
function fetchRoot() {
|
|
|
|
return fetch('/', { credentials: 'include' });
|
|
|
|
}
|
|
|
|
|
2017-07-18 01:19:17 +03:00
|
|
|
// Cause a new version of a registered Service Worker to replace an existing one
|
|
|
|
// that is already installed, and replace the currently active worker on open pages.
|
|
|
|
self.addEventListener('install', function(event) {
|
2018-03-18 16:14:38 +02:00
|
|
|
event.waitUntil(Promise.all([openCache(), fetchRoot()]).then(([cache, root]) => cache.put('/', root)));
|
2017-07-18 01:19:17 +03:00
|
|
|
});
|
|
|
|
self.addEventListener('activate', function(event) {
|
|
|
|
event.waitUntil(self.clients.claim());
|
|
|
|
});
|
2018-03-17 13:35:13 +02:00
|
|
|
self.addEventListener('fetch', function(event) {
|
|
|
|
const url = new URL(event.request.url);
|
|
|
|
|
|
|
|
if (url.pathname.startsWith('/web/')) {
|
2018-03-18 16:14:38 +02:00
|
|
|
const asyncResponse = fetchRoot();
|
|
|
|
const asyncCache = openCache();
|
|
|
|
|
|
|
|
event.respondWith(asyncResponse.then(async response => {
|
2018-03-17 13:35:13 +02:00
|
|
|
if (response.ok) {
|
2018-03-18 16:14:38 +02:00
|
|
|
const cache = await asyncCache;
|
|
|
|
await cache.put('/', response);
|
|
|
|
return response.clone();
|
2018-03-17 13:35:13 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
throw null;
|
|
|
|
}).catch(() => caches.match('/')));
|
2018-03-18 16:14:38 +02:00
|
|
|
} else if (url.pathname === '/auth/sign_out') {
|
|
|
|
const asyncResponse = fetch(event.request);
|
|
|
|
const asyncCache = openCache();
|
|
|
|
|
|
|
|
event.respondWith(asyncResponse.then(async response => {
|
|
|
|
if (response.ok || response.type === 'opaqueredirect') {
|
|
|
|
const cache = await asyncCache;
|
|
|
|
await cache.delete('/');
|
|
|
|
}
|
|
|
|
|
|
|
|
return response;
|
|
|
|
}));
|
2018-03-17 13:35:13 +02:00
|
|
|
}
|
|
|
|
});
|