353 lines
9.1 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 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>([
2017-10-17 09:48:20 +00:00
// API requests
2017-07-19 05:39:09 +00:00
"/api/",
2017-10-17 09:48:20 +00:00
// PayPal stuff
2017-07-19 05:39:09 +00:00
"/paypal/",
2017-10-17 09:48:20 +00:00
// List imports
2017-07-19 05:39:09 +00:00
"/import/",
2017-10-17 09:48:20 +00:00
// Infinite scrolling
"/from/",
// Chrome extension
2017-10-19 02:36:05 +00:00
"chrome-extension",
2017-07-13 18:45:16 +00:00
2017-10-19 02:36:05 +00:00
// Authorization paths /auth/ and /logout are not listed here because they are handled in a special way.
])
2017-07-14 02:58:21 +00:00
2017-10-19 02:36:05 +00:00
class MyCache {
version: string
2017-07-13 18:45:16 +00:00
2017-10-19 02:36:05 +00:00
constructor(version: string) {
this.version = version
}
2017-07-14 02:58:21 +00:00
2017-10-19 02:36:05 +00:00
store(request: RequestInfo, response: Response) {
return caches.open(this.version).then(cache => {
return cache.put(request, response)
})
}
}
2017-07-14 23:32:06 +00:00
2017-10-19 02:36:05 +00:00
class MyServiceWorker {
cache: MyCache
constructor() {
2017-11-16 14:15:35 +00:00
this.cache = new MyCache("v-5")
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
self.addEventListener("install", (evt: InstallEvent) => evt.waitUntil(this.onInstall(evt)))
self.addEventListener("activate", (evt: any) => evt.waitUntil(this.onActivate(evt)))
self.addEventListener("fetch", (evt: FetchEvent) => evt.waitUntil(this.onRequest(evt)))
self.addEventListener("message", (evt: any) => evt.waitUntil(this.onMessage(evt)))
self.addEventListener("push", (evt: PushEvent) => evt.waitUntil(this.onPush(evt)))
self.addEventListener("pushsubscriptionchange", (evt: any) => evt.waitUntil(this.onPushSubscriptionChange(evt)))
self.addEventListener("notificationclick", (evt: NotificationEvent) => evt.waitUntil(this.onNotificationClick(evt)))
}
2017-07-14 23:32:06 +00:00
2017-10-19 02:36:05 +00:00
onInstall(evt: InstallEvent) {
console.log("service worker install")
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
return (self as any).skipWaiting().then(() => {
return this.installCache()
})
}
2017-07-14 23:32:06 +00:00
2017-10-19 02:36:05 +00:00
onActivate(evt: any) {
console.log("service worker activate")
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
// Only keep current version of the cache and delete old caches
let cacheWhitelist = [this.cache.version]
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
let deleteOldCache = caches.keys().then(keyList => {
return Promise.all(keyList.map(key => {
if(cacheWhitelist.indexOf(key) === -1) {
return caches.delete(key)
}
}))
})
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
// Immediate claim helps us gain control over a new client immediately
let immediateClaim = (self as any).clients.claim()
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
return Promise.all([
2017-07-14 23:32:06 +00:00
deleteOldCache,
immediateClaim
])
2017-10-19 02:36:05 +00:00
}
2017-07-13 18:45:16 +00:00
2017-10-19 02:36:05 +00:00
onRequest(evt: FetchEvent) {
let request = evt.request as Request
2017-07-19 04:32:31 +00:00
2017-10-19 02:36:05 +00:00
// If it's not a GET request, fetch it normally
if(request.method !== "GET") {
return evt.respondWith(fetch(request))
}
2017-07-19 04:32:31 +00:00
2017-10-19 02:36:05 +00:00
// Clear cache on authentication and fetch it normally
if(request.url.includes("/auth/") || request.url.includes("/logout")) {
2017-10-28 01:53:12 +00:00
return evt.respondWith(caches.delete(this.cache.version).then(() => fetch(request)))
2017-10-19 02:36:05 +00:00
}
// Exclude certain URLs from being cached
for(let pattern of EXCLUDECACHE.keys()) {
if(request.url.includes(pattern)) {
return evt.respondWith(fetch(request))
}
}
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
// If the request included the header "X-CacheOnly", return a cache-only response.
// This is used in reloads to avoid generating a 2nd request after a cache refresh.
if(request.headers.get("X-CacheOnly") === "true") {
2017-10-28 01:53:12 +00:00
return evt.respondWith(this.fromCache(request))
2017-10-19 02:36:05 +00:00
}
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
// Start fetching the request
let refresh = fetch(request).then(response => {
let clone = response.clone()
2017-11-09 17:37:13 +00:00
2017-07-19 04:32:31 +00:00
// Save the new version of the resource in the cache
2017-10-19 02:36:05 +00:00
let cacheRefresh = this.cache.store(request, clone)
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
CACHEREFRESH.set(request.url, cacheRefresh)
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
return response
})
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
// Save in map
RELOADS.set(request.url, refresh)
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
// Forced reload
let servedETag = undefined
2017-07-19 04:32:31 +00:00
2017-10-19 02:36:05 +00:00
let onResponse = response => {
servedETag = response.headers.get("ETag")
ETAGS.set(request.url, servedETag)
return response
}
if(request.headers.get("X-Reload") === "true") {
return evt.respondWith(refresh.then(onResponse))
}
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
// Try to serve cache first and fall back to network response
let networkOrCache = this.fromCache(request).then(onResponse).catch(error => {
// console.log("Cache MISS:", request.url)
return refresh
2017-07-19 04:32:31 +00:00
})
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
return evt.respondWith(networkOrCache)
2017-07-19 04:32:31 +00:00
}
2017-10-19 02:36:05 +00:00
onMessage(evt: any) {
let message = JSON.parse(evt.data)
2017-10-20 00:43:02 +00:00
switch(message.type) {
case "loaded":
this.onDOMContentLoaded(evt, message.url)
break
}
}
// onDOMContentLoaded is called when the client sent this service worker
// a message that the page has been loaded.
onDOMContentLoaded(evt: any, url: string) {
2017-10-19 02:36:05 +00:00
let refresh = RELOADS.get(url)
let servedETag = ETAGS.get(url)
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
// If the user requests a sub-page we should prefetch the full page, too.
2017-11-11 15:09:37 +00:00
if(url.includes("/_/") && !url.includes("/_/search/")) {
2017-11-30 02:27:38 +00:00
var prefetch = true
for(let pattern of EXCLUDECACHE.keys()) {
if(url.includes(pattern)) {
prefetch = false
break
}
}
if(prefetch) {
this.prefetchFullPage(url)
}
2017-10-19 02:36:05 +00:00
}
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
if(!refresh || !servedETag) {
return Promise.resolve()
}
return refresh.then((response: Response) => {
2017-10-20 00:43:02 +00:00
// When the actual network request was used by the client, response.bodyUsed is set.
// In that case the client is already up to date and we don"t need to tell the client to do a refresh.
2017-07-14 02:58:21 +00:00
if(response.bodyUsed) {
return
}
2017-11-09 17:37:13 +00:00
2017-10-20 00:43:02 +00:00
// Get the ETag of the cached response we sent to the client earlier.
2017-07-14 02:58:21 +00:00
let eTag = response.headers.get("ETag")
2017-10-19 02:36:05 +00:00
// Update ETag
2017-07-14 02:58:21 +00:00
ETAGS.set(url, eTag)
2017-10-19 02:36:05 +00:00
// If the ETag changed, we need to do a reload.
if(eTag !== servedETag) {
return this.forceClientReloadContent(url, evt.source)
}
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
// Do nothing
return Promise.resolve()
2017-07-14 02:58:21 +00:00
})
2017-07-13 18:45:16 +00:00
}
2017-07-13 22:11:25 +00:00
2017-10-20 00:43:02 +00:00
prefetchFullPage(url: string) {
let fullPage = new Request(url.replace("/_/", "/"))
2017-11-09 17:37:13 +00:00
2017-10-20 00:43:02 +00:00
let fullPageRefresh = fetch(fullPage, {
2017-11-25 13:11:55 +00:00
credentials: "same-origin"
2017-10-20 00:43:02 +00:00
}).then(response => {
// Save the new version of the resource in the cache
let cacheRefresh = caches.open(this.cache.version).then(cache => {
return cache.put(fullPage, response)
})
CACHEREFRESH.set(fullPage.url, cacheRefresh)
return response
})
// Save in map
RELOADS.set(fullPage.url, fullPageRefresh)
}
2017-10-19 02:36:05 +00:00
onPush(evt: PushEvent) {
var payload = evt.data ? evt.data.json() : {}
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
return (self as any).registration.showNotification(payload.title, {
2017-07-14 23:32:06 +00:00
body: payload.message,
icon: payload.icon,
2017-07-15 00:32:54 +00:00
image: payload.image,
2017-07-19 17:13:57 +00:00
data: payload.link,
2017-10-19 02:36:05 +00:00
badge: "https://notify.moe/brand/64.png"
2017-07-14 21:50:34 +00:00
})
2017-10-19 02:36:05 +00:00
}
2017-07-19 01:22:50 +00:00
2017-10-19 02:36:05 +00:00
onPushSubscriptionChange(evt: any) {
return (self as any).registration.pushManager.subscribe(evt.oldSubscription.options)
.then(async subscription => {
console.log("send subscription to server...")
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
let rawKey = subscription.getKey("p256dh")
let key = rawKey ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawKey))) : ""
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
let rawSecret = subscription.getKey("auth")
let secret = rawSecret ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawSecret))) : ""
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
let endpoint = subscription.endpoint
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
let pushSubscription = {
endpoint,
p256dh: key,
auth: secret,
platform: navigator.platform,
userAgent: navigator.userAgent,
screen: {
width: window.screen.width,
height: window.screen.height
}
}
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
let user = await fetch("/api/me").then(response => response.json())
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
return fetch("/api/pushsubscriptions/" + user.id + "/add", {
method: "POST",
credentials: "same-origin",
body: JSON.stringify(pushSubscription)
})
2017-07-19 01:22:50 +00:00
})
2017-10-19 02:36:05 +00:00
}
2017-07-14 21:50:34 +00:00
2017-10-19 02:36:05 +00:00
onNotificationClick(evt: NotificationEvent) {
let notification = evt.notification
notification.close()
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
return (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-10-19 02:36:05 +00:00
}
2017-07-13 18:45:16 +00:00
2017-10-19 02:36:05 +00:00
forceClientReloadContent(url: string, eventSource: any) {
let message = {
type: "new content",
url
}
this.postMessageAfterPromise(message, CACHEREFRESH.get(url), eventSource)
}
forceClientReloadPage(url: string, eventSource: any) {
let message = {
type: "reload page",
url
}
2017-07-13 18:45:16 +00:00
2017-10-19 02:36:05 +00:00
this.postMessageAfterPromise(message, RELOADS.get(url.replace("/_/", "/")), eventSource)
}
postMessageAfterPromise(message: any, promise: Promise<any>, eventSource: any) {
if(!promise) {
console.log("forcing reload, cache refresh null")
return eventSource.postMessage(JSON.stringify(message))
}
return promise.then(() => {
console.log("forcing reload after cache refresh")
eventSource.postMessage(JSON.stringify(message))
})
}
installCache() {
2017-10-26 02:01:26 +00:00
// TODO: Implement a solution that caches resources with credentials: "same-origin"
return Promise.resolve()
2017-11-09 17:37:13 +00:00
2017-10-26 02:01:26 +00:00
// return caches.open(this.cache.version).then(cache => {
// return cache.addAll([
// "./",
// "./scripts",
// "https://fonts.gstatic.com/s/ubuntu/v11/4iCs6KVjbNBYlgoKfw7z.ttf"
// ])
// })
2017-10-19 02:36:05 +00:00
}
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
fromCache(request) {
return caches.open(this.cache.version).then(cache => {
return cache.match(request).then(matching => {
if(matching) {
// console.log("Cache HIT:", request.url)
return Promise.resolve(matching)
}
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
return Promise.reject("no-match")
})
})
}
2017-07-13 18:45:16 +00:00
}
2017-10-19 02:36:05 +00:00
const serviceWorker = new MyServiceWorker()