-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
412 lines (373 loc) · 10.5 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
// Service Worker Versão
const version = "1.124";
// Assets que serão salvos quando instalar o sw.
const swAssets = [
'./',
'./manifest.json',
'./index.html',
'./css/bootstrap-icons/font/bootstrap-icons.css',
'./css/bootstrap-icons/font/bootstrap-icons.min.css',
'./css/bootstrap-icons/font/fonts/bootstrap-icons.woff',
'./css/bootstrap-icons/font/fonts/bootstrap-icons.woff2',
'./css/bootstrap.min.css',
'./css/divListagem.css',
'./css/mk.css',
'./css/reset.css',
'./css/site.css',
'./html/offline.html',
'./img/icons/ok_72.png',
'./img/icons/ok_96.png',
'./img/icons/ok_128.png',
'./img/icons/ok_144.png',
'./img/icons/ok_152.png',
'./img/icons/ok_192.png',
'./img/icons/ok_384.png',
'./img/icons/ok_512.png',
'./img/icons/ok_mask_196.png',
'./js/mkt.js',
'./js/mksw.js',
'./js/popperv2.js',
'./js/site.js',
];
const icon = "img/icons/ok_72.png";
const vibrate = [100, 30, 100, 30, 100];
/**********************************\\
// MK SERVICE WORKER \\
//__________________________________*/
let log_level = new URL(location.href).searchParams.get("log");
if (log_level == null) { log_level = 0; }
let f = new URL(location.href).searchParams.get("f"); // ativa / desativa found (encontrado fora dos assets)
if (f != "false") { f = true; } else { f = false; };
let politica = new URL(location.href).searchParams.get("p");
if (politica == null) { politica = 1; } else { politica = Number(politica); } // Padrão CacheFirst
const cacheName = "sw_v_static_" + version; // Assets ao instalar
const cacheFound = "sw_v_found_" + version; // Assets que irá guardar durante.
self.numBadges = 0;
// Inside of Worker
const showError = (msg, erro) => {
console.log(`%cI> %cSW_ERRO: %c${msg}%c ->`, "color:lawngreen;", "color:MediumSpringGreen;", "background:#0009;color:red;border-radius:3px;padding:0px 3px;", "color:MediumOrchid;", erro);
}
// Inside of Worker
const showInfo = (msg, data, nivel = 2) => {
if (log_level >= nivel) {
console.log(`%cI> %cSW_INFO: %c${msg}%c ->`, "color:lawngreen;", "color:MediumSpringGreen;", "background:#0005;color:green;border-radius:3px;padding:0px 3px;", "color:MediumOrchid;", data);
}
}
const sw_cacheUpdate = async (cacheName) => {
showInfo("Atualizando Cache...", cacheName, 2);
caches.open(cacheName).then((cache) => {
const stack = [];
// ADD ==> Coleta as rotas e guarda.
swAssets.forEach((rota) => stack.push(
cache.add(rota).catch(_ => showError("Falha no cache da rota: ", rota))
));
return Promise.all(stack);
})
};
// Aqui salva apenas no found
const sw_cacheSave = (url, inNetwork) => {
if (swAssets.includes(url)) {
// Se for salvar um item do asset, já salva atualiza no static.
caches.open(cacheName).then((cache) => {
cache.put(url, inNetwork);
})
} else {
if (f) {
caches.open(cacheFound).then((cache) => {
showInfo(`+++ ${cacheFound}...`, url, 3);
cache.put(url, inNetwork);
})
}
}
};
const getClients = async () => await self.clients.matchAll({ includeUncontrolled: true });
const hasActiveClients = async () => {
const clients = await getClients();
return clients.some(({ visibilityState }) => visibilityState === 'visible');
};
const getActiveClients = async () => {
const clients = await getClients();
return clients.filter(({ visibilityState }) => visibilityState === 'visible');
};
const sw_messageToClients = async (msg, str = "") => {
const clients = await getClients();
let obj = {
type: msg,
str: str,
ver: version
}
showInfo(">> COMUNICAÇÃO", obj);
clients.forEach((client) => { client.postMessage(obj) });
}
// Comunicação
self.addEventListener('message', async (ev) => {
const { type } = ev.data;
showInfo("<< COMUNICAÇÃO", ev.data);
switch (type) {
case "PREPARE_CACHES_FOR_UPDATE":
ev.waitUntil(sw_cacheUpdate(cacheName).then(r => {
sw_messageToClients("UPDATED_CACHE");
}));
break;
case "SKIP_WAITING":
const clients = await getClients();
if (clients.length < 2) {
self.skipWaiting();
}
break;
case 'CLEAR_BADGES':
self.numBadges = 0;
if ('clearAppBadge' in navigator) {
navigator.clearAppBadge();
}
break;
case "VERSION":
sw_messageToClients("VERSION");
break;
}
});
// Ao instalar uma nova versão
self.addEventListener('install', ev => {
ev.waitUntil(showInfo("NOVA versão! (Updating Cache...)", version));
ev.waitUntil(sw_cacheUpdate(cacheName));
});
// Ao ativar nova versão
self.addEventListener("activate", ev => {
showInfo(`NOVA Versao ATIVA (${version}). Removendo Antigas...`, "ATIVO");
sw_messageToClients("VERSION");
// Aqui limpa versoes antigas.
// Possivel problema: 2 Abas, usando o mesmo cache,
// mas uma aba avança versão e a outra não.
// A segunda irá limpar o cache da primeira.
ev.waitUntil(caches.keys()
.then(versoesCache => {
return Promise.all(versoesCache
.filter(k => (k !== cacheName) && (k !== cacheFound))
.map(k => caches.delete(k))
)
})
);
ev.waitUntil(self.clients.claim());
})
// // POLÍTICAS SW PROXY
self.addEventListener("fetch", ev => {
// Verificar possibilidade de diferentes políticas pra diferentes tipos de request.
let url = new URL(ev.request.url);
let checkUrl = url.origin + url.pathname;
if (url.origin == location.origin) {
checkUrl = url.pathname; // Apenas Path dos assets
}
switch (politica) {
case 0:
// 0 - Stale-While-Revalidate
ev.respondWith(
caches.match(checkUrl).then((inCache) => {
return inCache || fetch(ev.request).then((inNetwork) => {
sw_cacheSave(checkUrl, inNetwork.clone());
return inNetwork;
});
})
)
break;
case 1:
// 1 - Cache first, then Network
ev.respondWith(
caches.match(checkUrl).then(async (inCache) => {
if (inCache) {
return inCache;
} else {
return fetch(ev.request).then(inNetwork => {
sw_cacheSave(checkUrl, inNetwork.clone());
return inNetwork;
});
}
})
)
break;
case 2:
// 2 - Network first, then Cache
ev.respondWith(
fetch(ev.request).then(inNetwork => {
sw_cacheSave(checkUrl, inNetwork.clone());
return inNetwork;
}).catch(async () => { // Só retorna cache se deu erro no fetch
const inCache = await caches.match(checkUrl);
if (inCache) return inCache;
})
);
break;
case 3:
// 3 - Cache only
ev.respondWith(
caches.match(checkUrl).then((cacheResponse) => {
return cacheResponse;
})
)
break;
case 4:
// 4 - Network only
ev.respondWith(
fetch(ev.request).then((inNetwork) => {
return inNetwork;
})
)
break;
}
})
// OUTRAS MECANICAS
// NOTIFICATION
// Close
const closeNotify = async (ev, msg = "Notif. Fechada") => {
showInfo(msg, ev);
ev.notification.close();
}
// Clique na notificação
self.addEventListener('notificationclick', async (ev) => {
if (ev.action !== "close") {
let promessa = async () => {
return new Promise((re) => {
setTimeout(re, 50);
}).then(() => {
showInfo(`Abrindo APP`, ev.notification.data.loc);
return self.clients.openWindow(ev.notification.data.loc);
});
}
ev.waitUntil((async () => {
let ativos = await getActiveClients();
showInfo(`Ativos`, ativos);
ativos.forEach(ativo => {
if (ativo.type == "window") {
// Aqui é possivel redirecionar pra tela de notificações por exemplo
showInfo(`Redirecionando...`, ativo);
ativo.navigate(ev.notification.data.loc);
}
})
if (ativos.length <= 0) {
await promessa();
}
})()
);
}
closeNotify(ev, "Notif. Clicada");
})
// Ao fechar, em massa e com delay.
self.addEventListener('notificationclose', async (ev) => {
closeNotify(ev);
});
// Push (Server > SW > Client)
self.addEventListener('push', async (ev) => {
const data = ev.data.json();
showInfo(`Push de Notificação do Servidor.`, data);
const { title, message, interaction } = data;
const options = {
body: message,
icon: icon,
vibrate: vibrate,
data: {
dateOfArrival: Date.now()
},
actions: [{
action: 'confirm',
title: 'OK'
}, {
action: 'close',
title: 'Fechar'
},],
requireInteraction: interaction
};
ev.waitUntil(
self.registration.showNotification(title, options)
.then(hasActiveClients)
.then((activeClients) => {
if (!activeClients) {
self.numBadges += 1;
navigator.setAppBadge(self.numBadges);
}
})
.catch(err => sw_messageToClients(err))
)
});
// STORAGE PWA
const IDBConfig = {
name: 'pwa-db',
version,
store: {
name: `pwa-store`,
keyPath: 'timestamp'
}
};
const getStoreFactory = (dbName) => ({ name }, mode = 'readonly') => {
return new Promise((resolve, reject) => {
const request = self.indexedDB.open(dbName, 1);
request.onsuccess = e => {
const db = request.result;
const transaction = db.transaction(name, mode);
const store = transaction.objectStore(name);
return resolve(store);
};
request.onerror = e => reject(request.error);
});
};
const openStore = getStoreFactory(IDBConfig.name);
const getCacheStorageNames = async () => {
const cacheNames = await caches.keys() || [];
const outdatedCacheNames = cacheNames.filter(name => !name.includes(cacheName));
const latestCacheName = cacheNames.find(name => name.includes(cacheName));
return { latestCacheName, outdatedCacheNames };
};
// Online
self.addEventListener('sync', async ev => {
const title = 'Background Sync demo';
const message = 'Background Sync demo message';
if (ev.tag.startsWith('sync-demo')) {
const options = {
body: message,
icon: icon,
vibrate: vibrate,
data: {
dateOfArrival: Date.now()
},
actions: [
{
action: 'confirm',
title: 'OK'
},
{
action: 'close',
title: 'Fechar'
},
]
};
let idbStore;
const getNotifications = () => new Promise((resolve, reject) => {
openStore(IDBConfig.store, 'readwrite')
.then((store) => {
idbStore = store;
const request = idbStore.getAll();
request.onsuccess = e => {
const { result } = request;
return resolve(result);
};
request.onerror = e => reject(e);
})
});
ev.waitUntil(
getNotifications()
.then((notifications) => {
console.log(notifications);
const requests = notifications.map(({ message }) => {
options.body = message;
return self.registration.showNotification(title, options);
});
return Promise.all(requests)
.then(() => openStore(IDBConfig.store, 'readwrite'))
.then(idbStore => idbStore.clear());
})
)
}
});
// Fetch in background
self.addEventListener('backgroundfetchsuccess', async (e) => {
const { id } = e.registration;
sw_messageToClients("background-fetch-success", id)
});