misskey/src/client/app/sw.js

74 lines
1.7 KiB
JavaScript
Raw Normal View History

2017-11-20 10:40:09 -08:00
/**
* Service Worker
*/
2017-11-20 12:09:45 -08:00
import composeNotification from './common/scripts/compose-notification';
2017-11-27 05:00:48 -08:00
// eslint-disable-next-line no-undef
const version = _VERSION_;
const cacheName = `mk-cache-${version}`;
const apiUrl = `${location.origin}/api/`;
2017-11-20 10:40:09 -08:00
// インストールされたとき
2017-11-27 05:00:48 -08:00
self.addEventListener('install', ev => {
2017-11-20 14:06:36 -08:00
console.info('installed');
2017-11-27 05:00:48 -08:00
ev.waitUntil(
caches.open(cacheName)
.then(cache => {
return cache.addAll([
"/",
`/assets/desktop.${version}.js`,
`/assets/mobile.${version}.js`,
"/assets/error.jpg"
]);
})
.then(() => self.skipWaiting())
);
});
self.addEventListener('activate', ev => {
ev.waitUntil(
caches.keys()
.then(cacheNames => Promise.all(
cacheNames
.filter((v) => v !== cacheName)
.map(name => caches.delete(name))
))
.then(() => self.clients.claim())
);
});
self.addEventListener('fetch', ev => {
if (ev.request.method !== 'GET' || ev.request.url.startsWith(apiUrl)) return;
ev.respondWith(
caches.match(ev.request)
.then(response => {
return response || fetch(ev.request);
})
.catch(() => {
return caches.match("/");
})
);
2017-11-27 05:00:48 -08:00
});
2017-11-20 10:40:09 -08:00
// プッシュ通知を受け取ったとき
self.addEventListener('push', ev => {
// クライアント取得
2017-11-20 14:06:36 -08:00
ev.waitUntil(self.clients.matchAll({
2017-11-20 10:40:09 -08:00
includeUncontrolled: true
}).then(clients => {
// クライアントがあったらストリームに接続しているということなので通知しない
if (clients.length != 0) return;
const { type, body } = ev.data.json();
2017-11-20 14:06:36 -08:00
2017-11-20 12:09:45 -08:00
const n = composeNotification(type, body);
2017-11-20 14:06:36 -08:00
return self.registration.showNotification(n.title, {
body: n.body,
icon: n.icon,
});
}));
2017-11-20 10:40:09 -08:00
});