mizzkey/src/client/sw/sw.ts

92 lines
2 KiB
TypeScript
Raw Normal View History

2017-11-21 03:40:09 +09:00
/**
* Service Worker
*/
declare var self: ServiceWorkerGlobalScope;
2017-11-21 03:40:09 +09:00
2020-12-26 14:11:08 +09:00
import composeNotification from '@/sw/compose-notification';
2021-01-21 21:17:22 +09:00
import { I18n } from '@/scripts/i18n';
export let i18n: I18n<any>;
let i: string;
2017-11-27 22:00:48 +09:00
const version = _VERSION_;
const cacheName = `mk-cache-${version}`;
const apiUrl = `${location.origin}/api/`;
2017-11-21 03:40:09 +09:00
// インストールされたとき
2017-11-27 22:00:48 +09:00
self.addEventListener('install', ev => {
ev.waitUntil(
caches.open(cacheName)
.then(cache => {
return cache.addAll([
2020-02-09 12:47:50 +09:00
`/?v=${version}`
]);
})
.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(() => {
2020-02-09 12:47:50 +09:00
return caches.match(`/?v=${version}`);
})
);
2017-11-27 22:00:48 +09:00
});
2017-11-21 03:40:09 +09:00
// プッシュ通知を受け取ったとき
self.addEventListener('push', ev => {
// クライアント取得
2017-11-21 07:06:36 +09:00
ev.waitUntil(self.clients.matchAll({
2017-11-21 03:40:09 +09:00
includeUncontrolled: true
}).then(async clients => {
2017-11-21 03:40:09 +09:00
// クライアントがあったらストリームに接続しているということなので通知しない
if (clients.length != 0) return;
2021-01-21 21:17:22 +09:00
const { type, body } = ev.data?.json();
2017-11-21 07:06:36 +09:00
2021-01-21 21:17:22 +09:00
const n = await composeNotification(type, body, i18n);
if (n) return self.registration.showNotification(...n);
2017-11-21 07:06:36 +09:00
}));
2017-11-21 03:40:09 +09:00
});
2021-01-21 21:17:22 +09:00
// クライアントのpostMessageを処理します
self.addEventListener('message', ev => {
switch(ev.data) {
case 'clear':
return; // TODO
default:
break;
}
if (typeof ev.data === 'object') {
const otype = Object.prototype.toString.call(ev.data).slice(8, -1).toLowerCase();
if (otype === 'object') {
if (ev.data.msg === 'initialize') {
i = ev.data.$i;
i18n = new I18n(ev.data.locale);
}
}
}
});