-
Notifications
You must be signed in to change notification settings - Fork 41
/
sw.js
684 lines (423 loc) · 15.2 KB
/
sw.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
importScripts( "js/libs/localforage.min.js" );
//remember to increment the version # when you update the service worker
const version = "1.00",
preCache = "PRECACHE-" + version,
doc_fallback = "offline.html",
cacheList = [ doc_fallback ],
dashboardDocs = [],
image_fallback = "img/offline.png",
dynamicCache = "DYNAMIC_CACHE" + version,
noCache = [],
DEFAULT_MAX_TIME = 10 * 60 * 1000, //10 minute for testing
SINGLE_DAY = 24 * 60 * 60 * 1000, //1 day for testing
NO_CACHE = /no-cache|no-store|must-revalidate/,
mime_types = {
"application/json": "json",
"video/mp4": "blob",
"image/jpg": "blob",
"image/png": "blob",
"image/gif": "blob",
"application/octet-stream": "blob",
"mp4": "video/mp4",
"jpg": "image/jpg",
"png": "image/png",
"gif": "image/gif"
},
LAST_ASSET_CHECK = "last-asset-check",
LAST_DYNAMIC_CHECK = "last-dynamic-check",
LAST_PRECACHE_CHECK = "last-precache-check",
UPDATE_DYNAMIC = "update-dynamic";
const success = [ "background: green", "color: white", "display: block", "text-align: center" ].join( ";" );
let requestLog = [];
localforage.setItem( "version", version );
/*
create a list (array) of urls to pre-cache for your application
*/
/* Service Worker Event Handlers */
self.addEventListener( "install", function ( event ) {
event.waitUntil( updatePreCache() );
} );
self.addEventListener( "activate", function ( event ) {
event.waitUntil(
//wholesale purge of previous version caches
caches.keys()
.then( cacheNames => {
cacheNames.forEach( value => {
if ( !value.includes( version ) ) {
caches.delete( value );
}
} );
return;
} )
);
} );
self.addEventListener( "fetch", function ( event ) {
event.respondWith(
handleRequest( event )
.catch( err => {
//assume offline as everything else should be handled
return caches.match( doc_fallback, {
ignoreSearch: true
} );
} )
);
} );
self.addEventListener( "message", event => {
console.log( event );
switch ( event.data.event ) {
case UPDATE_DYNAMIC:
cacheCoreAssets();
break;
//case UPDATE_DASHBOARD:
// updateDashboard();
// break;
// case OFFLINE_MSG_KEY:
// toggleOffline( event.data.state );
// break;
default:
console.log( "unhandled event" );
break;
}
} );
function handleRequest( event ) {
if ( event.request.method.toLowerCase() !== "get" ) {
return fetch( event.request );
} else {
let isVideo = isVideoRequest( event.request.url );
if ( event.request.headers.get( "range" ) ) {
if ( isVideo ) {
return fetchMediaAndCache( event.request.url )
.then( response => {
return handleRangeRequest( event.request, response );
} );
} else {
return cacheFirstNetwork( event )
.then( response => {
return handleRangeRequest( event.request, response );
} );
}
} else {
if ( isVideo || isImageRequest( event.request.url ) ) {
return fetchMediaAndCache( event.request.url );
} else {
//normal requests
return handleNonMedia( event );
}
}
}
}
function updatePreCache() {
return updateCachedAssets( preCache );
//.then(() => {
// return updateCachedAssets(dynamicCache);
//});
}
function fetchHead( url, cache ) {
return cache.match( url, {
ignoreSearch: true
} )
.then( response => {
if ( response ) {
return fetch( url, {
method: "HEAD"
} )
.then( function ( response ) {
if ( !response.ok ) {
return false;
}
let lastModified = response.headers.get( "last-modified" );
if ( lastModified ) {
return cache.match( url, {
ignoreSearch: true
} )
.then( cachedResponse => {
if ( cachedResponse ) {
let cachedModified = cachedResponse.headers.get( "last-modified" );
if ( new Date( lastModified ) > new Date( cachedModified ) ) {
return fetchAndCache( url, cache );
}
} else {
return fetchAndCache( url, cache );
}
} );
} else {
return fetchAndCache( url, cache );
}
} )
.catch( () => {
return false;
} );
} else {
return fetchAndCache( url, cache );
}
} );
}
let cacheUpdate = [];
function fetchAndCache( url, cache ) {
return fetch( url )
.then( function ( response ) {
if ( [ 0, 200, 204 ].includes( response.status ) ) {
cacheUpdate.push( url );
return cache.put( url, response );
} else {
console.error( "bad response status - " + response.url );
}
} )
.catch( err => {
console.error( err );
} );
}
function purgeDynamicCache() {
return caches.open( dynamicCache )
.then( cache => {
let actions = [];
for ( let i = 0; i < dashboardDocs.length; i++ ) {
actions.push( cache.delete( dashboardDocs[ i ] ) );
}
return Promise.all( actions );
} );
}
function replaceDynamicCachedAssets() {
return caches.open( preCache )
.then( cache => {
let actions = [];
for ( let i = 0; i < dashboardDocs.length; i++ ) {
//change this to check the existing cache for any update needed
actions.push( fetchHead( dashboardDocs[ i ], cache ) );
}
return Promise.all( actions )
.catch( err => {
console.error( err );
} );
} );
}
function checkAssetTTL( key, ttl ) {
return localforage.getItem( key )
.then( lastCheck => {
let dt = new Date( lastCheck || 0 ).getTime(),
currentDT = new Date().getTime();
if ( dt < ( currentDT - ttl ) ) {
return localforage.setItem( key, currentDT )
.then( () => {
return true;
} );
} else {
return false;
}
} );
}
//periodically update this cache from network
function cacheCoreAssets() {
return checkAssetTTL( LAST_DYNAMIC_CHECK, DEFAULT_MAX_TIME )
//.then(shouldCheck => {
// if (shouldCheck) {
// return replaceDynamicCachedAssets();
// }
//})
.then( () => {
periodicAssetUpdate();
} );
}
function cacheResponse( request, response, cache_name ) {
return caches.open( cache_name )
.then( cache => {
return cache.put( request, response );
} );
}
function getSrcUrl( url ) {
let _url = new URL( url );
let srcUrl = _url.pathname;
if ( srcUrl.charAt( 0 ) === "/" ) {
srcUrl = srcUrl.substring( 1 );
}
return srcUrl;
}
function getFileExtension( pathname ) {
let pathParts = pathname.split( "." );
return ( pathParts.length > 1 ) ? pathParts[ 1 ] : "";
}
function fetchMediaAndCache( url ) {
//check service worker cache first
return caches.match( url, {
ignoreSearch: true
} )
.then( response => {
if ( response && [ 0, 200, 204 ].includes( response.status ) ) {
return response;
} else {
//then fallback to IDB Cache
return fetchAndCacheMediaIndexedDB( url );
}
} );
}
function fetchAndCacheMediaIndexedDB( url ) {
return localforage.getItem( url )
.then( blob => {
if ( blob ) {
return new Response( blob, {
headers: {
"Content-Type": mime_types[ getFileExtension( url ) ],
"Content-Length": blob.size
}
} );
} else {
let _ret;
return fetch( url, {
cache: "no-cache",
mode: "no-cors"
} )
.then( response => {
_ret = response.clone();
switch ( response.status ) {
case 0:
//can't cache opaque body
//either set CORS on source media or just deal with network
return response;
case 200:
case 204:
//store fetched media object in IDB
//helps with iOS quota issues
//note: if IDB > 50MB user is prompted to increase storage allowance
return response.blob()
.then( data => {
return localforage.setItem( url, data );
} )
.then( () => {
return _ret;
} );
default:
return caches.match( image_fallback );
}
} );
}
} );
}
function handleOffline( request ) {
let url = "";
if ( typeof request === "string" ) {
url = url;
} else {
url = request.url;
}
//place handlers for different routes here
//should have fallback responses for different routes and mime-types
if ( ( /\.jpg|\.png|\.gif/i ).test( url ) ) {
return caches.match( image_fallback );
} else {
return caches.match( doc_fallback );
}
}
function isVideoRequest( url ) {
return /\.mp4/.test( url );
}
function isImageRequest( url ) {
return /\.png|\.jpg|\.jpeg|\.webp|\.gif/.test( url );
}
function daysDifferent( d1, d2 ) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt( ( t2 - t1 ) / ( 24 * 3600 * 1000 ) );
}
//https://philna.sh/blog/2018/10/23/service-workers-beware-safaris-range-request/
//https://googlechrome.github.io/samples/service-worker/prefetch-video/
function handleRangeRequest( request, response ) {
if ( response ) {
return response.arrayBuffer()
.then( arrayBuffer => {
const bytes = /^bytes\=(\d+)\-(\d+)?$/g.exec(
request.headers.get( "range" )
);
if ( bytes ) {
const start = Number( bytes[ 1 ] );
const end = Number( bytes[ 2 ] ) || arrayBuffer.byteLength - 1;
return new Response( arrayBuffer.slice( start, end + 1 ), {
status: 206,
statusText: "Partial Content",
headers: [
[ "Content-Range", `bytes ${start}-${end}/${arrayBuffer.byteLength}` ]
]
} );
} else {
return new Response( null, {
status: 416,
statusText: "Range Not Satisfiable",
headers: [
[ "Content-Range", `*/${arrayBuffer.byteLength}` ]
]
} );
}
} );
}
return response;
}
function handleNonMedia( event ) {
return cacheFirstNetwork( event );
}
function cacheFirstNetwork( event ) {
return handleDocument( event.request )
.then( response => {
if ( response ) {
return response;
} else {
return fetch( event.request )
.then( response => {
//too much complexity, refactor
if ( [ 200, 204 ].includes( response.status ) ) {
let ContentType = response.headers.get( "content-type" );
if ( isCacheable( event.request.url ) &&
event.request.method.toLowerCase() === "get" &&
ContentType &&
!ContentType.toLowerCase().includes( "application/json" )
) {
if ( ContentType.toLowerCase().includes( "text/html" ) ) {
//return processHTML(response);
return response;
} else {
return cacheResponse( event.request, response.clone(), dynamicCache )
.then( () => {
return response;
} );
}
} else {
return response;
}
} else {
return response;
}
} );
}
} );
}
function isCacheable( url ) {
let u = new URL( url );
return !noCache.includes( u.pathname );
}
function networkCache( event ) {
//if offline then return from cache
//if within cache TTL then return from cache
//if TTL expired fetch from network then cache
//always update from network
}
function updateCachedAssets( cacheName ) {
return caches.open( cacheName )
.then( cache => {
cacheList.forEach( url => {
return fetchHead( url, cache );
} );
} )
.then( () => {
self.skipWaiting();
console.log( "pre-cached assets complete. the following URLs were updated" );
console.table( cacheUpdate, success );
} );
}
function handleDocument( request ) {
if ( request.destination === "document" ) {
return fetch( request );
//.then(processHTML);
} else {
return caches.match( request, {
ignoreSearch: true
} );
}
}