This repository has been archived by the owner on Feb 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 97
/
index.js
191 lines (170 loc) · 5.62 KB
/
index.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
require('regenerator/runtime');
require('serviceworker-cache-polyfill');
var wikipedia = require('../shared/wikipedia');
var storage = require('../shared/storage');
var version = '24';
var prefix = 'wikioffline';
var staticCacheName = `${prefix}-static-v${version}`;
self.addEventListener('install', event => {
event.waitUntil(
caches.open(staticCacheName).then(cache => {
return cache.addAll([
'/',
'/shell.html',
'/js/page.js',
'/js/page-framework.js', // yeahhhh, we're caching waayyyyy more than we need, but keeps the request tests fair
'/css/head-wiki.css', // don't need this when it's inlined, but helps when rendered with blocking CSS in settings
'/css/wiki.css'
]).then(() => cache.match('/shell.html')).then(response => {
// bit hacky, making the shell start & end from the shell just fetched
return response.text().then(text => {
const headerEnd = text.indexOf('<div class="article-header subheading">');
const articleEnd = text.indexOf('<div class="background-load-offer card">');
return Promise.all([
cache.put('/shell-start.html', new Response(text.slice(0, headerEnd), response)),
cache.put('/shell-end.html', new Response(text.slice(articleEnd), response))
]);
});
});
})
);
});
var expectedCaches = [
staticCacheName
];
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keys => {
return Promise.all(
keys.map(key => {
if (key.startsWith(prefix + '-')
&& !key.startsWith(`${prefix}-article-`)
&& expectedCaches.indexOf(key) == -1) {
return caches.delete(key);
}
})
);
})
);
});
// This will vanish when the ServiceWorker closes,
// but that's cool, I want that.
var dataTmpCache = {};
self.addEventListener('fetch', event => {
var requestURL = new URL(event.request.url);
// catch the root request
if (requestURL.origin == location.origin) {
if (requestURL.pathname == '/') {
event.respondWith(caches.match('/'));
return;
}
if (requestURL.pathname.startsWith('/wiki/')) {
if (/\.(middle.inc)$/.test(requestURL.pathname)) {
return;
}
if (/\.(json|inc)$/.test(requestURL.pathname)) {
if (dataTmpCache[requestURL.href]) {
var response = dataTmpCache[requestURL.href];
delete dataTmpCache[requestURL.href];
event.respondWith(response);
}
return;
}
if (requestURL.search.includes('sw-stream')) {
event.respondWith(streamArticle(requestURL));
return;
}
// Get ahead of the pack by starting the json request now
if (!requestURL.search.includes('no-prefetch')) {
var jsonURL = new URL(requestURL);
jsonURL.pathname += '.json';
jsonURL.search = '';
var incURL = new URL(requestURL);
incURL.pathname += '.inc';
incURL.search = '';
dataTmpCache[jsonURL.href] = fetch(jsonURL, {
credentials: 'include' // needed for flag cookies
});
dataTmpCache[incURL.href] = fetch(incURL, {
credentials: 'include' // needed for flag cookies
});
}
event.respondWith(caches.match('/shell.html'));
return;
}
}
// default fetch behaviour
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request);
})
);
});
function streamArticle(url) {
try {
new ReadableStream({});
}
catch(e) {
return new Response("Streams not supported");
}
const stream = new ReadableStream({
start(controller) {
const contentURL = new URL(url);
contentURL.pathname += '.middle.inc';
const startFetch = caches.match('/shell-start.html');
const contentFetch = fetch(contentURL).catch(() => new Response("Failed, soz"));
const endFetch = caches.match('/shell-end.html');
function pushStream(stream) {
const reader = stream.getReader();
function read() {
return reader.read().then(result => {
if (result.done) return;
controller.enqueue(result.value);
return read();
});
}
return read();
}
startFetch
.then(response => pushStream(response.body))
.then(() => contentFetch)
.then(response => pushStream(response.body))
.then(() => endFetch)
.then(response => pushStream(response.body))
.then(() => controller.close());
}
});
return new Response(stream, {
headers: {'Content-Type': 'text/html'}
})
}
self.addEventListener('sync', event => {
// My use of storage here has race conditions. Meh.
console.log("Good lord, a sync event");
event.waitUntil(
storage.get('to-bg-cache').then(toCache => {
toCache = toCache || [];
return Promise.all(toCache.map(async articleName => {
var article = await wikipedia.article(articleName);
await article.cache();
registration.showNotification((await article.meta).title + " ready!", {
icon: "/imgs/wikipedia-192.png",
body: "View the article",
data: (await article.meta).urlId
});
}));
}).then(_ => {
storage.set('to-bg-cache', []);
})
);
});
self.addEventListener('notificationclick', function(event) {
// assuming only one type of notification right now
event.notification.close();
clients.openWindow(`${location.origin}/wiki/${event.notification.data}`);
});
self.addEventListener('message', event => {
if (event.data == 'skipWaiting') {
self.skipWaiting();
}
});