From ce20daed6d5e3f76aa313947418f115c5bd8ec4f Mon Sep 17 00:00:00 2001 From: paoloar77 Date: Sun, 7 Aug 2022 02:01:20 +0200 Subject: [PATCH] Notification with Service Workers now is working! When a Notification arrives, it save into the IndexDb, then in Vue.js call a polling to check in the db if there is a different record count. If is different then call a get to update the notification. --- .env.development | 1 + public/js/storage.js | 13 +- src-pwa/custom-service-worker.js | 347 ++++++++++-------- src/common/shared_vuejs.ts | 2 +- src/components/CFundRaising/CFundRaising.ts | 9 - .../CPhotosGallery/CPhotosGallery.ts | 5 - .../CPresentazione/CPresentazione.ts | 9 - src/globalroutines/index.ts | 4 +- src/globalroutines/indexdb.ts | 18 +- src/js/storage.js | 40 +- .../toolbar/notifPopover/notifPopover.ts | 30 +- src/model/MessageStore.ts | 3 +- src/rootgen/admin/userPanel/userPanel.vue | 6 +- src/rootgen/admin/usersList/usersList.ts | 4 + src/statics/lang/it.js | 3 + src/store/Api/Inst-Pao.ts | 2 +- src/store/Api/Instance.ts | 6 +- src/store/Api/index.ts | 4 +- src/store/MessageStore.ts | 4 +- src/store/Modules/ApiTables.ts | 61 ++- src/store/Modules/costanti.ts | 2 +- src/store/Modules/fieldsTable.ts | 4 +- src/store/Modules/tools.ts | 9 + src/store/NotifStore.ts | 28 ++ src/store/UserStore.ts | 5 +- src/store/globalStore.ts | 22 +- src/views/user/myprofile/myprofile.vue | 2 +- 27 files changed, 411 insertions(+), 232 deletions(-) diff --git a/.env.development b/.env.development index 1b0aef03..4d78c3de 100755 --- a/.env.development +++ b/.env.development @@ -26,4 +26,5 @@ TELEGRAM_SUPPORT="" PROJECT_ID_MAIN="5cc0a13fe5c9d156728f400a" TEST_CELL="" ISTEST=1 +INLOCALE=1 BAK_MONGODB_HOST="http://192.168.0.200:3000" diff --git a/public/js/storage.js b/public/js/storage.js index 2b127be2..01c2051a 100755 --- a/public/js/storage.js +++ b/public/js/storage.js @@ -1,4 +1,4 @@ -const OtherTables = ['categories', 'config', 'swmsg'] +const OtherTables = ['categories', 'config', 'swmsg', 'notifications'] const MainTables = ['todos', 'projects'] const allMethod = ['sync_post_', 'sync_patch_', 'delete_'] @@ -13,7 +13,7 @@ let idbKeyval = (() => { if (!db) { // console.log('CREO DB STORAGE JS !') db = new Promise((resolve, reject) => { - const openreq = indexedDB.open('mydb3', 11); + const openreq = indexedDB.open('mydb3', 13); openreq.onerror = () => { reject(openreq.error); @@ -84,12 +84,19 @@ let idbKeyval = (() => { async getdata(table, key) { let req; + console.log('getdata', table, key) + await withStore('readonly', table, store => { // console.log('store', store, 'key', key) req = store.get(key); + // console.log(' req', req) }); - return req.result; + if (req) { + return req.result; + } else { + return null; + } }, async getalldata(table) { let req; diff --git a/src-pwa/custom-service-worker.js b/src-pwa/custom-service-worker.js index 86867dfa..3694d4e4 100755 --- a/src-pwa/custom-service-worker.js +++ b/src-pwa/custom-service-worker.js @@ -16,7 +16,7 @@ import { CacheableResponsePlugin } from 'workbox-cacheable-response' import { ExpirationPlugin } from 'workbox-expiration' console.log( - ' [ VER-0.1.2b ] _---------________------ PAO: this is my custom service worker') + ' [ VER-0.3.23b ] _---------________------ PAO: this is my custom service worker') importScripts('js/idb.js') importScripts('js/storage.js') @@ -24,6 +24,8 @@ importScripts('js/storage.js') importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.4/workbox-sw.js'); + + // importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js'); // importScripts('./ChabokSDKWorker.js', 'https://storage.googleapis.com/workbox-cdn/releases/5.0.0/workbox-sw.js'); @@ -43,7 +45,7 @@ const cfgenv = { // console.log('serverweb', cfgenv.serverweb) async function writeData (table, data) { - // console.log('writeData', table, data); + console.log('writeData', table, data); await idbKeyval.setdata(table, data) } @@ -350,152 +352,155 @@ if ('serviceWorker' in navigator) { } -// self.addEventListener('fetch', (event) => { -// if (event.request.url === '/') { -// const StaleWhileRevalidate = new StaleWhileRevalidate(); -// event.respondWith(StaleWhileRevalidate.handle({ event })); -// } -// }); +self.addEventListener('fetch', (event) => { + if (event.request.url === '/') { + const StaleWhileRevalidate = new StaleWhileRevalidate(); + event.respondWith(StaleWhileRevalidate.handle({ event })); + } +}); -// self.addEventListener('fetch', function (event) { -// console.log('[Service Worker] Fetching something ....', event); -// console.log('event.request.cache=', event.request.cache) -// if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') { -// console.log('SAME ORIGIN!', event); -// return; -// } -// event.respondWith(caches.match(event.request)); -// }); -// +self.addEventListener('fetch', function (event) { + console.log('[Service Worker] Fetching something ....', event); + console.log('event.request.cache=', event.request.cache) + if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') { + console.log('SAME ORIGIN!', event); + return; + } + event.respondWith(caches.match(event.request)); +}); -// const syncStore = {} -// self.addEventListener('message', event => { -// if (event.data.type === 'sync') { -// // get a unique id to save the data -// const id = uuid() -// syncStore[id] = event.data -// // register a sync and pass the id as tag for it to get the data -// self.registration.sync.register(id) -// } -// console.log(event.data) -// }) -// addEventListener('fetch', event => { -// // Prevent the default, and handle the request ourselves. -// event.respondWith(async function() { -// // Try to get the response from a cache. -// const cachedResponse = await caches.match(event.request); -// // Return it if we found one. -// if (cachedResponse && (event.request.cache !== 'no-cache')) -// return cachedResponse; -// -// // If we didn't find a match in the cache, use the network. -// return fetch(event.request); -// }()); -// }); +const syncStore = {} +self.addEventListener('message', event => { + if (event.data.type === 'sync') { + console.log('addEventListener - message') + // get a unique id to save the data + const id = uuid() + syncStore[id] = event.data + // register a sync and pass the id as tag for it to get the data + self.registration.sync.register(id) + console.log('self.registration.sync.register(id)') + } + console.log(event.data) +}) -// self.addEventListener('fetch', function (event) { -// event.respondWith( -// caches.match(event.request).then(function (response) { -// return response || -// fetch(event.request, event.headers) -// .catch(err => { -// console.log('_______________________ ERRORE FETCH SW: ', event.request, err) -// writeData('config', { _id: 2, stateconn: 'offline' }) -// return caches.match(event.request); -// }) -// }) -// ); -// }); +addEventListener('fetch', event => { + // Prevent the default, and handle the request ourselves. + event.respondWith(async function() { + // Try to get the response from a cache. + const cachedResponse = await caches.match(event.request); + // Return it if we found one. + if (cachedResponse && (event.request.cache !== 'no-cache')) + return cachedResponse; -// self.addEventListener('fetch', function (event) { -// event.respondWith( -// fetch(event.request, event.headers) -// .catch(err => { -// console.log('_______________________ ERRORE FETCH SW: ', event.request, err) -// writeData('config', {_id: 2, stateconn: 'offline'}) -// return caches.match(event.request); -// }) -// ); -// }); + // If we didn't find a match in the cache, use the network. + return fetch(event.request); + }()); +}); -// self.addEventListener('sync', function (event) { -// console.log('[Service Worker V5] Background syncing', event.tag); -// -// let mystrparam = event.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.............................................................'); -// -// event.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=') -// } -// } -// } -// }) -// ; +self.addEventListener('fetch', function (event) { + event.respondWith( + caches.match(event.request).then(function (response) { + return response || + fetch(event.request, event.headers) + .catch(err => { + console.log('_______________________ ERRORE FETCH SW: ', event.request, err) + writeData('config', { _id: 2, stateconn: 'offline' }) + return caches.match(event.request); + }) + }) + ); +}); + +self.addEventListener('fetch', function (event) { + event.respondWith( + fetch(event.request, event.headers) + .catch(err => { + console.log('_______________________ ERRORE FETCH SW: ', event.request, err) + writeData('config', {_id: 2, stateconn: 'offline'}) + return caches.match(event.request); + }) + ); +}); + +self.addEventListener('sync', function (event) { + console.log('[Service Worker V5] Background syncing', event); + console.log('event:', event); + + let mystrparam = event.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.............................................................'); + + event.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=') + } + } + } +}) +; /* @@ -565,28 +570,62 @@ self.addEventListener('push', (event) => { } try { + let isobj = false if (event.data) { try { data = JSON.parse(event.data.text()) + isobj = true } catch (e) { data = event.data.text() } } - const options = { - body: data.content, - icon: '/images/android-chrome-192x192.png', - badge: '/images/android-chrome-192x192.png', - data: { - url: data.url, - }, - tag: 'received', - renitify: true, // vibrate also with others messages. + console.log('event.data', data) + + let options = {} + + let myid = '0' + + if (isobj) { + if (data.id) { + myid = data.id + } + + options = { + body: data.content, + icon: data.icon ? data.icon : '/images/android-chrome-192x192.png', + badge: data.badge ? data.badge : '/images/android-chrome-192x192.png', + data: { + url: data.url, + }, + tag: data.tag, + renitify: true, // vibrate also with others messages. + } + + event.waitUntil( + self.registration.showNotification(data.title ? data.title : data.content, options), + ) + } else { + let text = data; + options = { + body: text, + icon: '/images/android-chrome-192x192.png', + badge: '/images/android-chrome-192x192.png', + data: { + url: '/', + }, + tag: 'notif', + renitify: true, // vibrate also with others messages. + } + + event.waitUntil( + self.registration.showNotification('', options), + ) } - event.waitUntil( - self.registration.showNotification(data.title, options), - ) + self.registration.sync.register(myid) + writeData('notifications', { _id: myid, tag: options.tag }) + } catch (e) { console.log('Error on event push:', e) } diff --git a/src/common/shared_vuejs.ts b/src/common/shared_vuejs.ts index d9ad9888..f60962a3 100755 --- a/src/common/shared_vuejs.ts +++ b/src/common/shared_vuejs.ts @@ -36,7 +36,7 @@ export const shared_consts = { FILTER_ASK_ZOOM_VISTO: 32768, FILTER_HOURS_MYLIST: 65536, FILTER_HOURS_ALL: 131072, - FILTER_MISSING_PAYMENT: 262144, + FILTER_REPORTED: 262144, FILTER_TO_MAKE_MEMBERSHIP_CARD: 524288, FILTER_MEMBERSHIP_CARD_OK: 1048576, FILTER_USER_NO_VERIFIED_APORTADOR: 2097152, diff --git a/src/components/CFundRaising/CFundRaising.ts b/src/components/CFundRaising/CFundRaising.ts index eaf8396f..fc2ddd3d 100755 --- a/src/components/CFundRaising/CFundRaising.ts +++ b/src/components/CFundRaising/CFundRaising.ts @@ -78,14 +78,6 @@ export default defineComponent({ } } - function getenv(myvar: any) { - try { - return process.env[myvar] - } catch (e) { - return '' - } - } - function getPermission() { return Notification.permission } @@ -123,7 +115,6 @@ export default defineComponent({ appname, meta, mystilecard, - getenv, getPermission, NotServiceWorker, PagLogin, diff --git a/src/components/CPhotosGallery/CPhotosGallery.ts b/src/components/CPhotosGallery/CPhotosGallery.ts index 8fc9b0a0..9f227937 100755 --- a/src/components/CPhotosGallery/CPhotosGallery.ts +++ b/src/components/CPhotosGallery/CPhotosGallery.ts @@ -131,10 +131,6 @@ export default defineComponent({ } } - function getenv(myvar: any) { - return process.env[myvar] - } - function initprompt() { window.addEventListener('beforeinstallprompt', function (event) { // console.log('******************************** beforeinstallprompt fired') @@ -232,7 +228,6 @@ export default defineComponent({ getappname, appname, mystilecard, - getenv, getPermission, NotServiceWorker, PagLogin, diff --git a/src/components/CPresentazione/CPresentazione.ts b/src/components/CPresentazione/CPresentazione.ts index e1c40bb4..0aaf294c 100755 --- a/src/components/CPresentazione/CPresentazione.ts +++ b/src/components/CPresentazione/CPresentazione.ts @@ -78,14 +78,6 @@ export default defineComponent({ } } - function getenv(myvar: any) { - try { - return process.env[myvar] - } catch (e) { - return '' - } - } - function getPermission() { return Notification.permission } @@ -123,7 +115,6 @@ export default defineComponent({ appname, meta, mystilecard, - getenv, getPermission, NotServiceWorker, PagLogin, diff --git a/src/globalroutines/index.ts b/src/globalroutines/index.ts index 2bf44ec6..2adcaea1 100755 --- a/src/globalroutines/index.ts +++ b/src/globalroutines/index.ts @@ -1,11 +1,11 @@ // import { useGlobalStore } from '@store/globalStore' -// import indexdb from './indexdb' + import indexdb from './indexdb' import { idbKeyval as storage } from '@src/js/storage' -export default async (cmd: string, table: string, data: any = null, id = '') => { +export default async (cmd: string, table: string, data: any = null, id: any = '') => { // const globalStore = useGlobalStore() // const descr = data !== null ? data.descr : '' diff --git a/src/globalroutines/indexdb.ts b/src/globalroutines/indexdb.ts index fc826a5c..ebef4b8c 100755 --- a/src/globalroutines/indexdb.ts +++ b/src/globalroutines/indexdb.ts @@ -6,13 +6,13 @@ import { useUserStore } from '@store/UserStore' import { useGlobalStore } from '@store/globalStore' import { idbKeyval as storage } from '../js/storage.js' -function writeConfigIndexDb(context: any, data: any) { +function writeConfigIndexDb(data: any) { // console.log('writeConfigIndexDb', data) storage.setdata('config', data) } -function saveConfigIndexDb(context: any) { +function saveConfigIndexDb() { const userStore = useUserStore() const data: ICfgData = { @@ -22,10 +22,10 @@ function saveConfigIndexDb(context: any) { userId: userStore.my._id, } - writeConfigIndexDb('config', data) + writeConfigIndexDb(data) } -async function readfromIndexDbToState(context: any, table: string) { +async function readfromIndexDbToState(table: string) { console.log('*** readfromIndexDbToState ***', table) return storage.getalldata(table) @@ -79,13 +79,13 @@ function consolelogpao(str: string, str2 = '', str3 = '') { // Todos.mutations.setTestpao(str + str2 + str3) } -export default async (context: any, cmd: string, table: string, datakey: any = null, id = '') => { +export default async (cmd: string, table: string, datakey: any = null, id: any = '') => { const globalStore = useGlobalStore() try { // console.log('TABLE', table, 'cmd', cmd) if (cmd === 'loadapp') { // ****** LOAD APP AL CARICAMENTO ! ******* - return saveConfigIndexDb(context) + return saveConfigIndexDb() } if (cmd === 'write') { if (globalStore) { @@ -94,7 +94,7 @@ export default async (context: any, cmd: string, table: string, datakey: any = n return await storage.setdata(table, datakey) } if (cmd === 'updatefromIndexedDbToState') { - return await readfromIndexDbToState(context, table) + return await readfromIndexDbToState(table) } if (cmd === 'readall') { if (globalStore) { @@ -104,7 +104,9 @@ export default async (context: any, cmd: string, table: string, datakey: any = n return await storage.getalldata(table) } if (cmd === 'count') { - return await storage.count(table) + let contatore = await storage.count(table) + // console.log('COUNT:', table, contatore) + return contatore } if (cmd === 'read') { if (globalStore) { diff --git a/src/js/storage.js b/src/js/storage.js index d82824ca..718ec8fe 100755 --- a/src/js/storage.js +++ b/src/js/storage.js @@ -8,7 +8,7 @@ export let idbKeyval = (() => { // console.log('CREO DB STORAGE JS !') db = new Promise((resolve, reject) => { // console.log('open mydb3') - const openreq = indexedDB.open('mydb3', 12); + const openreq = indexedDB.open('mydb3', 13); openreq.onerror = () => { reject(openreq.error); @@ -50,7 +50,7 @@ export let idbKeyval = (() => { return { async get(key) { let req; - withStore('readonly', 'keyval', store => { + await withStore('readonly', 'keyval', store => { req = store.get(key); }); return req.result; @@ -62,30 +62,49 @@ export let idbKeyval = (() => { async getdata(table, key) { let req; - withStore('readonly', table, store => { + + await withStore('readonly', table, store => { // console.log('getdata', table, key) req = store.get(key); + // console.log(' req', req) }); - return req.result; + if (req) { + console.log('getdata', table, key, req.result) + return req.result; + } else { + return null; + } }, async getalldata(table) { let req; - withStore('readonly', table, store => { + await withStore('readonly', table, store => { req = store.getAll(); + console.log(' req', req) }); - return req.result; + if (req) { + return req.result; + } else { + return null; + } }, async count(table) { let req; - withStore('readonly', table, store => { + await withStore('readonly', table, store => { req = store.count(); }); - return req.result; + + // console.log('req', req) + if (req) { + // console.log('COUNT:', table, req.result) + return req.result; + } else { + return 0; + } }, async set(key, value) { let req; - withStore('readwrite', 'keyval', store => { + await withStore('readwrite', 'keyval', store => { req = store.put(value, key); }); return req.result; @@ -94,7 +113,7 @@ export let idbKeyval = (() => { let req; // console.log('setdata', table, value) - withStore('readwrite', table, store => { + await withStore('readwrite', table, store => { req = store.put(value); }); return req.result; @@ -121,6 +140,7 @@ export let idbKeyval = (() => { // iOS add-to-homescreen is missing IDB, or at least it used to. // I haven't tested this in a while. if (!self.indexedDB) { + console.log('NO indexedDB') idbKeyval = { get: key => Promise.resolve(localStorage.getItem(key)), set: (key, val) => Promise.resolve(localStorage.setItem(key, val)), diff --git a/src/layouts/toolbar/notifPopover/notifPopover.ts b/src/layouts/toolbar/notifPopover/notifPopover.ts index b6fbe100..9570a1c5 100755 --- a/src/layouts/toolbar/notifPopover/notifPopover.ts +++ b/src/layouts/toolbar/notifPopover/notifPopover.ts @@ -21,6 +21,7 @@ import { shared_consts } from '@/common/shared_vuejs' import { useI18n } from '@/boot/i18n' import { useQuasar } from 'quasar' import { costanti } from '@costanti' +import { waitAndcheckPendingNotif } from '../../../store/Modules/ApiTables' const namespace = 'notifModule' @@ -50,6 +51,9 @@ export default defineComponent({ const userId = ref('') const open = ref(false) + const polling = ref( null) + const eseguipolling = ref(true) + const notifsel = ref({ dest: '', datenotif: new Date() @@ -61,6 +65,30 @@ export default defineComponent({ // // } + function checkIfArrivedSomeNotif() { + waitAndcheckPendingNotif() + + return true + } + + function checkifpolling() { + console.log('checkifpolling') + if (eseguipolling.value) { + if (!polling.value) { + console.log('esegui POLLING....') + polling.value = setInterval(() => { + checkIfArrivedSomeNotif() + }, 3000) + } + } + } + + function beforeDestroy() { + console.log('beforeDestroy') + if (polling.value) + clearInterval(polling.value) + } + watch(() => usernotifs.value, async (to: any, from: any) => { if (usernotifs.value) { @@ -152,6 +180,7 @@ export default defineComponent({ async function mounted() { myuser.value = userStore.my await refreshdata(userStore.my.username) + checkifpolling() } onMounted(mounted) @@ -177,7 +206,6 @@ export default defineComponent({ notifStore, show_all, t, - $q, username, userStore, } diff --git a/src/model/MessageStore.ts b/src/model/MessageStore.ts index 80c799ce..581c6ca3 100755 --- a/src/model/MessageStore.ts +++ b/src/model/MessageStore.ts @@ -77,7 +77,7 @@ export interface IMessage { read?: boolean deleted?: boolean status?: StatusMessage - options?: number + typesend?: number } export interface INotif { @@ -120,4 +120,5 @@ export interface INotifState { last_notifs: INotif[] show_all: boolean updateNotification: boolean + countNotif: number } diff --git a/src/rootgen/admin/userPanel/userPanel.vue b/src/rootgen/admin/userPanel/userPanel.vue index 91213123..5fd64d2c 100755 --- a/src/rootgen/admin/userPanel/userPanel.vue +++ b/src/rootgen/admin/userPanel/userPanel.vue @@ -2,7 +2,9 @@ -
+
+ +
@@ -65,7 +67,7 @@
-
+
username cercato: "{{ search }}"

diff --git a/src/rootgen/admin/usersList/usersList.ts b/src/rootgen/admin/usersList/usersList.ts index 1a7f890b..cbe41584 100755 --- a/src/rootgen/admin/usersList/usersList.ts +++ b/src/rootgen/admin/usersList/usersList.ts @@ -30,6 +30,10 @@ export default defineComponent({ label: 'Non hanno l\'Invitante', value: shared_consts.FILTER_USER_NO_INVITANTE }, + { + label: 'Segnalati', + value: shared_consts.FILTER_REPORTED + }, { label: 'No Approv. Invitante', value: shared_consts.FILTER_USER_NO_VERIFIED_APORTADOR diff --git a/src/statics/lang/it.js b/src/statics/lang/it.js index 20a5f92d..4fa634d9 100755 --- a/src/statics/lang/it.js +++ b/src/statics/lang/it.js @@ -415,6 +415,9 @@ const msg_it = { verified_by_aportador: 'Verificato', notAsk_ToVerify: 'No Verif. Reg', trust_modified: 'Fiducia Modificata', + reported: 'Segnalato', + username_who_reported: 'Segnal da', + date_reported: 'Data Segnal.', blocked: 'Bloccato', username_who_block: 'Bloccato da', username_regala_invitato: 'Username del Destinatario del regalo', diff --git a/src/store/Api/Inst-Pao.ts b/src/store/Api/Inst-Pao.ts index 93eb9e40..8136b00a 100755 --- a/src/store/Api/Inst-Pao.ts +++ b/src/store/Api/Inst-Pao.ts @@ -5,7 +5,7 @@ import { Api } from '@api' import * as Types from '@src/store/Api/ApiTypes' async function sendRequest(url: string, method: string, mydata: any) { - if (!process.env.DEBUG) console.log('sendRequest', method, url) + if (process.env.DEBUG) console.log('sendRequest', method, url) let request if (method === 'GET') request = Api.get(url, mydata) diff --git a/src/store/Api/Instance.ts b/src/store/Api/Instance.ts index d6187524..9636b0ae 100755 --- a/src/store/Api/Instance.ts +++ b/src/store/Api/Instance.ts @@ -7,7 +7,7 @@ import { useUserStore } from '@store/UserStore' import { tools } from '@src/store/Modules/tools' import * as Types from './ApiTypes' -export let API_URL = process.env.MONGODB_HOST +export let API_URL = '' export const axiosInstance: AxiosInstance = axios.create({ baseURL: API_URL, headers: { @@ -18,14 +18,14 @@ export const axiosInstance: AxiosInstance = axios.create({ axiosInstance.interceptors.response.use( (response) => { - if (process.env.DEBUG === '1') console.log(response) + if (process.env.DEBUGGING === '1') console.log(response) return response }, (error) => { const globalStore = useGlobalStore() // console.log('error', error) if (error.response) { - if (process.env.DEBUG === '1') console.log('Status = ', error.response.status) + if (process.env.DEBUGGING === '1') console.log('Status = ', error.response.status) console.log('Request Error: ', error.response) if (error.response.status !== 0) { globalStore.setStateConnection('online') diff --git a/src/store/Api/index.ts b/src/store/Api/index.ts index 63088756..b44414fb 100755 --- a/src/store/Api/index.ts +++ b/src/store/Api/index.ts @@ -92,7 +92,7 @@ export const Api = { idapp: process.env.APP_ID, } - console.log('INIZIO - SendReq', url) + // console.log('INIZIO - SendReq', url) // console.log('mydata', mydata) const userStore = useUserStore() @@ -145,7 +145,7 @@ export const Api = { }, async syncAlternative(mystrparam: string) { - // console.log('[ALTERNATIVE Background syncing', mystrparam) + console.log('[ALTERNATIVE Background syncing', mystrparam) const multiparams = mystrparam.split('|') if (multiparams) { diff --git a/src/store/MessageStore.ts b/src/store/MessageStore.ts index be5c8faa..c545710a 100755 --- a/src/store/MessageStore.ts +++ b/src/store/MessageStore.ts @@ -106,8 +106,8 @@ export const useMessageStore = defineStore('MessageStore', { data.datemsg = tools.getDateNow() data.status = StatusMessage.WaitingToSend // Options - data.options = tools.SetBit(data.options, shared_consts.MessageOptions.Notify_ByEmail) - data.options = tools.SetBit(data.options, shared_consts.MessageOptions.Notify_ByPushNotification) + data.typesend = tools.SetBit(data.typesend, shared_consts.MessageOptions.Notify_ByEmail) + data.typesend = tools.SetBit(data.typesend, shared_consts.MessageOptions.Notify_ByPushNotification) // console.log('DOPO:') // console.table(data) diff --git a/src/store/Modules/ApiTables.ts b/src/store/Modules/ApiTables.ts index c2291fd7..3ac60749 100755 --- a/src/store/Modules/ApiTables.ts +++ b/src/store/Modules/ApiTables.ts @@ -9,12 +9,12 @@ import { useGlobalStore } from '@store/globalStore' import globalroutines from '../../globalroutines/index' import { useProjectStore } from '@store/Projects' import { useTodoStore } from '@store/Todos' +import { useNotifStore } from '@store/NotifStore' export function getLinkByTableName(nametable: string) { if (nametable === 'todos') { return 'todos' - } - if (nametable === 'projects') { + } else if (nametable === 'projects') { return 'projects' } return '' @@ -34,13 +34,13 @@ export const DB = { } export function allTables() { - /* const myarr = OtherTables - for (const tab of costanti.MainTables) { - for (const method of costanti.allMethod) { + const myarr = OtherTables + for (const tab of MainTables) { + for (const method of allMethod) { myarr.push(method + tab) } - } */ - return costanti.OtherTables + } + return myarr } async function updatefromIndexedDbToState(nametab: string) { @@ -52,7 +52,7 @@ async function updatefromIndexedDbToState(nametab: string) { } async function checkPendingMsg() { - // console.log('checkPendingMsg') + console.log('checkPendingMsg') const globalStore = useGlobalStore() const config = await globalroutines('read', 'config', null, '1') @@ -82,8 +82,26 @@ async function checkPendingMsg() { }).catch(() => reject())) } +async function checkPendingNotif() { + + const notifStore = useNotifStore() + + const howmanybefore = notifStore.countNotif + + // eslint-disable-next-line @typescript-eslint/no-misused-promises + return new Promise((resolve, reject) => globalroutines('count', 'notifications') + .then((count) => { + if (count !== howmanybefore) { + notifStore.setCountNotifs(count) + return resolve(true) + } + return resolve(false) + }).catch(() => reject())) +} + function useServiceWorker() { - return false // return 'serviceWorker' in navigator + return 'serviceWorker' in navigator + // return false // } // If something in the call of Service Worker went wrong (Network or Server Down), then retry ! @@ -99,7 +117,7 @@ async function sendSwMsgIfAvailable() { .then(() => globalroutines('readall', 'swmsg') .then((arr_recmsg) => { if (arr_recmsg.length > 0) { - // console.log('---------------------- 2) navigator (2) .serviceWorker.ready') + console.log('---------------------- 2) navigator (2) .serviceWorker.ready') let promiseChain = Promise.resolve() for (const rec of arr_recmsg) { @@ -130,6 +148,14 @@ export async function waitAndRefreshData() { return await todos.dbLoad({ checkPending: false }) } +export function waitAndRefreshNotif() { + + const notifStore = useNotifStore() + + notifStore.updateNotification = true +} + + export async function waitAndcheckPendingMsg() { // await aspettansec(1000) const globalStore = useGlobalStore() @@ -157,6 +183,21 @@ export async function waitAndcheckPendingMsg() { }) } +export async function waitAndcheckPendingNotif() { + // await aspettansec(1000) + const globalStore = useGlobalStore() + + return checkPendingNotif() + .then((ris) => { + if (ris) { + if (globalStore.isOnline()) { // If is Offline, then check + return waitAndRefreshNotif() + } + } + }) +} + + async function dbInsertSave(call: string, item: any, method: string) { let ret = true const userStore = useUserStore() diff --git a/src/store/Modules/costanti.ts b/src/store/Modules/costanti.ts index 6b9be451..602e03df 100755 --- a/src/store/Modules/costanti.ts +++ b/src/store/Modules/costanti.ts @@ -231,7 +231,7 @@ export const costanti = { MAX_PHASES: 5, - OtherTables: ['config', 'swmsg'], + OtherTables: ['config', 'swmsg', 'notifications'], // export const MainTables = ['todos', 'projects'] MainTables: [], allMethod: ['sync_post_', 'sync_patch_', 'delete_', 'hide_'], diff --git a/src/store/Modules/fieldsTable.ts b/src/store/Modules/fieldsTable.ts index 3c75fc86..dcf85ef6 100755 --- a/src/store/Modules/fieldsTable.ts +++ b/src/store/Modules/fieldsTable.ts @@ -2156,8 +2156,8 @@ export const colTableUsersISP = [ AddCol({ name: 'username_who_block', label_trans: 'reg.username_who_block' }), AddCol({ name: 'date_blocked', label_trans: 'reg.date_blocked', fieldtype: costanti.FieldType.date }), AddCol({ name: 'reported', label_trans: 'reg.reported', fieldtype: costanti.FieldType.boolean }), - AddCol({ name: 'username_who_reported', label_trans: 'reg.username_who_reported' }), - AddCol({ name: 'date_reported', label_trans: 'reg.date_reported', fieldtype: costanti.FieldType.date }), + AddCol({ name: 'username_who_report', label_trans: 'reg.username_who_reported' }), + AddCol({ name: 'date_report', label_trans: 'reg.date_reported', fieldtype: costanti.FieldType.date }), AddCol({ name: 'profile.resplist', field: 'profile', diff --git a/src/store/Modules/tools.ts b/src/store/Modules/tools.ts index 1fc75e8b..6643ca15 100644 --- a/src/store/Modules/tools.ts +++ b/src/store/Modules/tools.ts @@ -56,6 +56,7 @@ export const tools = { TABBED_HOME: 't-home', TABBED_NAVE: 't-nave', + FILTER_ALL: 0, FILTER_MYREC: 1, FILTER_MYFOLLOW: 2, @@ -5627,6 +5628,14 @@ export const tools = { } }, + getEnv(name: string) { + const config: any = { + // @ts-ignore + VUE_APP_BACKEND_API_URL: window?.appConfig?.VUE_APP_BACKEND_API_URL || process.env.VUE_APP_BACKEND_API_URL + } + + return config[name]; + }, // getLocale() { // if (navigator.languages && navigator.languages.length > 0) { diff --git a/src/store/NotifStore.ts b/src/store/NotifStore.ts index ebdf0f8d..fa677b98 100755 --- a/src/store/NotifStore.ts +++ b/src/store/NotifStore.ts @@ -14,6 +14,7 @@ export const useNotifStore = defineStore('NotifStore', { last_notifs: [], show_all: true, updateNotification: false, + countNotif: 0, }), getters: { @@ -32,11 +33,17 @@ export const useNotifStore = defineStore('NotifStore', { }, actions: { + updateArrNotif() { + this.setBadgeIconApp() + }, + setNotif(notif: INotif) { console.log('setNotif', notif) if (notif) { this.last_notifs = [notif, ...this.last_notifs] } + this.updateArrNotif() + }, setAsRead(idnotif: string) { @@ -44,6 +51,18 @@ export const useNotifStore = defineStore('NotifStore', { if (rec) { rec.read = true } + + this.updateArrNotif() + }, + + async setBadgeIconApp(){ + // Get our dummy count and update it, + // just to give more context for this demo. + const countNow = this.getnumNotifUnread() + + // @ts-ignore + await navigator.setAppBadge(countNow) + .catch((error: any) => { /* ... */ }); }, setAllRead(username: string) { @@ -55,6 +74,7 @@ export const useNotifStore = defineStore('NotifStore', { rec.read = true } } + this.updateArrNotif() }) .catch((error) => { @@ -71,6 +91,7 @@ export const useNotifStore = defineStore('NotifStore', { this.last_notifs = this.last_notifs.filter((rec) => rec._id !== id) } + this.updateArrNotif() }) .catch((error) => { console.error(error) @@ -85,6 +106,7 @@ export const useNotifStore = defineStore('NotifStore', { // console.log('res', res) if (res) { this.last_notifs = [] + this.updateArrNotif() } }) @@ -110,6 +132,7 @@ export const useNotifStore = defineStore('NotifStore', { } else { this.last_notifs = [] } + this.updateArrNotif() return true }) .catch((error) => { @@ -157,5 +180,10 @@ export const useNotifStore = defineStore('NotifStore', { return false }) }, + + setCountNotifs(num: number) { + this.countNotif = num + }, }, + }) diff --git a/src/store/UserStore.ts b/src/store/UserStore.ts index 2198abcd..850bdd38 100755 --- a/src/store/UserStore.ts +++ b/src/store/UserStore.ts @@ -25,6 +25,8 @@ import { shared_consts } from '@/common/shared_vuejs' import { costanti } from '@costanti' import { IMyGroup } from '@model/UserStore' +import globalroutines from '../globalroutines/index' + export const DefaultUser: IUserFields = { _id: '', email: '', @@ -955,6 +957,7 @@ export const useUserStore = defineStore('UserStore', { return await this.setGlobal($router, isLogged) .then((loadstorage: any) => { + console.log('RISULT setGlobal:', loadstorage) if (loadstorage) { if ($q.screen.gt.sm) { @@ -969,7 +972,7 @@ export const useUserStore = defineStore('UserStore', { }*/ - //++Todo PWA: globalroutines('loadapp', '') + globalroutines('loadapp', '') // Create Subscription to Push Notification globalStore.createPushSubscription() diff --git a/src/store/globalStore.ts b/src/store/globalStore.ts index 643d65c2..97d1ab8c 100644 --- a/src/store/globalStore.ts +++ b/src/store/globalStore.ts @@ -564,6 +564,7 @@ export const useGlobalStore = defineStore('GlobalStore', { async createPushSubscription() { + // console.log('ENTER TO createPushSubscription') // If Already subscribed, don't send to the Server DB // if (state.wasAlreadySubOnDb) { // // console.log('wasAlreadySubOnDb!') @@ -574,10 +575,12 @@ export const useGlobalStore = defineStore('GlobalStore', { return if (!('serviceWorker' in navigator)) { + console.log('serviceWorker not present !') return } if (!('PushManager' in window)) { + console.log('PushManager not present !') return } @@ -1657,12 +1660,23 @@ export const useGlobalStore = defineStore('GlobalStore', { getServerHost() { - if (this.serverHost) { - return this.serverHost - } else { - return process.env.MONGODB_HOST + let myserv = '' + myserv = window.location.host + + if (process.env.DEBUGGING) { + myserv = 'http://192.168.1.54:3000' } + if (!myserv) { + if (this.serverHost) { + myserv = this.serverHost + } else { + myserv = process.env.MONGODB_HOST! + } + } + + return myserv + }, diff --git a/src/views/user/myprofile/myprofile.vue b/src/views/user/myprofile/myprofile.vue index 69997d55..2cf28d79 100755 --- a/src/views/user/myprofile/myprofile.vue +++ b/src/views/user/myprofile/myprofile.vue @@ -32,7 +32,7 @@
- +