Primo committ Notevole
This commit is contained in:
579
src-pwa/custom-service-worker.js
Normal file
579
src-pwa/custom-service-worker.js
Normal file
@@ -0,0 +1,579 @@
|
||||
/*
|
||||
* This file (which will be your service worker)
|
||||
* is picked up by the build system ONLY if
|
||||
* quasar.conf > pwa > workboxPluginMode is set to "InjectManifest"
|
||||
*/
|
||||
|
||||
// Questo è il swSrc
|
||||
|
||||
console.log(' [ VER-0.0.62 ] _---------________------ PAO: this is my custom service worker');
|
||||
|
||||
importScripts('../statics/js/idb.js');
|
||||
importScripts('../statics/js/storage.js');
|
||||
importScripts('../statics/js/workbox-sw.js');
|
||||
|
||||
// importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js');
|
||||
|
||||
|
||||
let port = 3000;
|
||||
if (self.location.hostname.startsWith('test')) {
|
||||
port = 3001;
|
||||
}
|
||||
// console.log('SW-06 1');
|
||||
const cfgenv = {
|
||||
serverweb: self.location.protocol + "//" + self.location.hostname + ':' + port,
|
||||
dbname: 'mydb3',
|
||||
dbversion: 11,
|
||||
}
|
||||
|
||||
// console.log('serverweb', cfgenv.serverweb)
|
||||
|
||||
async function writeData(table, data) {
|
||||
// console.log('writeData', table, data);
|
||||
await idbKeyval.setdata(table, data);
|
||||
}
|
||||
|
||||
|
||||
async function readAllData(table) {
|
||||
// console.log('readAllData', table);
|
||||
return await idbKeyval.getalldata(table);
|
||||
}
|
||||
|
||||
async function clearAllData(table) {
|
||||
// console.log('clearAllData', table);
|
||||
await idbKeyval.clearalldata(table)
|
||||
}
|
||||
|
||||
async function deleteItemFromData(table, id) {
|
||||
// console.log('deleteItemFromData', table, 'ID:', id);
|
||||
|
||||
await idbKeyval.deletedata(table, id)
|
||||
}
|
||||
|
||||
|
||||
// self.addEventListener('activate', function(myevent) {
|
||||
// myevent.waitUntil(
|
||||
// // createDB()
|
||||
// );
|
||||
// });
|
||||
|
||||
if (!workbox) {
|
||||
let workbox = new self.WorkboxSW();
|
||||
}
|
||||
|
||||
if (workbox) {
|
||||
// console.log('WORKBOX PRESENT')
|
||||
// const url = new URL(location.href);
|
||||
// const debug = url.searchParams.has('debug');
|
||||
const debug = false;
|
||||
workbox.setConfig({ debug: debug });
|
||||
|
||||
workbox.core.setCacheNameDetails({ prefix: "notevole" });
|
||||
|
||||
/**
|
||||
* The workboxSW.precacheAndRoute() method efficiently caches and responds to
|
||||
* requests for URLs in the manifest.
|
||||
* See https://goo.gl/S9QRab
|
||||
*/
|
||||
self.__precacheManifest = [].concat(self.__precacheManifest || []);
|
||||
workbox.precaching.suppressWarnings();
|
||||
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
|
||||
|
||||
// workbox.routing.registerRoute(/^http/, workbox.strategies.networkFirst(), 'GET');
|
||||
|
||||
workbox.routing.registerRoute(
|
||||
new RegExp(/\.(?:png|gif|jpg|jpeg|svg)$/),
|
||||
new workbox.strategies.CacheFirst({
|
||||
cacheName: 'images',
|
||||
plugins: [
|
||||
new workbox.expiration.Plugin({
|
||||
maxEntries: 60,
|
||||
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
|
||||
}),
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
// Per Articoli....
|
||||
const articleHandler = workbox.strategies.networkFirst({
|
||||
cacheName: 'articles-cache',
|
||||
plugins: [
|
||||
new workbox.expiration.Plugin({
|
||||
maxEntries: 50,
|
||||
})
|
||||
]
|
||||
});
|
||||
|
||||
workbox.routing.registerRoute(
|
||||
new RegExp(/(.*)article(.*)\.html/), args => {
|
||||
return articleHandler.handle(args);
|
||||
});
|
||||
|
||||
|
||||
workbox.routing.registerRoute(
|
||||
new RegExp(/.*(?:googleapis|gstatic)\.com.*$/),
|
||||
workbox.strategies.staleWhileRevalidate({
|
||||
cacheName: 'google-fonts',
|
||||
plugins: [
|
||||
new workbox.expiration.Plugin({
|
||||
maxEntries: 30,
|
||||
}),
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
// console.log(' routing.registerRoute function declaration:')
|
||||
|
||||
function Execute_Fetch(table, args) {
|
||||
console.log('Execute_Fetch registerRoute! ', cfgenv.serverweb + '/' + table + '/')
|
||||
// console.log('DATABODY:', args.myevent.request.body)
|
||||
let myres = null
|
||||
// return fetch(args.myevent.request, args.myevent.headers)
|
||||
return fetch(args.event.request, args.event.headers)
|
||||
.then(function (res) {
|
||||
myres = res
|
||||
if (res.status === 200) {
|
||||
const clonedRes = res.clone();
|
||||
|
||||
let secondatab = ''
|
||||
if (table === 'todos') {
|
||||
secondatab = 'categories'
|
||||
}
|
||||
console.log('1) clearAllData: ', table)
|
||||
return clearAllData(table)
|
||||
.then(() => {
|
||||
if (secondatab !== '') {
|
||||
// console.log('2) clearAllData(todos)')
|
||||
return clearAllData(secondatab)
|
||||
.then(() => {
|
||||
// console.log('3) ....return clonedRes')
|
||||
return clonedRes
|
||||
})
|
||||
} else {
|
||||
return clonedRes
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
.then((clonedRes) => {
|
||||
// console.log(' 3) ')
|
||||
if (!!clonedRes)
|
||||
return clonedRes.json();
|
||||
return null
|
||||
})
|
||||
.then(data => {
|
||||
// console.log(' 4) data = ', data)
|
||||
if (data) {
|
||||
|
||||
myarr = idbKeyval.getArrayByTable(table, data)
|
||||
if (myarr) {
|
||||
|
||||
let promiseChain = Promise.resolve();
|
||||
|
||||
console.log('*********+++++++++++++++++********** Records ', table + ' Received from Server [', myarr.length, 'record]', myarr)
|
||||
|
||||
if (table === 'todos') {
|
||||
for (const cat in data.categories) {
|
||||
promiseChain = promiseChain.then(() => {
|
||||
return writeData('categories', { _id: cat, valore: data.categories[cat] })
|
||||
})
|
||||
}
|
||||
|
||||
for (const arrsing of myarr) {
|
||||
for (const rec of arrsing) {
|
||||
promiseChain = promiseChain.then(() => {
|
||||
return writeData(table, rec)
|
||||
})
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Others tables
|
||||
for (const rec of myarr) {
|
||||
promiseChain = promiseChain.then(() => {
|
||||
return writeData(table, rec)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// console.log('promiseChain', promiseChain)
|
||||
|
||||
return promiseChain
|
||||
}
|
||||
}
|
||||
})
|
||||
.then(() => {
|
||||
return myres
|
||||
})
|
||||
.catch(err => {
|
||||
console.log('ERROR registerRoute FETCH:', err)
|
||||
return myres
|
||||
})
|
||||
}
|
||||
|
||||
for (let table of MainTables) {
|
||||
workbox.routing.registerRoute(
|
||||
new RegExp(cfgenv.serverweb + '/' + table + '/'),
|
||||
function (args) {
|
||||
Execute_Fetch(table, args)
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
workbox.routing.registerRoute(function (routeData) {
|
||||
return (routeData.event.request.headers.get('accept').includes('text/html'));
|
||||
}, function (args) {
|
||||
return caches.match(args.event.request)
|
||||
.then(function (response) {
|
||||
if (response) {
|
||||
return response;
|
||||
} else {
|
||||
return fetch(args.event.request)
|
||||
.then(function (res) {
|
||||
return caches.open('dynamic')
|
||||
.then(function (cache) {
|
||||
cache.put(args.event.request.url, res.clone());
|
||||
return res;
|
||||
})
|
||||
})
|
||||
.catch(function (err) {
|
||||
return caches.match('/offline')
|
||||
.then(function (res) {
|
||||
return res;
|
||||
});
|
||||
});
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
workbox.routing.registerRoute(
|
||||
new RegExp(/.*\/(?:statics\/icons).*$/),
|
||||
new workbox.strategies.StaleWhileRevalidate({
|
||||
cacheName: 'image-cache',
|
||||
})
|
||||
);
|
||||
|
||||
workbox.routing.registerRoute(
|
||||
new RegExp(/\.(?:js|css|font)$/),
|
||||
new workbox.strategies.StaleWhileRevalidate({
|
||||
cacheName: 'js-css-fonts',
|
||||
}),
|
||||
);
|
||||
|
||||
/*
|
||||
workbox.routing.registerRoute(
|
||||
new RegExp('https://cdnjs.coudflare.com/ajax/libs/material-design-lite/1.3.0/material.indigo-pink.min.css'),
|
||||
workbox.strategies.staleWhileRevalidate({
|
||||
cacheName: 'material-css',
|
||||
plugins: [
|
||||
new workbox.expiration.Plugin({
|
||||
maxAgeSeconds: 30 * 24 * 60 * 60,
|
||||
}),
|
||||
]
|
||||
})
|
||||
);
|
||||
*/
|
||||
|
||||
// Storage
|
||||
workbox.routing.registerRoute(
|
||||
new RegExp(/.*(?:storage)/),
|
||||
workbox.strategies.staleWhileRevalidate({
|
||||
cacheName: 'storage',
|
||||
plugins: [
|
||||
new workbox.expiration.Plugin({
|
||||
maxAgeSeconds: 30 * 24 * 60 * 60,
|
||||
// Only cache 10 requests.
|
||||
maxEntries: 200,
|
||||
}),
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
workbox.routing.registerRoute(
|
||||
new RegExp(/.*\/(?:statics).*$/),
|
||||
workbox.strategies.staleWhileRevalidate({
|
||||
cacheName: 'statics',
|
||||
})
|
||||
);
|
||||
|
||||
/*
|
||||
workbox.routing.registerRoute(
|
||||
new RegExp(/^http/),
|
||||
workbox.strategies.networkFirst({
|
||||
cacheName: 'all-stuff',
|
||||
plugins: [
|
||||
new workbox.expiration.Plugin({
|
||||
maxAgeSeconds: 10 * 24 * 60 * 60,
|
||||
// Only cache 10 requests.
|
||||
}),
|
||||
]
|
||||
})
|
||||
);
|
||||
*/
|
||||
|
||||
|
||||
workbox.routing.registerRoute(
|
||||
new RegExp('/admin/'),
|
||||
workbox.strategies.networkOnly()
|
||||
);
|
||||
|
||||
workbox.routing.registerRoute(
|
||||
new RegExp('/owa/'),
|
||||
workbox.strategies.networkOnly()
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
if ('serviceWorker' in navigator) {
|
||||
|
||||
// console.log('***************** Entering in custom-service-worker.js:')
|
||||
|
||||
}
|
||||
|
||||
|
||||
// self.addEventListener('fetch', (myevent) => {
|
||||
// if (myevent.request.url === '/') {
|
||||
// const staleWhileRevalidate = new workbox.strategies.StaleWhileRevalidate();
|
||||
// myevent.respondWith(staleWhileRevalidate.handle({ myevent }));
|
||||
// }
|
||||
// });
|
||||
|
||||
// self.addEventListener('fetch', function (myevent) {
|
||||
// console.log('[Service Worker] Fetching something ....', myevent);
|
||||
// console.log('myevent.request.cache=', myevent.request.cache)
|
||||
// if (myevent.request.cache === 'only-if-cached' && myevent.request.mode !== 'same-origin') {
|
||||
// console.log('SAME ORIGIN!', myevent);
|
||||
// return;
|
||||
// }
|
||||
// myevent.respondWith(caches.match(myevent.request));
|
||||
// });
|
||||
//
|
||||
|
||||
// const syncStore = {}
|
||||
// self.addEventListener('message', myevent => {
|
||||
// if (myevent.data.type === 'sync') {
|
||||
// // get a unique id to save the data
|
||||
// const id = uuid()
|
||||
// syncStore[id] = myevent.data
|
||||
// // register a sync and pass the id as tag for it to get the data
|
||||
// self.registration.sync.register(id)
|
||||
// }
|
||||
// console.log(myevent.data)
|
||||
// })
|
||||
|
||||
// addEventListener('fetch', myevent => {
|
||||
// // Prevent the default, and handle the request ourselves.
|
||||
// myevent.respondWith(async function() {
|
||||
// // Try to get the response from a cache.
|
||||
// const cachedResponse = await caches.match(myevent.request);
|
||||
// // Return it if we found one.
|
||||
// if (cachedResponse && (myevent.request.cache !== 'no-cache'))
|
||||
// return cachedResponse;
|
||||
//
|
||||
// // If we didn't find a match in the cache, use the network.
|
||||
// return fetch(myevent.request);
|
||||
// }());
|
||||
// });
|
||||
|
||||
// self.addEventListener('fetch', function (myevent) {
|
||||
// myevent.respondWith(
|
||||
// caches.match(myevent.request).then(function (response) {
|
||||
// return response ||
|
||||
// fetch(myevent.request, myevent.headers)
|
||||
// .catch(err => {
|
||||
// console.log('_______________________ ERRORE FETCH SW: ', myevent.request, err)
|
||||
// writeData('config', { _id: 2, stateconn: 'offline' })
|
||||
// return caches.match(myevent.request);
|
||||
// })
|
||||
// })
|
||||
// );
|
||||
// });
|
||||
|
||||
|
||||
// self.addEventListener('fetch', function (myevent) {
|
||||
// myevent.respondWith(
|
||||
// fetch(myevent.request, myevent.headers)
|
||||
// .catch(err => {
|
||||
// console.log('_______________________ ERRORE FETCH SW: ', myevent.request, err)
|
||||
// writeData('config', {_id: 2, stateconn: 'offline'})
|
||||
// return caches.match(myevent.request);
|
||||
// })
|
||||
// );
|
||||
// });
|
||||
|
||||
|
||||
// self.addEventListener('sync', function (myevent) {
|
||||
// console.log('[Service Worker V5] Background syncing', myevent.tag);
|
||||
//
|
||||
// let mystrparam = myevent.tag
|
||||
// let multiparams = mystrparam.split('|')
|
||||
// if (multiparams) {
|
||||
// if (multiparams.length > 3) {
|
||||
// let cmd = multiparams[0]
|
||||
// let table = multiparams[1]
|
||||
// let method = multiparams[2]
|
||||
// let token = multiparams[3]
|
||||
// // let lang = multiparams[3]
|
||||
//
|
||||
// if (cmd === 'sync-todos') {
|
||||
// console.log('[Service Worker] Syncing', cmd, table, method);
|
||||
//
|
||||
// const headers = new Headers()
|
||||
// headers.append('content-Type', 'application/json')
|
||||
// headers.append('Accept', 'application/json')
|
||||
// headers.append('x-auth', token)
|
||||
//
|
||||
//
|
||||
// // console.log('A1) INIZIO.............................................................');
|
||||
//
|
||||
// myevent.waitUntil(
|
||||
// readAllData(table)
|
||||
// .then(function (alldata) {
|
||||
// const myrecs = [...alldata]
|
||||
// console.log('----------------------- LEGGO QUALCOSA DAL WAITUNTIL ')
|
||||
// let errorfromserver = false
|
||||
// if (myrecs) {
|
||||
// for (let rec of myrecs) {
|
||||
// //console.log('syncing', table, '', rec.descr)
|
||||
// let link = cfgenv.serverweb + '/todos'
|
||||
//
|
||||
// if (method !== 'POST')
|
||||
// link += '/' + rec._id
|
||||
//
|
||||
// console.log('++++++++++++++++++ SYNCING !!!! ', rec.descr, table, 'FETCH: ', method, link, 'data:')
|
||||
//
|
||||
// // console.log('DATATOSAVE:', JSON.stringify(rec))
|
||||
//
|
||||
// // Insert/Delete/Update table to the server
|
||||
// fetch(link, {
|
||||
// method: method,
|
||||
// headers: headers,
|
||||
// cache: 'no-cache',
|
||||
// mode: 'cors', // 'no-cors',
|
||||
// body: JSON.stringify(rec)
|
||||
// })
|
||||
// .then(() => {
|
||||
// deleteItemFromData(table, rec._id)
|
||||
// })
|
||||
// .then(() => {
|
||||
// deleteItemFromData('swmsg', mystrparam)
|
||||
// })
|
||||
// .catch(function (err) {
|
||||
// console.log('!!!!!!!!!!!!!!! Error while sending data', err, err.message);
|
||||
// if (err.message === 'Failed to fetch') {
|
||||
// errorfromserver = true
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
// return errorfromserver
|
||||
// }
|
||||
// })
|
||||
// .then((errorfromserver) => {
|
||||
// const mystate = !errorfromserver ? 'online' : 'offline'
|
||||
// writeData('config', { _id: 2, stateconn: mystate })
|
||||
// })
|
||||
// );
|
||||
// // console.log('A2) ?????????????????????????? ESCO DAL LOOP !!!!!!!!! err=')
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// ;
|
||||
|
||||
|
||||
/*
|
||||
|
||||
// send message to serviceWorker
|
||||
function sync (url, options) {
|
||||
navigator.serviceWorker.controller.postMessage({type: 'sync', url, options})
|
||||
}
|
||||
|
||||
|
||||
const syncStore = {}
|
||||
self.addEventListener('message', myevent => {
|
||||
if(myevent.data.type === 'sync') {
|
||||
// get a unique id to save the data
|
||||
const id = uuid()
|
||||
syncStore[id] = myevent.data
|
||||
// register a sync and pass the id as tag for it to get the data
|
||||
self.registration.sync.register(id)
|
||||
}
|
||||
console.log(myevent.data)
|
||||
})
|
||||
|
||||
|
||||
self.addEventListener('sync', myevent => {
|
||||
// get the data by tag
|
||||
const {url, options} = syncStore[myevent.tag]
|
||||
myevent.waitUntil(fetch(url, options))
|
||||
})
|
||||
*/
|
||||
|
||||
self.addEventListener('notificationclick', function (event) {
|
||||
var notification = event.notification;
|
||||
var action = event.action;
|
||||
|
||||
console.log(notification);
|
||||
|
||||
if (action === 'confirm') {
|
||||
console.log('Confirm was chosen');
|
||||
notification.close();
|
||||
} else {
|
||||
console.log(action);
|
||||
event.waitUntil(
|
||||
clients.matchAll()
|
||||
.then(function (clis) {
|
||||
var client = clis.find(function (c) {
|
||||
return c.visibilityState === 'visible';
|
||||
});
|
||||
|
||||
if (!!client) {
|
||||
client.navigate(notification.data.url);
|
||||
client.focus();
|
||||
} else {
|
||||
clients.openWindow(notification.data.url);
|
||||
}
|
||||
notification.close();
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
self.addEventListener('notificationclose', function (event) {
|
||||
console.log('Notification was closed', event);
|
||||
});
|
||||
|
||||
self.addEventListener('push', function (event) {
|
||||
console.log('Push Notification received', event);
|
||||
|
||||
var data = { title: 'New!', content: 'Something new happened!', url: '/' };
|
||||
|
||||
try {
|
||||
|
||||
if (event.data) {
|
||||
try {
|
||||
data = JSON.parse(event.data.text());
|
||||
} catch (e) {
|
||||
data = event.data.text();
|
||||
}
|
||||
}
|
||||
|
||||
var options = {
|
||||
body: data.content,
|
||||
icon: '/statics/icons/android-chrome-192x192.png',
|
||||
badge: '/statics/icons/android-chrome-192x192.png',
|
||||
data: {
|
||||
url: data.url
|
||||
},
|
||||
tag: 'received',
|
||||
renitify: true, // vibrate also with others messages.
|
||||
};
|
||||
|
||||
event.waitUntil(
|
||||
self.registration.showNotification(data.title, options)
|
||||
);
|
||||
} catch (e) {
|
||||
console.log('Error on myevent push:', e)
|
||||
}
|
||||
});
|
||||
|
||||
40
src-pwa/register-service-worker.js
Normal file
40
src-pwa/register-service-worker.js
Normal file
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* This file is picked up by the build system only
|
||||
* when building for PRODUCTION
|
||||
*/
|
||||
|
||||
import { register } from 'register-service-worker'
|
||||
|
||||
|
||||
|
||||
register(process.env.SERVICE_WORKER_FILE, {
|
||||
ready() {
|
||||
console.log('READY::: App is being served from cache by a service worker.')
|
||||
},
|
||||
|
||||
registered(registration) { // registration -> a ServiceWorkerRegistration instance
|
||||
console.log('REGISTERED::: !!!', process.env.SERVICE_WORKER_FILE)
|
||||
},
|
||||
cached(registration) {
|
||||
console.log('CACHED::: Content has been cached for offline use.')
|
||||
},
|
||||
updatefound(registration) {
|
||||
console.log('UPDATEFOUND::: New content is downloading.')
|
||||
// $('#newvers').addClass('btnNewVersShow').removeClass("btnNewVersHide")
|
||||
},
|
||||
updated(registration) {
|
||||
console.log('New content is available; please refresh.')
|
||||
},
|
||||
offline() {
|
||||
console.log('No internet connection found. App is running in offline mode.')
|
||||
},
|
||||
error(err) {
|
||||
console.error('Error during service worker registration:', err)
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// ServiceWorkerRegistration: https://developer.mozilla.org/enUs/docs/Web/API/ServiceWorkerRegistration
|
||||
|
||||
|
||||
// "build": "quasar build -m pwa && workbox generateSW workbox-config.js",
|
||||
Reference in New Issue
Block a user