488 lines
13 KiB
TypeScript
Raw Normal View History

2017-07-13 15:56:14 +00:00
// pack:ignore
2017-12-01 13:30:38 +00:00
// This is the service worker for notify.moe.
// When installed, it will intercept all requests made by the browser
2017-12-03 20:33:03 +00:00
// and return a cache-first response.
// request request
// Browser -------> Service Worker ------> notify.moe Server
// <-------
// response (cache)
// <------
// response (network)
// <-------
2017-12-04 07:48:08 +00:00
// response (network)
2017-12-03 20:33:03 +00:00
//
// -> Diff cache with network response.
// By always returning cache first,
2017-12-01 13:30:38 +00:00
// we avoid latency problems on high latency connections like mobile
// networks. While the cache is being served, we start a real network
// request to the server to see if the resource changed. We compare the
// E-Tag of the cached and latest version of the resource. If the E-Tag
// of the current document changed, we send a message to the client
// that will cause the client to reload (diff) the page. It is not a real
// page reload as we will only calculate a DOM diff on the contents.
// If the style or script resources changed after being served, we need
// to force a real page reload.
2017-12-01 14:38:44 +00:00
// Promises
2017-07-14 23:53:08 +00:00
const CACHEREFRESH = new Map<string, Promise<void>>()
2017-12-01 14:38:44 +00:00
// E-Tags that we served for a given URL
const ETAGS = new Map<string, string>()
// When these patterns are matched for the request URL, we exclude them from being
// served cache-first and instead serve them via a network request.
// Note that the service worker URL is automatically excluded from fetch events
// and therefore doesn't need to be added here.
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-12-01 18:37:19 +00:00
// MyServiceWorker is the process that controls all the tabs in a browser.
2017-10-19 02:36:05 +00:00
class MyServiceWorker {
cache: MyCache
2017-12-04 08:45:56 +00:00
reloads: Map<string, Promise<Response>>
2017-10-19 02:36:05 +00:00
constructor() {
2017-11-16 14:15:35 +00:00
this.cache = new MyCache("v-5")
2017-12-04 08:45:56 +00:00
this.reloads = new Map<string, Promise<Response>>()
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-12-01 18:37:19 +00:00
return self.skipWaiting().then(() => {
2017-10-19 02:36:05 +00:00
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
2017-12-01 18:13:07 +00:00
let immediateClaim = self.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-12-04 07:48:08 +00:00
// onRequest intercepts all browser requests
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") {
2017-12-04 08:45:56 +00:00
return evt.respondWith(this.fromNetwork(request))
2017-10-19 02:36:05 +00:00
}
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)) {
2017-12-04 08:45:56 +00:00
return evt.respondWith(this.fromNetwork(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
// 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-12-04 09:25:22 +00:00
// Save the served E-Tag when onResponse is called
let servedETag = undefined
2017-12-04 10:19:21 +00:00
let onResponse = (response: Response | null) => {
if(response) {
servedETag = response.headers.get("ETag")
ETAGS.set(request.url, servedETag)
}
2017-12-04 09:25:22 +00:00
return response
}
let saveResponseInCache = response => {
2017-10-19 02:36:05 +00:00
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-12-01 16:43:34 +00:00
let cacheRefresh = this.cache.store(request, clone).catch(err => {
console.error(err)
// TODO: Tell client that the quota is exceeded (disk full).
})
2017-11-09 17:37:13 +00:00
2017-10-19 02:36:05 +00:00
CACHEREFRESH.set(request.url, cacheRefresh)
return response
2017-12-04 09:25:22 +00:00
}
2017-11-09 17:37:13 +00:00
2017-12-04 09:25:22 +00:00
// Start fetching the request
let network =
fetch(request)
.then(saveResponseInCache)
.catch(error => {
console.log("Fetch error:", error)
throw error
})
2017-07-19 04:32:31 +00:00
2017-12-04 09:25:22 +00:00
// Save in map
this.reloads.set(request.url, network)
2017-10-19 02:36:05 +00:00
if(request.headers.get("X-Reload") === "true") {
2017-12-04 09:25:22 +00:00
return evt.respondWith(network)
2017-10-19 02:36:05 +00:00
}
2017-11-09 17:37:13 +00:00
2017-12-04 08:45:56 +00:00
// Scripts and styles are server pushed on the initial response
2017-12-04 09:25:22 +00:00
// so we can use a network-first response without an additional round-trip.
// This causes the browser to always load the most recent scripts and styles.
2017-12-04 08:45:56 +00:00
if(request.url.endsWith("/styles") || request.url.endsWith("/scripts")) {
2017-12-04 09:25:22 +00:00
return evt.respondWith(this.networkFirst(request, network, onResponse))
2017-12-04 08:45:56 +00:00
}
2017-12-04 09:25:22 +00:00
return evt.respondWith(this.cacheFirst(request, network, onResponse))
2017-07-19 04:32:31 +00:00
}
2017-12-04 09:25:22 +00:00
// onMessage is called when the service worker receives a message from a client (browser tab).
2017-12-01 18:13:07 +00:00
async onMessage(evt: ServiceWorkerMessageEvent) {
2017-10-19 02:36:05 +00:00
let message = JSON.parse(evt.data)
2017-12-01 18:13:07 +00:00
let clientId = (evt.source as any).id
let client = await MyClient.get(clientId)
2017-10-20 00:43:02 +00:00
2017-12-01 18:13:07 +00:00
client.onMessage(message)
2017-10-20 00:43:02 +00:00
}
2017-12-04 09:25:22 +00:00
// onPush is called on push events and requires the payload to contain JSON information about the notification.
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-12-01 18:37:19 +00:00
return self.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) {
2017-12-01 18:37:19 +00:00
return self.registration.pushManager.subscribe(evt.oldSubscription.options)
2017-10-19 02:36:05 +00:00
.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
let user = await fetch("/api/me", {
credentials: "same-origin"
}).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-12-04 09:25:22 +00:00
// onNotificationClick is called when the user clicks on a notification.
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-12-01 18:13:07 +00:00
return self.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) {
2017-12-01 18:13:07 +00:00
return self.clients.openWindow(url)
2017-07-15 00:32:54 +00:00
}
2017-07-14 21:50:34 +00:00
// If there is at least one client, focus it.
if(clientList.length > 0) {
2017-12-01 18:13:07 +00:00
return (clientList[0] as WindowClient).focus()
2017-07-14 21:50:34 +00:00
}
// Otherwise open a new window
2017-12-01 18:13:07 +00:00
return self.clients.openWindow("https://notify.moe")
2017-10-19 02:36:05 +00:00
})
}
2017-12-04 09:25:22 +00:00
// installCache is called when the service worker is installed for the first time.
2017-10-19 02:36:05 +00:00
installCache() {
2017-12-04 09:25:22 +00:00
return caches.open(this.cache.version).then(cache => {
return cache.addAll([
"./scripts",
"./styles",
])
})
}
// Serve network first.
// Fall back to cache.
async networkFirst(request: Request, network: Promise<Response>, onResponse: (r: Response) => Response): Promise<Response> {
2017-12-04 10:19:21 +00:00
let response: Response | null
2017-12-04 09:25:22 +00:00
try {
response = await network
console.log("Network HIT:", request.url)
} catch(error) {
console.log("Network MISS:", request.url, error)
2017-12-04 10:19:21 +00:00
try {
response = await this.fromCache(request)
} catch(error) {
console.error(error)
}
2017-12-04 09:25:22 +00:00
}
return onResponse(response)
}
// Serve cache first.
// Fall back to network.
async cacheFirst(request: Request, network: Promise<Response>, onResponse: (r: Response) => Response): Promise<Response> {
2017-12-04 10:19:21 +00:00
let response: Response | null
2017-12-04 09:25:22 +00:00
try {
response = await this.fromCache(request)
console.log("Cache HIT:", request.url)
} catch(error) {
console.log("Cache MISS:", request.url, error)
2017-12-04 10:19:21 +00:00
try {
response = await network
} catch(error) {
console.error(error)
}
2017-12-04 09:25:22 +00:00
}
return onResponse(response)
2017-10-19 02:36:05 +00:00
}
2017-11-09 17:37:13 +00:00
2017-12-04 09:25:22 +00:00
fromCache(request): Promise<Response> {
2017-10-19 02:36:05 +00:00
return caches.open(this.cache.version).then(cache => {
return cache.match(request).then(matching => {
if(matching) {
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-12-04 08:45:56 +00:00
2017-12-04 09:25:22 +00:00
fromNetwork(request): Promise<Response> {
2017-12-04 08:45:56 +00:00
return fetch(request)
}
2017-07-13 18:45:16 +00:00
}
2017-10-19 02:36:05 +00:00
2017-12-01 18:37:19 +00:00
// MyCache is the cache used by the service worker.
class MyCache {
version: string
constructor(version: string) {
this.version = version
}
store(request: RequestInfo, response: Response) {
return caches.open(this.version).then(cache => {
// This can fail if the disk space quota has been exceeded.
return cache.put(request, response)
})
}
}
// MyClient represents a single tab in the browser.
class MyClient {
client: ServiceWorkerClient
constructor(client: ServiceWorkerClient) {
this.client = client
}
onMessage(message: any) {
switch(message.type) {
case "loaded":
this.onDOMContentLoaded(message.url)
break
}
}
postMessage(message: object) {
this.client.postMessage(JSON.stringify(message))
}
// onDOMContentLoaded is called when the client sent this service worker
// a message that the page has been loaded.
onDOMContentLoaded(url: string) {
2017-12-04 08:45:56 +00:00
let refresh = serviceWorker.reloads.get(url)
2017-12-01 18:37:19 +00:00
let servedETag = ETAGS.get(url)
// If the user requests a sub-page we should prefetch the full page, too.
if(url.includes("/_/") && !url.includes("/_/search/")) {
var prefetch = true
for(let pattern of EXCLUDECACHE.keys()) {
if(url.includes(pattern)) {
prefetch = false
break
}
}
if(prefetch) {
this.prefetchFullPage(url)
}
}
if(!refresh || !servedETag) {
return Promise.resolve()
}
return refresh.then(async (response: Response) => {
// 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.
if(response.bodyUsed) {
return
}
// Get the ETag of the cached response we sent to the client earlier.
let eTag = response.headers.get("ETag")
// Update ETag
ETAGS.set(url, eTag)
// If the ETag changed, we need to do a reload.
if(eTag !== servedETag) {
return this.reloadContent(url)
}
// Do nothing
return Promise.resolve()
})
}
prefetchFullPage(url: string) {
let fullPage = new Request(url.replace("/_/", "/"))
let fullPageRefresh = fetch(fullPage, {
credentials: "same-origin"
}).then(response => {
// Save the new version of the resource in the cache
let cacheRefresh = caches.open(serviceWorker.cache.version).then(cache => {
return cache.put(fullPage, response)
})
CACHEREFRESH.set(fullPage.url, cacheRefresh)
return response
})
// Save in map
2017-12-04 08:45:56 +00:00
serviceWorker.reloads.set(fullPage.url, fullPageRefresh)
2017-12-01 18:37:19 +00:00
}
async reloadContent(url: string) {
let cacheRefresh = CACHEREFRESH.get(url)
if(cacheRefresh) {
await cacheRefresh
}
return this.postMessage({
type: "new content",
url
})
}
2017-12-04 10:19:21 +00:00
// async reloadPage(url: string) {
// let networkFetch = serviceWorker.reloads.get(url.replace("/_/", "/"))
2017-12-01 18:37:19 +00:00
2017-12-04 10:19:21 +00:00
// if(networkFetch) {
// await networkFetch
// }
2017-12-01 18:37:19 +00:00
2017-12-04 10:19:21 +00:00
// return this.postMessage({
// type: "reload page",
// url
// })
// }
2017-12-01 18:37:19 +00:00
reloadStyles() {
return this.postMessage({
type: "reload styles"
})
}
// Map of clients
static idToClient = new Map<string, MyClient>()
static async get(id: string): Promise<MyClient> {
let client = MyClient.idToClient.get(id)
if(!client) {
client = new MyClient(await self.clients.get(id))
MyClient.idToClient.set(id, client)
}
return client
}
}
2017-10-19 02:36:05 +00:00
const serviceWorker = new MyServiceWorker()