pinafore/src/service-worker.js

253 lines
7.1 KiB
JavaScript
Raw Normal View History

import {
assets as __assets__,
shell as __shell__,
routes as __routes__
} from '../__sapper__/service-worker.js'
import {
get,
post
} from './routes/_utils/ajax'
const timestamp = process.env.SAPPER_TIMESTAMP
const ASSETS = `assets_${timestamp}`
const WEBPACK_ASSETS = `webpack_assets_${timestamp}`
2018-01-06 23:51:25 +00:00
// `static` is an array of everything in the `static` directory
const assets = __assets__
.map(file => file.startsWith('/') ? file : `/${file}`)
2018-03-20 03:24:33 +00:00
.filter(filename => !filename.startsWith('/apple-icon'))
.filter(filename => !filename.endsWith('.map'))
.filter(filename => filename !== '/robots.txt')
// `shell` is an array of all the files generated by webpack
// also contains '/index.html' for some reason
const webpackAssets = __shell__
.filter(filename => !filename.endsWith('.map')) // don't bother with sourcemaps
2018-01-06 23:51:25 +00:00
// `routes` is an array of `{ pattern: RegExp }` objects that
// match the pages in your src
2018-01-14 22:54:26 +00:00
const routes = __routes__
2018-01-06 23:51:25 +00:00
self.addEventListener('install', event => {
2018-03-23 05:30:48 +00:00
event.waitUntil((async () => {
await Promise.all([
caches.open(WEBPACK_ASSETS).then(cache => cache.addAll(webpackAssets)),
caches.open(ASSETS).then(cache => cache.addAll(assets))
])
})())
2018-01-14 22:54:26 +00:00
})
2018-01-06 23:51:25 +00:00
self.addEventListener('activate', event => {
2018-03-23 05:30:48 +00:00
event.waitUntil((async () => {
let keys = await caches.keys()
// delete old asset/ondemand caches
for (let key of keys) {
if (key !== ASSETS &&
!key.startsWith('webpack_assets_')) {
await caches.delete(key)
2018-01-14 22:54:26 +00:00
}
}
// for webpack static, keep the two latest builds because we may need
// them when the service worker has installed but the page has not
// yet reloaded (e.g. when it gives the toast saying "please reload"
// but then you don't refresh and instead load an async chunk)
let webpackKeysToDelete = keys
.filter(key => key.startsWith('webpack_assets_'))
.sort((a, b) => {
let aTimestamp = parseInt(a.substring(15), 10)
let bTimestamp = parseInt(b.substring(15), 10)
return bTimestamp < aTimestamp ? -1 : 1
})
.slice(2)
for (let key of webpackKeysToDelete) {
await caches.delete(key)
}
await self.clients.claim()
})())
2018-01-14 22:54:26 +00:00
})
2018-01-06 23:51:25 +00:00
self.addEventListener('fetch', event => {
2018-01-15 01:13:42 +00:00
const req = event.request
const url = new URL(req.url)
2018-01-06 23:51:25 +00:00
2018-01-14 22:54:26 +00:00
// don't try to handle e.g. data: URIs
if (!url.protocol.startsWith('http')) {
2018-02-09 06:29:29 +00:00
return
2018-01-14 22:54:26 +00:00
}
2018-01-06 23:51:25 +00:00
2018-03-23 05:30:48 +00:00
event.respondWith((async () => {
let sameOrigin = url.origin === self.origin
2018-01-06 23:51:25 +00:00
2018-04-05 05:52:04 +00:00
if (sameOrigin) {
// always serve webpack-generated resources and
// static from the cache if possible
2018-04-05 05:52:04 +00:00
let response = await caches.match(req)
if (response) {
return response
}
// for routes, serve the /service-worker-index.html file from the most recent
// static cache
2018-04-05 05:52:04 +00:00
if (routes.find(route => route.pattern.test(url.pathname))) {
let response = await caches.match('/service-worker-index.html')
if (response) {
return response
}
2018-04-05 05:52:04 +00:00
}
}
2018-01-06 23:51:25 +00:00
// for everything else, go network-only
return fetch(req)
})())
2018-01-14 22:54:26 +00:00
})
self.addEventListener('push', event => {
event.waitUntil((async () => {
const data = event.data.json()
const { origin } = new URL(data.icon)
try {
const notification = await get(`${origin}/api/v1/notifications/${data.notification_id}`, {
'Authorization': `Bearer ${data.access_token}`
}, { timeout: 2000 })
await showRichNotification(data, notification)
} catch (e) {
await showSimpleNotification(data)
}
})())
})
async function showSimpleNotification (data) {
await self.registration.showNotification(data.title, {
icon: data.icon,
body: data.body
})
}
async function showRichNotification (data, notification) {
const { icon, body } = data
const tag = notification.id
const { origin } = self.location
const badge = '/icon-push-badge.png'
switch (notification.type) {
case 'follow': {
await self.registration.showNotification(data.title, {
badge,
icon,
body,
tag,
data: {
url: `${origin}/accounts/${notification.account.id}`
}
})
break
}
case 'reblog':
case 'favourite':
case 'poll':
await self.registration.showNotification(data.title, {
badge,
icon,
body,
tag,
data: {
url: `${origin}/statuses/${notification.status.id}`
}
})
break
case 'mention':
const isPublic = ['public', 'unlisted'].includes(notification.status.visibility)
const actions = [
isPublic && {
action: 'reblog',
icon: '/icon-push-fa-retweet.png', // generated manually from font-awesome-svg
title: 'Boost'
},
{
action: 'favourite',
icon: '/icon-push-fa-star.png', // generated manually from font-awesome-svg
title: 'Favorite'
}
].filter(Boolean)
await self.registration.showNotification(data.title, {
badge,
icon,
body,
tag,
data: {
instance: new URL(data.icon).origin,
status_id: notification.status.id,
access_token: data.access_token,
url: `${origin}/statuses/${notification.status.id}`
},
actions
})
break
}
}
const cloneNotification = notification => {
const clone = {}
for (let k in notification) {
// deliberately not doing a hasOwnProperty check, but skipping
// functions and null props like onclick and onshow and showTrigger
if (typeof notification[k] !== 'function' && notification[k] !== null) {
clone[k] = notification[k]
}
}
return clone
}
const updateNotificationWithoutAction = (notification, action) => {
const newNotification = cloneNotification(notification)
newNotification.actions = newNotification.actions.filter(item => item.action !== action)
return self.registration.showNotification(newNotification.title, newNotification)
}
self.addEventListener('notificationclick', event => {
event.waitUntil((async () => {
switch (event.action) {
case 'reblog': {
const url = `${event.notification.data.instance}/api/v1/statuses/${event.notification.data.status_id}/reblog`
await post(url, null, {
'Authorization': `Bearer ${event.notification.data.access_token}`
})
await updateNotificationWithoutAction(event.notification, 'reblog')
break
}
case 'favourite': {
const url = `${event.notification.data.instance}/api/v1/statuses/${event.notification.data.status_id}/favourite`
await post(url, null, {
'Authorization': `Bearer ${event.notification.data.access_token}`
})
await updateNotificationWithoutAction(event.notification, 'favourite')
break
}
default: {
await self.clients.openWindow(event.notification.data.url)
await event.notification.close()
break
}
}
})())
})
self.addEventListener('message', (event) => {
switch (event.data) {
case 'skip-waiting':
self.skipWaiting()
break
}
})