-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsw.js
More file actions
311 lines (263 loc) · 7.26 KB
/
sw.js
File metadata and controls
311 lines (263 loc) · 7.26 KB
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
//<editor-fold desc="tarball" defaultstate="collapsed">
class TarReader {
constructor() {
this.fileInfo = [];
}
readFile(file) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = (event) => {
this.buffer = event.target.result;
this.fileInfo = [];
this._readFileInfo();
resolve(this.fileInfo);
};
reader.readAsArrayBuffer(file);
});
}
readArrayBuffer(arrayBuffer) {
this.buffer = arrayBuffer;
this.fileInfo = [];
this._readFileInfo();
return this.fileInfo;
}
_readFileInfo() {
this.fileInfo = [];
let offset = 0;
let file_size = 0;
let file_name = "";
let file_type = null;
while (offset < this.buffer.byteLength - 512) {
file_name = this._readFileName(offset); // file name
if (file_name.length == 0) {
break;
}
file_type = this._readFileType(offset);
file_size = this._readFileSize(offset);
this.fileInfo.push({
"name": file_name,
"type": file_type,
"size": file_size,
"header_offset": offset
});
offset += (512 + 512 * Math.trunc(file_size / 512));
if (file_size % 512) {
offset += 512;
}
}
}
getFileInfo() {
return this.fileInfo;
}
_readString(str_offset, size) {
let strView = new Uint8Array(this.buffer, str_offset, size);
let i = strView.indexOf(0);
let td = new TextDecoder();
return td.decode(strView.slice(0, i));
}
_readFileName(header_offset) {
let name = this._readString(header_offset, 100);
return name;
}
_readFileType(header_offset) {
// offset: 156
let typeView = new Uint8Array(this.buffer, header_offset + 156, 1);
let typeStr = String.fromCharCode(typeView[0]);
if (typeStr == "0") {
return "file";
} else if (typeStr == "5") {
return "directory";
} else {
return typeStr;
}
}
_readFileSize(header_offset) {
// offset: 124
let szView = new Uint8Array(this.buffer, header_offset + 124, 12);
let szStr = "";
for (let i = 0; i < 11; i++) {
szStr += String.fromCharCode(szView[i]);
}
return parseInt(szStr, 8);
}
_readFileBlob(file_offset, size, mimetype) {
let view = new Uint8Array(this.buffer, file_offset, size);
let blob = new Blob([view], {"type": mimetype});
return blob;
}
_readFileBinary(file_offset, size) {
let view = new Uint8Array(this.buffer, file_offset, size);
return view;
}
_readTextFile(file_offset, size) {
let view = new Uint8Array(this.buffer, file_offset, size);
let td = new TextDecoder();
return td.decode(view);
}
getTextFile(file_name) {
let info = this.fileInfo.find(info => info.name == file_name);
if (info) {
return this._readTextFile(info.header_offset + 512, info.size);
}
}
getFileBlob(file_name, mimetype) {
let info = this.fileInfo.find(info => info.name == file_name);
if (info) {
return this._readFileBlob(info.header_offset + 512, info.size, mimetype);
}
}
getFileBinary(file_name) {
let info = this.fileInfo.find(info => info.name == file_name);
if (info) {
return this._readFileBinary(info.header_offset + 512, info.size);
}
}
};
//</editor-fold>
let version = 9;
let commit = "";
let cacheCommitToUse = "";
let fullyLoaded = false;
let zip;
updateCommit().then();
self.addEventListener("install", event => {
console.log("Installing service worker...");
self.skipWaiting();
console.log("Service worker installed!");
});
self.addEventListener("activate", event => {
clients.claim();
console.log("Service worker activated");
});
setInterval(async () => {
await updateCommit();
}, 60000 * 60); //every hour
/** @type {{string: [number, {}]}} */
let cache = {};
setInterval(async () => {
let now = Date.now();
for (let url in cache) {
if (now - cache[url][0] > 60000) {
delete cache[url];
}
}
}, 60000); //every minute
self.addEventListener('fetch', event => {
const url = new URL(event.request.url);
if (url.hostname === "cache") {
event.respondWith((async () => {
let [cacheTime, host] = url.pathname.substring(1).split("@");
let fullUrl = url.protocol + "//" + host;
if (fullUrl in cache) {
if (Date.now() - cache[fullUrl][0] < parseInt(cacheTime)) {
return new Response(JSON.stringify(cache[fullUrl]));
}
}
let data = await fetch(fullUrl);
let json = await data.json();
cache[fullUrl] = [Date.now(), json];
return new Response(JSON.stringify(cache[fullUrl]));
})());
return;
}
if (url.origin === location.origin) {
event.respondWith((async () => {
while (!fullyLoaded) {
await new Promise(resolve => setTimeout(resolve, 50));
}
if (url.pathname === "/") {
updateCommit().then();
}
if (url.pathname === "/hassw.txt") {
return new Response("YES");
}
if (commit.startsWith("DEV-") || url.pathname === "/commit.txt") {
return await fetch(event.request);
}
if (!fullyLoaded) {
return await fetch(event.request);
}
let path = url.pathname;
if (url.pathname === "/") path = "/index.html";
let mimeType = "application/octet-stream"
if (path.endsWith(".txt")) mimeType = "text/plain";
else if (path.endsWith(".js")) mimeType = "text/javascript";
else if (path.endsWith(".css")) mimeType = "text/css";
else if (path.endsWith(".json")) mimeType = "application/json";
else if (path.endsWith(".html")) mimeType = "text/html";
let fileBlob = zip.getFileBlob("." + path, mimeType);
return new Response(fileBlob);
// let cache = await caches.open(commit);
// return cache.match(url.pathname);
// } else {
// console.log("File not in cache!", url);
//
// let response = await fetch(url.pathname);
//
// let cache = await caches.open(commit);
// await cache.put(url.pathname, response);
//
// return await caches.match(url.pathname);
// }
})());
}
});
let updating = false;
async function updateCommit() {
let keys = await caches.keys();
try {
let res = await fetch("/commit.txt");
commit = await res.text();
commit += "-" + version;
} catch (e) {
if (keys.length > 0) {
console.log("Offline using cached data!")
commit = keys[0];
} else {
//no cached data sadge
return;
}
}
if (!cacheCommitToUse) {
cacheCommitToUse = commit;
}
//console.log("Commit updated:", commit);
if (!updating && (!fullyLoaded || !keys.includes(commit))) {
updating = true;
console.log("Updating website...");
let start = Date.now();
if (!commit.startsWith("DEV-")) {
zip = await this.loadFilesNew(commit);
}
fullyLoaded = true;
await Promise.all(keys.map(key => {
if (key !== commit) {
//console.log("Deleting cache:", key);
return caches.delete(key);
}
}));
cacheCommitToUse = commit;
updating = false;
console.log("Finished updating! (Took " + (Date.now() - start) + " ms)");
//TODO: send some sort of update avalible notification?
}
while (updating) {
await new Promise(r => setTimeout(r, 50));
}
}
async function loadFilesNew(commit) {
let response;
let hasCache = await caches.has(commit);
let cache = await caches.open(commit);
if (hasCache) {
response = (await cache.match("source.tar.gz"));
} else {
response = await fetch("source.tar.gz");
await cache.put("source.tar.gz", response.clone());
}
let uncompressed = await response.body.pipeThrough(new DecompressionStream("gzip"))
let blob = await new Response(uncompressed).blob();
let reader = new TarReader();
await reader.readFile(blob)
return reader;
}