283 lines
6.6 KiB
TypeScript
Raw Normal View History

2017-07-13 15:56:14 +00:00
// pack:ignore
2017-07-14 02:58:21 +00:00
const CACHE = "v-1"
const RELOADS = new Map<string, Promise<Response>>()
const ETAGS = new Map<string, string>()
2017-07-14 23:53:08 +00:00
const CACHEREFRESH = new Map<string, Promise<void>>()
2017-07-19 05:39:09 +00:00
const EXCLUDECACHE = new Set<string>([
"/api/",
"/paypal/",
"/import/",
"chrome-extension"
])
2017-07-13 18:45:16 +00:00
2017-07-14 21:50:34 +00:00
self.addEventListener("install", (evt: InstallEvent) => {
2017-07-19 05:39:09 +00:00
console.log("service worker install")
2017-07-14 02:58:21 +00:00
2017-07-13 22:11:25 +00:00
evt.waitUntil(
(self as any).skipWaiting().then(() => {
return installCache()
})
)
2017-07-13 18:45:16 +00:00
})
self.addEventListener("activate", (evt: any) => {
2017-07-19 05:39:09 +00:00
console.log("service worker activate")
2017-07-14 02:58:21 +00:00
2017-07-14 23:32:06 +00:00
// Delete old cache
let cacheWhitelist = [CACHE]
let deleteOldCache = caches.keys().then(keyList => {
return Promise.all(keyList.map(key => {
if(cacheWhitelist.indexOf(key) === -1) {
return caches.delete(key)
}
}))
})
let immediateClaim = (self as any).clients.claim()
// Immediate claim
2017-07-13 22:11:25 +00:00
evt.waitUntil(
2017-07-14 23:32:06 +00:00
Promise.all([
deleteOldCache,
immediateClaim
])
2017-07-13 22:11:25 +00:00
)
2017-07-13 18:45:16 +00:00
})
2017-07-14 02:58:21 +00:00
// controlling service worker
self.addEventListener("message", (evt: any) => {
let message = JSON.parse(evt.data)
2017-07-19 04:32:31 +00:00
2017-07-14 02:58:21 +00:00
let url = message.url
let refresh = RELOADS.get(url)
let servedETag = ETAGS.get(url)
2017-07-19 04:32:31 +00:00
// If the user requests a sub-page we should prefetch the full page, too.
if(url.includes("/_/")) {
let fullPage = new Request(url.replace("/_/", "/"))
fetch(fullPage, {
credentials: "same-origin"
})
.then(response => {
// Save the new version of the resource in the cache
let cacheRefresh = caches.open(CACHE).then(cache => {
return cache.put(fullPage, response)
})
CACHEREFRESH.set(fullPage.url, cacheRefresh)
return cacheRefresh
})
}
2017-07-14 02:58:21 +00:00
if(!refresh || !servedETag) {
return
}
evt.waitUntil(
refresh.then((response: Response) => {
// If the fresh copy was used to serve the request instead of the cache,
2017-07-14 21:50:34 +00:00
// we don"t need to tell the client to do a refresh.
2017-07-14 02:58:21 +00:00
if(response.bodyUsed) {
return
}
let eTag = response.headers.get("ETag")
if(eTag === servedETag) {
return
}
ETAGS.set(url, eTag)
let message = {
type: "new content",
url
}
2017-07-14 23:53:08 +00:00
let cacheRefresh = CACHEREFRESH.get(url)
if(!cacheRefresh) {
2017-07-19 05:39:09 +00:00
console.log("forcing reload, cache refresh null")
2017-07-14 23:53:08 +00:00
return evt.source.postMessage(JSON.stringify(message))
}
return cacheRefresh.then(() => {
2017-07-19 05:39:09 +00:00
console.log("forcing reload after cache refresh")
2017-07-14 23:53:08 +00:00
evt.source.postMessage(JSON.stringify(message))
})
2017-07-14 02:58:21 +00:00
})
)
})
2017-07-14 21:50:34 +00:00
self.addEventListener("fetch", async (evt: FetchEvent) => {
2017-07-15 15:07:24 +00:00
let request = evt.request as Request
2017-07-13 22:11:25 +00:00
let isAuth = request.url.includes("/auth/") || request.url.includes("/logout")
2017-07-19 05:39:09 +00:00
let ignoreCache = false
2017-07-19 06:49:38 +00:00
// console.log("fetch:", request.url)
2017-07-19 05:39:09 +00:00
// Exclude certain URLs from being cached
for(let pattern of EXCLUDECACHE.keys()) {
if(request.url.includes(pattern)) {
ignoreCache = true
break
}
}
2017-07-13 18:45:16 +00:00
2017-07-13 22:11:25 +00:00
// Delete existing cache on authentication
if(isAuth) {
caches.delete(CACHE)
}
2017-07-13 18:45:16 +00:00
// Do not use cache in some cases
2017-07-14 21:50:34 +00:00
if(request.method !== "GET" || isAuth || ignoreCache) {
2017-07-13 18:45:16 +00:00
return evt.waitUntil(evt.respondWith(fetch(request)))
}
2017-07-13 22:11:25 +00:00
2017-07-19 06:45:41 +00:00
// Forced cache response?
if(request.headers.get("X-CacheOnly") === "true") {
2017-07-19 06:49:38 +00:00
// console.log("forced cache response")
2017-07-19 06:45:41 +00:00
return evt.waitUntil(fromCache(request))
}
2017-07-14 02:58:21 +00:00
let servedETag = undefined
2017-07-13 18:45:16 +00:00
// Start fetching the request
let refresh = fetch(request).then(response => {
2017-07-19 06:49:38 +00:00
// console.log(response)
2017-07-13 18:45:16 +00:00
let clone = response.clone()
// Save the new version of the resource in the cache
2017-07-14 23:53:08 +00:00
let cacheRefresh = caches.open(CACHE).then(cache => {
2017-07-13 22:11:25 +00:00
return cache.put(request, clone)
2017-07-13 18:45:16 +00:00
})
2017-07-14 23:53:08 +00:00
CACHEREFRESH.set(request.url, cacheRefresh)
2017-07-13 18:45:16 +00:00
return response
})
2017-07-14 02:58:21 +00:00
// Save in map
RELOADS.set(request.url, refresh)
2017-07-13 22:11:25 +00:00
// Forced reload
if(request.headers.get("X-Reload") === "true") {
2017-07-19 06:45:41 +00:00
return evt.waitUntil(evt.respondWith(refresh.then(response => {
2017-07-19 05:39:09 +00:00
servedETag = response.headers.get("ETag")
ETAGS.set(request.url, servedETag)
return response
2017-07-19 06:45:41 +00:00
})))
2017-07-13 22:11:25 +00:00
}
2017-07-13 18:45:16 +00:00
// Try to serve cache first and fall back to network response
2017-07-13 22:11:25 +00:00
let networkOrCache = fromCache(request).then(response => {
2017-07-19 06:49:38 +00:00
// console.log("served from cache:", request.url)
2017-07-14 02:58:21 +00:00
servedETag = response.headers.get("ETag")
ETAGS.set(request.url, servedETag)
2017-07-13 22:11:25 +00:00
return response
}).catch(error => {
// console.log("Cache MISS:", request.url)
2017-07-13 18:45:16 +00:00
return refresh
})
return evt.waitUntil(evt.respondWith(networkOrCache))
})
2017-07-14 21:50:34 +00:00
self.addEventListener("push", (evt: PushEvent) => {
2017-07-14 23:32:06 +00:00
var payload = evt.data ? evt.data.json() : {}
2017-07-14 21:50:34 +00:00
evt.waitUntil(
2017-07-14 23:32:06 +00:00
(self as any).registration.showNotification(payload.title, {
body: payload.message,
icon: payload.icon,
2017-07-15 00:32:54 +00:00
image: payload.image,
data: payload.link
2017-07-14 21:50:34 +00:00
})
)
})
self.addEventListener("pushsubscriptionchange", (evt: any) => {
2017-07-19 01:22:50 +00:00
evt.waitUntil((self as any).registration.pushManager.subscribe(evt.oldSubscription.options)
.then(async subscription => {
2017-07-19 05:39:09 +00:00
console.log("send subscription to server...")
2017-07-19 01:22:50 +00:00
let rawKey = subscription.getKey("p256dh")
let key = rawKey ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawKey))) : ""
let rawSecret = subscription.getKey("auth")
let secret = rawSecret ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawSecret))) : ""
let endpoint = subscription.endpoint
let pushSubscription = {
endpoint,
p256dh: key,
auth: secret,
platform: navigator.platform,
userAgent: navigator.userAgent,
screen: {
width: window.screen.width,
height: window.screen.height
}
}
let user = await fetch("/api/me").then(response => response.json())
return fetch("/api/pushsubscriptions/" + user.id + "/add", {
method: "POST",
credentials: "same-origin",
body: JSON.stringify(pushSubscription)
})
}))
2017-07-14 21:50:34 +00:00
})
self.addEventListener("notificationclick", (evt: NotificationEvent) => {
2017-07-15 00:32:54 +00:00
let notification = evt.notification
notification.close()
2017-07-14 21:50:34 +00:00
evt.waitUntil(
(self as any).clients.matchAll().then(function(clientList) {
2017-07-15 00:32:54 +00:00
// If we have a link, use that link to open a new window.
let url = notification.data
if(url) {
return (self as any).clients.openWindow(url)
}
2017-07-14 21:50:34 +00:00
// If there is at least one client, focus it.
if(clientList.length > 0) {
return clientList[0].focus()
}
// Otherwise open a new window
return (self as any).clients.openWindow("https://notify.moe")
})
)
})
2017-07-13 18:45:16 +00:00
function installCache() {
return caches.open(CACHE).then(cache => {
return cache.addAll([
"./",
"./scripts",
"https://fonts.gstatic.com/s/ubuntu/v10/2Q-AW1e_taO6pHwMXcXW5w.ttf"
])
})
}
function fromCache(request) {
return caches.open(CACHE).then(cache => {
return cache.match(request).then(matching => {
if(matching) {
2017-07-13 22:11:25 +00:00
// console.log("Cache HIT:", request.url)
2017-07-13 18:45:16 +00:00
return Promise.resolve(matching)
}
return Promise.reject("no-match")
})
})
}