diff --git a/src-pwa/custom-service-worker.js b/src-pwa/custom-service-worker.js index b296be7..f03c2e0 100644 --- a/src-pwa/custom-service-worker.js +++ b/src-pwa/custom-service-worker.js @@ -6,7 +6,7 @@ // Questo รจ il swSrc -console.log(' [ VER-0.0.17 ] _---------________-----------_________------------__________________________ PAO: this is my custom service worker'); +console.log(' [ VER-0.0.21 ] _---------________-----------_________------------__________________________ PAO: this is my custom service worker'); importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js'); //++Todo: Replace with local workbox.js importScripts('../statics/js/idb.js'); @@ -31,7 +31,7 @@ async function readAllData(table) { } async function clearAllData(table) { - // console.log('clearAllData', table); + console.log('clearAllData', table); await idbKeyval.clearalldata(table) } @@ -104,6 +104,7 @@ if (workbox) { // console.log('registerRoute!') // console.log('DATABODY:', args.event.request.body) let myres = null + // return fetch(args.event.request, args.event.headers) return fetch(args.event.request, args.event.headers) .then(function (res) { myres = res @@ -117,7 +118,7 @@ if (workbox) { } }) .then((clonedRes) => { - if (clonedRes !== null) + if (clonedRes !== undefined) return clonedRes.json(); return null }) @@ -141,6 +142,32 @@ if (workbox) { }) + 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).*$/), workbox.strategies.cacheFirst({ @@ -206,18 +233,18 @@ if (workbox) { }) ); -// 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(/^http/), + workbox.strategies.networkFirst({ + cacheName: 'all-stuff', + plugins: [ + new workbox.expiration.Plugin({ + maxAgeSeconds: 10 * 24 * 60 * 60, + // Only cache 10 requests. + }), + ] + }) + ); workbox.routing.registerRoute( @@ -234,15 +261,6 @@ if ('serviceWorker' in navigator) { } -self.addEventListener('fetch', function (event) { - event.respondWith( - fetch(event.request, event.headers) - .catch(err => { - console.log('_______________________ ERRORE FETCH SW: ', event.request, err) - return caches.match(event.request); - }) - ); -}); // self.addEventListener('fetch', (event) => { // if (event.request.url === '/') { @@ -260,7 +278,7 @@ self.addEventListener('fetch', function (event) { // } // event.respondWith(caches.match(event.request)); // }); - +// // const syncStore = {} // self.addEventListener('message', event => { @@ -274,6 +292,47 @@ self.addEventListener('fetch', function (event) { // 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); +// }()); +// }); + +// 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.tag); @@ -295,13 +354,14 @@ self.addEventListener('sync', function (event) { 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 ') + console.log('----------------------- LEGGO QUALCOSA DAL WAITUNTIL ') if (myrecs) { for (let rec of myrecs) { //console.log('syncing', table, '', rec.descr) @@ -312,7 +372,7 @@ self.addEventListener('sync', function (event) { console.log('++++++++++++++++++ SYNCING !!!! ', rec.descr, table, 'FETCH: ', method, link, 'data:') - console.log('DATATOSAVE:', JSON.stringify(rec)) + // console.log('DATATOSAVE:', JSON.stringify(rec)) // Insert/Delete/Update table to the server fetch(link, { @@ -322,19 +382,28 @@ self.addEventListener('sync', function (event) { body: JSON.stringify(rec) }) .then(() => { - console.log('DELETE SWMSG: ', mystrparam) + deleteItemFromData(table, rec._id) deleteItemFromData('swmsg', mystrparam) + + // console.log('config WRITE ONLINE') + writeData('config', { _id: 2, stateconn: 'online' }) }) .catch(function (err) { - console.log('DELETE : ', table, mystrparam) - deleteItemFromData(table, rec._id) + console.log('err', err, err.message) + // console.log('DELETE : ', table, mystrparam) + + if (err.message === 'Failed to fetch') { + // console.log('config WRITE OFFLINE') + writeData('config', { _id: 2, stateconn: 'offline' }) + } + console.log('!!!!!!!!!!!!!!! Error while sending data', err); }) } } }) ); - console.log('A2) ?????????????????????????? ESCO DAL LOOP !!!!!!!!! err=') + // console.log('A2) ?????????????????????????? ESCO DAL LOOP !!!!!!!!! err=') } } } diff --git a/src/components/Header.vue b/src/components/Header.vue index 7f14cd9..2b6b97c 100644 --- a/src/components/Header.vue +++ b/src/components/Header.vue @@ -182,10 +182,10 @@ } - create () { + mounted () { // Test this by running the code snippet below and then -// use the "Offline" checkbox in DevTools Network panel + // use the "Offline" checkbox in DevTools Network panel let mythis = this console.log('Event LOAD') @@ -195,12 +195,12 @@ function updateOnlineStatus(event) { if (navigator.onLine) { - console.log('ONLINE!') + console.log('EVENT ONLINE!') // handle online status GlobalStore.mutations.setStateConnection('online') mythis.changeIconConn() } else { - console.log('OFFLINE!') + console.log('EVENT OFFLINE!') // handle offline status GlobalStore.mutations.setStateConnection('offline') mythis.changeIconConn() diff --git a/src/components/offline/index.ts b/src/components/offline/index.ts new file mode 100644 index 0000000..35e7653 --- /dev/null +++ b/src/components/offline/index.ts @@ -0,0 +1 @@ +export {default as Offline} from './offline.vue' diff --git a/src/components/offline/offline.scss b/src/components/offline/offline.scss new file mode 100644 index 0000000..5307147 --- /dev/null +++ b/src/components/offline/offline.scss @@ -0,0 +1,29 @@ +.svgclass{ + color: white; + transform: translateY(0px); + +} + +.svgclass_animate { + transform: translateY(-70px); + color: red; +} + +#sun { + animation: gravity 5s infinite; + +} + +@keyframes gravity{ + 0%{ + transform: rotateY(0deg); + } + 100%{ + transform: rotateY(360deg); + } +} + +#smile{ + opacity: 0.1 !important; + fill: red; +} diff --git a/src/components/offline/offline.ts b/src/components/offline/offline.ts new file mode 100644 index 0000000..c76d173 --- /dev/null +++ b/src/components/offline/offline.ts @@ -0,0 +1,53 @@ +import Vue from 'vue' +import { Component } from 'vue-property-decorator' + +import { TimelineLite, Back } from 'gsap' + +import $ from 'jquery' +import Timeout = NodeJS.Timeout + +@Component({ + +}) +export default class Offline extends Vue { + logoimg: string = '' + + created() { + this.logoimg = 'statics/images/' + process.env.LOGO_REG + this.animate() + } + + animate () { + const timeline = new TimelineLite() + + /* + + let mysmile = $('#smile') + + mysmile.attr('class', 'smile_hide') + + setTimeout(() => { + mysmile.removeClass('smilevisible') + mysmile.addClass('smile_hide') + }, 1000) + + + setTimeout(() => { + mysmile.addClass('smilevisible') + mysmile.removeClass('smile_hide') + }, 10000) + + */ + + + /* + timeline.to('#smile', 5, { + cy: 20, + cx: 60, + ease: Back.easeInOut // Specify an ease + }) + */ + + } + +} diff --git a/src/components/offline/offline.vue b/src/components/offline/offline.vue new file mode 100644 index 0000000..21c6646 --- /dev/null +++ b/src/components/offline/offline.vue @@ -0,0 +1,11 @@ + + + + diff --git a/src/components/todos/SingleTodo/SingleTodo.ts b/src/components/todos/SingleTodo/SingleTodo.ts index 8d7ead8..1a0f6da 100644 --- a/src/components/todos/SingleTodo/SingleTodo.ts +++ b/src/components/todos/SingleTodo/SingleTodo.ts @@ -39,6 +39,7 @@ export default class SingleTodo extends Vue { public colProgress: string = 'blue' public togglemenu: boolean = false public percentageProgress: number = 0 + public itemtodoPrec: ITodo $q: any @Prop({ required: true }) itemtodo: ITodo @@ -292,6 +293,9 @@ export default class SingleTodo extends Vue { this.itemtodo.descr = this.precDescr console.log('updateTodo', this.precDescr, this.itemtodo.descr) + console.log('itemtodo', this.itemtodo) + console.log('Prec:', this.itemtodoPrec) + this.watchupdate() this.inEdit = false // this.precDescr = this.itemtodo.descr diff --git a/src/components/todos/SingleTodo/SingleTodo.vue b/src/components/todos/SingleTodo/SingleTodo.vue index 8be08c9..1c8a0ea 100644 --- a/src/components/todos/SingleTodo/SingleTodo.vue +++ b/src/components/todos/SingleTodo/SingleTodo.vue @@ -60,7 +60,7 @@ - + diff --git a/src/components/todos/todo/todo.ts b/src/components/todos/todo/todo.ts index 8d7b184..020485d 100644 --- a/src/components/todos/todo/todo.ts +++ b/src/components/todos/todo/todo.ts @@ -287,7 +287,7 @@ export default class Todo extends Vue { let update = false await this.todos_arr.forEach((elem: ITodo) => { if (elem.modified) { - // console.log('calling MODIFY 3') + console.log('calling MODIFY 3') this.modify(elem, false) update = true elem.modified = false @@ -448,17 +448,17 @@ export default class Todo extends Vue { cmdSw = rescodes.DB.CMD_SYNC_TODOS } - if (process.env.DEV) { - console.log('serviceWorker ', ('serviceWorker' in navigator) ? 'PRESENT!' : 'DOESN\'T EXIST!') - console.log('SyncManager ', ('SyncManager' in window) ? 'PRESENT!' : 'DOESN\'T EXIST!') - } + // if (process.env.DEV) { + // console.log('serviceWorker ', ('serviceWorker' in navigator) ? 'PRESENT!' : 'DOESN\'T EXIST!') + // console.log('SyncManager ', ('SyncManager' in window) ? 'PRESENT!' : 'DOESN\'T EXIST!') + // } const mythis = this if ('serviceWorker' in navigator) { await navigator.serviceWorker.ready .then(function (sw) { // _id: new Date().toISOString(), - console.log('---------------------- navigator.serviceWorker.ready') + // console.log('---------------------- navigator.serviceWorker.ready') // mythis.sendMessageToSW(item, method) @@ -469,20 +469,20 @@ export default class Todo extends Vue { }) const sep = '|' - let multiparams = cmdSw + sep + table + sep + method + sep + UserStore.state.idToken + sep + UserStore.state.lang + let multiparams = cmdSw + sep + table + sep + method + sep + UserStore.state.x_auth_token + sep + UserStore.state.lang let mymsgkey = { _id: multiparams, value: multiparams } globalroutines(mythis, 'write', 'swmsg', mymsgkey, multiparams) .then(ris => { - if ('SyncManager' in window) { - console.log(' SENDING... sw.sync.register', multiparams) - return sw.sync.register(multiparams) - } else { + // if ('SyncManager' in window) { + // console.log(' SENDING... sw.sync.register', multiparams) + // return sw.sync.register(multiparams) + // } else { // #Todo ++ Alternative 2 to SyncManager Api.syncAlternative(multiparams) - } + // } }) .then(function () { @@ -515,12 +515,12 @@ export default class Todo extends Vue { } async saveItemToSyncAndDb(table: String, method, item: ITodo, update: boolean) { - return await this.cmdToSyncAndDb(rescodes.DB.CMD_SYNC_NEW_TODOS, table, method, item, 0, 'Your Post was saved for syncing!', update) + return await this.cmdToSyncAndDb(rescodes.DB.CMD_SYNC_NEW_TODOS, table, method, item, 0, '', update) } deleteItemToSyncAndDb(table: String, item: ITodo, id, update: boolean) { - return this.cmdToSyncAndDb(rescodes.DB.CMD_DELETE_TODOS, table, 'DELETE', item, id, 'Your Post was canceled for syncing!', update) + return this.cmdToSyncAndDb(rescodes.DB.CMD_DELETE_TODOS, table, 'DELETE', item, id, '', update) } /* @@ -561,14 +561,14 @@ export default class Todo extends Vue { if (myobjprev !== null) { myobjprev.id_next = myobjtrov.id_next myobjprev.modified = true - // console.log('calling MODIFY 2') + console.log('calling MODIFY 2') this.modify(myobjprev, false) } if (myobjnext !== null) { myobjnext.id_prev = myobjtrov.id_prev myobjnext.modified = true - // console.log('calling MODIFY 1') + console.log('calling MODIFY 1') this.modify(myobjnext, false) } @@ -703,7 +703,7 @@ export default class Todo extends Vue { } updateitem(myobj) { - // console.log('updateitem') + console.log('calling MODIFY 4 updateitem') this.modify(myobj, true) } @@ -751,8 +751,10 @@ export default class Todo extends Vue { // } modifyField(recOut, recIn, field) { - if (recOut[field] !== recIn[field]) { - // console.log('*************** CAMPO ', field, 'MODIFICATO!', recOut[field]) + if (String(recOut[field]) !== String(recIn[field])) { + console.log('*************** CAMPO ', field, 'MODIFICATO!') + console.log(recOut[field]) + console.log(recIn[field]) recOut.modified = true recOut[field] = recIn[field] return true diff --git a/src/globalroutines/indexdb.js b/src/globalroutines/indexdb.js index 2a52c73..e647dce 100644 --- a/src/globalroutines/indexdb.js +++ b/src/globalroutines/indexdb.js @@ -1,4 +1,4 @@ -import store from '../store' +import store, { GlobalStore } from '../store' import _ from 'lodash' import { UserStore, Todos } from '@store' import { i18n } from '../plugins/i18n' @@ -10,7 +10,7 @@ function saveConfigIndexDb(context) { let data = [] data['_id'] = 1 data['lang'] = UserStore.state.lang - data['token'] = UserStore.state.idToken + data['token'] = UserStore.state.x_auth_token data['userId'] = UserStore.state.userId writeConfigIndexDb('config', data) diff --git a/src/js/storage.js b/src/js/storage.js index ead047a..64b4ffe 100644 --- a/src/js/storage.js +++ b/src/js/storage.js @@ -56,7 +56,7 @@ export let idbKeyval = (() => { let req; await withStore('readonly', table, store => { - // console.log('store', store, 'key', key) + console.log('getdata', table, key) req = store.get(key); }); @@ -86,6 +86,7 @@ export let idbKeyval = (() => { async setdata(table, value) { let req; + console.log('setdata', table, value) await withStore('readwrite', table, store => { req = store.put(value); }); @@ -102,6 +103,7 @@ export let idbKeyval = (() => { }); }, async clearalldata(table) { + console.log('clearalldata', table) return await withStore('readwrite', table, store => { store.clear(); }); diff --git a/src/model/GlobalStore.ts b/src/model/GlobalStore.ts index 8887aa0..a52a16c 100644 --- a/src/model/GlobalStore.ts +++ b/src/model/GlobalStore.ts @@ -13,7 +13,7 @@ export interface IGlobalState { menuCollapse: boolean leftDrawerOpen: boolean category: string - stateConnection: StateConnection + stateConnection: string posts: IPost[] listatodo: ITodoList[] } diff --git a/src/model/UserStore.ts b/src/model/UserStore.ts index b604466..3e483e8 100644 --- a/src/model/UserStore.ts +++ b/src/model/UserStore.ts @@ -17,8 +17,6 @@ export interface IUserState { lang?: string repeatPassword?: string - idToken?: string - tokens?: IToken[] verified_email?: boolean diff --git a/src/model/other.ts b/src/model/other.ts index c7c5a3c..dc9e839 100644 --- a/src/model/other.ts +++ b/src/model/other.ts @@ -10,7 +10,7 @@ export interface ILinkReg { } export interface IIdToken { - idToken: string + x_auth_token: string } export interface IResult { diff --git a/src/router/route-config.ts b/src/router/route-config.ts index cdd182e..17cf55f 100644 --- a/src/router/route-config.ts +++ b/src/router/route-config.ts @@ -34,6 +34,11 @@ export const RouteConfig: VueRouteConfig[] = [ path: '/category', component: () => import('@/components/categories/category/category.vue'), meta: { name: 'Categories' } + }, + { + path: '/offline', + component: () => import('@/components/offline/offline.vue'), + meta: { name: 'Offline' } } /* { diff --git a/src/statics/js/storage.js b/src/statics/js/storage.js index 505a0aa..8dcbc4b 100644 --- a/src/statics/js/storage.js +++ b/src/statics/js/storage.js @@ -105,6 +105,7 @@ let idbKeyval = (() => { }); }, async clearalldata(table) { + console.log('clearalldata', table) return await withStore('readwrite', table, store => { store.clear(); }); diff --git a/src/store/Api/Inst-Pao.ts b/src/store/Api/Inst-Pao.ts index 1fd4da2..6afdf65 100644 --- a/src/store/Api/Inst-Pao.ts +++ b/src/store/Api/Inst-Pao.ts @@ -7,7 +7,10 @@ async function sendRequest(url: string, lang: string, mytok: string, method: str const authHeader = new Headers() authHeader.append('content-Type', 'application/json') authHeader.append('Accept', 'application/json') - authHeader.append('x-auth', mytok) + if (url !== process.env.MONGODB_HOST + '/users/login') { + authHeader.append('x-auth', mytok) + console.log('TOK PASSATO ALLA FETCH:', mytok) + } // authHeader.append('accept-language', lang) let configInit: RequestInit diff --git a/src/store/Api/index.ts b/src/store/Api/index.ts index 6c1f9fe..7ab6b24 100644 --- a/src/store/Api/index.ts +++ b/src/store/Api/index.ts @@ -47,14 +47,13 @@ export namespace ApiTool { }) } - export async function SendReq(url: string, lang: string, mytok: string, method: string, mydata: any, setAuthToken: boolean = false) { + export async function SendReq(url: string, method: string, mydata: any, setAuthToken: boolean = false) { UserStore.mutations.setServerCode(rescodes.EMPTY) UserStore.mutations.setResStatus(0) - UserStore.mutations.setAuth('') return await new Promise(function (resolve, reject) { let ricevuto = false - return sendRequest(url, lang, mytok, method, mydata) + return sendRequest(url, UserStore.state.lang, UserStore.state.x_auth_token, method, mydata) .then(resreceived => { console.log('resreceived', resreceived) ricevuto = true @@ -76,7 +75,7 @@ export namespace ApiTool { UserStore.mutations.setAuth(x_auth_token) if (url === process.env.MONGODB_HOST + '/updatepwd') { - UserStore.mutations.UpdatePwd({ idToken: x_auth_token }) + UserStore.mutations.UpdatePwd({ x_auth_token }) localStorage.setItem(rescodes.localStorage.token, x_auth_token) } } @@ -88,7 +87,7 @@ export namespace ApiTool { UserStore.mutations.setAuth('') } GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline') - return reject({ code: rescodes.ERR_AUTHENTICATION, status: res.status }) + return reject({ code: rescodes.ERR_AUTHENTICATION }) } } else if (res.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) { // Forbidden @@ -97,17 +96,17 @@ export namespace ApiTool { UserStore.mutations.setAuth('') GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline') router.push('/signin') - return reject({ code: rescodes.ERR_AUTHENTICATION, status: res.status }) + return reject({ code: rescodes.ERR_AUTHENTICATION }) } GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline') return res.json() .then((body) => { - return resolve({ res, body }) + return resolve({ res, body, status: res.status }) }) .catch(e => { - return resolve({ res, body: {} }) + return resolve({ res, body: {}, status: res.status }) // Array not found... // UserStore.mutations.setServerCode(rescodes.ERR_GENERICO) // return reject({ code: rescodes.ERR_GENERICO, status: res.status }) @@ -126,7 +125,7 @@ export namespace ApiTool { GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline') - return reject({ code: error, status: 0 }) + return reject({ code: error }) }) }) } @@ -169,7 +168,7 @@ export namespace ApiTool { let lettoqualcosa = false // Insert/Delete/Update table to the server - return fetch(link, { + fetch(link, { method: method, headers: headers, cache: 'no-cache', @@ -178,16 +177,20 @@ export namespace ApiTool { }).then(resData => { lettoqualcosa = true - console.log('Clear', table, rec._id) - return globalroutines(null, 'delete', table, null, rec._id) - }) + return globalroutines(null, 'delete', 'swmsg', null, mystrparam) + }).then(() => globalroutines(null, 'delete', table, null, rec._id)) .then((ris) => { - console.log('Clear', 'swmsg', method) + return globalroutines(null, 'write', 'config', { _id: 2, stateconn: 'online' }) + }) + .then(() => { + // console.log('Clear', 'swmsg', method) GlobalStore.mutations.setStateConnection(lettoqualcosa ? 'online' : 'offline') - // deleteItemFromData('swmsg', mystrparam) - return globalroutines(null, 'delete', 'swmsg', null, mystrparam) }) .catch(function (err) { + if (err.message === 'Failed to fetch') { + // console.log('config WRITE OFFLINE') + globalroutines(null, 'write', 'config', { _id: 2, stateconn: 'offline' }) + } console.log(' [Alternative] !!!!!!!!!!!!!!! Error while sending data', err) GlobalStore.mutations.setStateConnection(lettoqualcosa ? 'online' : 'offline') }) diff --git a/src/store/Modules/GlobalStore.ts b/src/store/Modules/GlobalStore.ts index 729fdec..7d147ad 100644 --- a/src/store/Modules/GlobalStore.ts +++ b/src/store/Modules/GlobalStore.ts @@ -12,6 +12,23 @@ import { UserStore } from '@store' import globalroutines from './../../globalroutines/index' const allTables = ['todos', 'sync_todos', 'sync_todos_patch', 'delete_todos', 'config', 'swmsg'] +const allTablesAfterLogin = ['todos', 'sync_todos', 'sync_todos_patch', 'delete_todos', 'config', 'swmsg'] + +async function getstateConnSaved() { + const config = await globalroutines(null, 'readall', 'config', null) + if (config.length > 1) { + return config[1].stateconn + } else { + return 'online' + } +} + +let stateConnDefault = 'online' + +getstateConnSaved() + .then(conn => { + stateConnDefault = conn + }) const state: IGlobalState = { conta: 0, @@ -21,16 +38,17 @@ const state: IGlobalState = { mobileMode: false, menuCollapse: true, leftDrawerOpen: true, - stateConnection: 'online', + stateConnection: stateConnDefault, category: 'personal', posts: [], listatodo: [ - {namecat: 'personal', description: 'personal'}, - {namecat: 'work', description: 'work'}, - {namecat: 'shopping', description: 'shopping'} - ] + { namecat: 'personal', description: 'personal' }, + { namecat: 'work', description: 'work' }, + { namecat: 'shopping', description: 'shopping' } + ] } + const b = storeBuilder.module('GlobalModule', state) // Getters @@ -51,6 +69,10 @@ namespace Getters { get category() { return category() + }, + + get isOnline() { + return state.stateConnection === 'online' } } } @@ -95,6 +117,10 @@ namespace Actions { return } + if (!('PushManager' in window)) { + return + } + console.log('createPushSubscription') let reg @@ -123,7 +149,12 @@ namespace Actions { // console.log('newSub', newSub) if (newSub) { saveNewSubscriptionToServer(context, newSub) - mystate.isSubscribed = true + .then(ris => { + mystate.isSubscribed = true + }) + .catch(e => { + console.log('Error during Subscription!', e) + }) } return null }) @@ -147,7 +178,8 @@ namespace Actions { options: { ...options }, subs: newSub, others: { - userId: UserStore.state.userId + userId: UserStore.state.userId, + access: UserStore.state.tokens[0].access } } @@ -163,6 +195,20 @@ namespace Actions { } + async function deleteSubscriptionToServer(context) { + console.log('DeleteSubscriptionToServer: ') + + return await fetch(process.env.MONGODB_HOST + '/subscribe/del', { + method: 'DELETE', + headers: { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + 'x-auth': UserStore.state.x_auth_token + } + }) + + } + function t(params) { let msg = params.split('.') let lang = UserStore.state.lang @@ -186,17 +232,48 @@ namespace Actions { } - async function clearDataAfterLogout (context) { + async function clearDataAfterLogout(context) { + console.log('clearDataAfterLogout') // Clear all data from the IndexedDB - allTables.forEach(table => { + await allTables.forEach(table => { globalroutines(null, 'clearalldata', table, null) }) + // REMOVE ALL SUBSCRIPTION + console.log('REMOVE ALL SUBSCRIPTION...') + await navigator.serviceWorker.ready.then(function(reg) { + console.log('... Ready') + reg.pushManager.getSubscription().then(function(subscription) { + console.log(' Found Subscription...') + subscription.unsubscribe().then(function(successful) { + // You've successfully unsubscribed + console.log('You\'ve successfully unsubscribed') + }).catch(function(e) { + // Unsubscription failed + }) + }) + }) + + await deleteSubscriptionToServer(context) + } - async function loadAfterLogin (context) { - actions.clearDataAfterLogout() + async function clearDataAfterLoginOnlyIfActiveConnection(context) { + + // if (Getters.getters.isOnline) { + // console.log('clearDataAfterLoginOnlyIfActiveConnection') + // // Clear all data from the IndexedDB + // allTablesAfterLogin.forEach(table => { + // globalroutines(null, 'clearalldata', table, null) + // }) + // } + + } + + + async function loadAfterLogin(context) { + actions.clearDataAfterLoginOnlyIfActiveConnection() } @@ -205,6 +282,7 @@ namespace Actions { createPushSubscription: b.dispatch(createPushSubscription), loadAfterLogin: b.dispatch(loadAfterLogin), clearDataAfterLogout: b.dispatch(clearDataAfterLogout), + clearDataAfterLoginOnlyIfActiveConnection: b.dispatch(clearDataAfterLoginOnlyIfActiveConnection), prova: b.dispatch(prova) } diff --git a/src/store/Modules/Todos.ts b/src/store/Modules/Todos.ts index e15ed32..194801c 100644 --- a/src/store/Modules/Todos.ts +++ b/src/store/Modules/Todos.ts @@ -5,8 +5,8 @@ import Api from '@api' import { rescodes } from './rescodes' import { GlobalStore, Todos, UserStore } from '@store' import globalroutines from './../../globalroutines/index' -import { Mutation } from "vuex-module-decorators" -import { serv_constants } from "@src/store/Modules/serv_constants" +import { Mutation } from 'vuex-module-decorators' +import { serv_constants } from '@src/store/Modules/serv_constants' const state: ITodosState = { @@ -74,7 +74,7 @@ namespace Actions { let something = false if ('serviceWorker' in navigator) { - // console.log(' -------- sendSwMsgIfAvailable') + console.log(' -------- sendSwMsgIfAvailable') let count = await checkPendingMsg(null) if (count > 0) { @@ -86,19 +86,19 @@ namespace Actions { // let recclone = [...arr_recmsg] if (arr_recmsg.length > 0) { - console.log(' TROVATI MSG PENDENTI ! ORA LI MANDO: ', arr_recmsg) + // console.log(' TROVATI MSG PENDENTI ! ORA LI MANDO: ', arr_recmsg) // console.log('---------------------- 2) navigator (2) .serviceWorker.ready') something = true for (let rec of arr_recmsg) { - console.log(' .... sw.sync.register ( ', rec._id) - if ('SyncManager' in window) { - sw.sync.register(rec._id) - } else { + // console.log(' .... sw.sync.register ( ', rec._id) + // if ('SyncManager' in window) { + // sw.sync.register(rec._id) + // } else { // #Todo ++ Alternative to SyncManager Api.syncAlternative(rec._id) - } + // } } return something } @@ -115,12 +115,10 @@ namespace Actions { await aspettansec(1000) - // console.log('waitAndcheckPendingMsg') - return await checkPendingMsg(context) .then(ris => { if (ris) { - console.log('ris = ', ris) + console.log('risPending = ', ris) const result = sendSwMsgIfAvailable() .then(something => { if (something) { @@ -136,14 +134,30 @@ namespace Actions { async function waitAndRefreshData(context) { await aspettansec(3000) - // console.log('waitAndRefreshData') - return await dbLoadTodo(context, false) } async function checkPendingMsg(context) { // console.log('checkPendingMsg') + const config = await globalroutines(null, 'readall', 'config', null) + // console.log('config', config) + + try { + if (config) { + if (config[1].stateconn !== undefined) { + // console.log('config.stateconn', config[1].stateconn) + + if (config[1].stateconn !== GlobalStore.state.stateConnection) { + GlobalStore.mutations.setStateConnection(config[1].stateconn) + } + + } + } + } catch (e) { + + } + return new Promise(function (resolve, reject) { /* @@ -173,45 +187,49 @@ namespace Actions { async function dbLoadTodo(context, checkPending: boolean = false) { console.log('dbLoadTodo', checkPending) - const token = UserStore.state.idToken + if (UserStore.state.userId === '') + return false // Login not made let call = process.env.MONGODB_HOST + '/todos/' + UserStore.state.userId state.networkDataReceived = false - let ris = await Api.SendReq(call, UserStore.state.lang, token, 'GET', null) - .then(({ resData, body }) => { + let ris = await Api.SendReq(call, 'GET', null) + .then(({ resData, body, status }) => { state.networkDataReceived = true // console.log('******* UPDATE TODOS.STATE.TODOS !:', resData.todos) - state.todos = [...body.todos] - Todos.mutations.setTodos_changed() + if (body.todos) { + state.todos = [...body.todos] + Todos.mutations.setTodos_changed() + } console.log('********** resData', resData, 'state.todos', state.todos, 'checkPending', checkPending) // After Login will store into the indexedDb... - return rescodes.OK + return { status } }) - .catch((error) => { + .catch(error => { console.log('error=', error) UserStore.mutations.setErrorCatch(error) - return UserStore.getters.getServerCode + return { status } }) - console.log('ris FUNZ: ', ris.code, 'status', ris.status) + console.log('ris : ', ris) + console.log('ris STATUS: ', ris.status) if (!Todos.state.networkDataReceived) { if (ris.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) { consolelogpao('UNAUTHORIZING... TOKEN EXPIRED... !! ') } else { - consolelogpao('NETWORK UNREACHABLE ! (Error in fetch)', UserStore.getters.getServerCode, ris.code) + consolelogpao('NETWORK UNREACHABLE ! (Error in fetch)', UserStore.getters.getServerCode, ris.status) } // Read all data from IndexedDB Store into Memory await updateArrayInMemory(context) } else { - if (ris.code === rescodes.OK && checkPending) { + if (ris.status === rescodes.OK && checkPending) { waitAndcheckPendingMsg(context) } } @@ -273,14 +291,15 @@ namespace Actions { console.log('dbInsertSaveTodo', itemtodo, method) let call = process.env.MONGODB_HOST + '/todos' + if (UserStore.state.userId === '') + return false // Login not made + if (method !== 'POST') call += '/' + itemtodo._id - const token = UserStore.state.idToken - console.log('TODO TO SAVE: ', itemtodo) - let res = await Api.SendReq(call, UserStore.state.lang, token, method, itemtodo) + let res = await Api.SendReq(call, method, itemtodo) .then(({ res, newItem }) => { console.log('dbInsertSaveTodo RIS =', newItem) if (newItem) { @@ -301,9 +320,10 @@ namespace Actions { // console.log('dbDeleteTodo', item) let call = process.env.MONGODB_HOST + '/todos/' + item._id - const token = UserStore.state.idToken + if (UserStore.state.userId === '') + return false // Login not made - let res = await Api.SendReq(call, UserStore.state.lang, token, 'DELETE', item) + let res = await Api.SendReq(call, 'DELETE', item) .then(function ({ res, itemris }) { if (res.status === 200) { diff --git a/src/store/Modules/UserStore.ts b/src/store/Modules/UserStore.ts index 892e6b6..da8f436 100644 --- a/src/store/Modules/UserStore.ts +++ b/src/store/Modules/UserStore.ts @@ -1,6 +1,6 @@ import Api from '@api' import { ISignupOptions, ISigninOptions, IUserState } from 'model' -import { ILinkReg, IResult, IIdToken } from 'model/other' +import { ILinkReg, IResult, IIdToken, IToken } from 'model/other' import { storeBuilder } from './Store/Store' import router from '@router' @@ -22,7 +22,6 @@ const state: IUserState = { password: '', lang: '', repeatPassword: '', - idToken: '', tokens: [], verified_email: false, categorySel: 'personal', @@ -44,17 +43,17 @@ namespace Getters { } }, 'lang') - const tok = b.read(state => { - if (state.tokens) { - if (typeof state.tokens[0] !== 'undefined') { - return state.tokens[0].token - } else { - return '' - } - } else { - return '' - } - }, 'tok') + // const tok = b.read(state => { + // if (state.tokens) { + // if (typeof state.tokens[0] !== 'undefined') { + // return state.tokens[0].token + // } else { + // return '' + // } + // } else { + // return '' + // } + // }, 'tok') const isServerError = b.read(state => { return (state.servercode === rescodes.ERR_SERVERFETCH) @@ -68,9 +67,9 @@ namespace Getters { get lang() { return lang() }, - get tok() { - return tok() - }, + // get tok() { + // return tok() + // }, get isServerError() { return isServerError() }, @@ -87,13 +86,11 @@ namespace Mutations { function authUser(state, data: IUserState) { state.userId = data.userId state.username = data.username - state.idToken = data.idToken state.verified_email = data.verified_email state.category = data.categorySel - // @ts-ignore - state.tokens = [ - { access: 'auth ' + navigator.userAgent, token: data.idToken, date_login: new Date() } - ] + resetArrToken(state.tokens) + state.tokens.push({ access: 'auth ' + navigator.userAgent, token: state.x_auth_token, date_login: new Date() }) + console.log('state.tokens', state.tokens) } function setpassword(state: IUserState, newstr: string) { @@ -110,11 +107,11 @@ namespace Mutations { } function UpdatePwd(state: IUserState, data: IIdToken) { - state.idToken = data.idToken + state.x_auth_token = data.x_auth_token if (!state.tokens) { state.tokens = [] } - state.tokens.push({ access: 'auth ' + navigator.userAgent, token: data.idToken, data_login: new Date() }) + state.tokens.push({ access: 'auth ' + navigator.userAgent, token: data.x_auth_token, data_login: new Date() }) } function setServerCode(state: IUserState, num: number) { @@ -126,14 +123,27 @@ namespace Mutations { } function setAuth(state: IUserState, x_auth_token: string) { + state.x_auth_token = x_auth_token } + + function resetArrToken(arrtokens) { + if (!arrtokens.tokens) { + arrtokens.tokens = [] + } + + // Take only the others access (from others Browser) + return arrtokens.filter((token: IToken) => { + return token.access !== 'auth ' + navigator.userAgent + }) + } + function clearAuthData(state: IUserState) { state.userId = '' state.username = '' - state.tokens = [] - state.idToken = '' + resetArrToken(state.tokens) + state.x_auth_token = '' state.verified_email = false state.categorySel = 'personal' } @@ -211,7 +221,7 @@ namespace Actions { Mutations.mutations.setServerCode(rescodes.CALLING) - return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend, true) + return await Api.SendReq(call, 'POST', usertosend, true) .then(({ res, body }) => { return { code: body.code, msg: body.msg } }) @@ -236,7 +246,7 @@ namespace Actions { Mutations.mutations.setServerCode(rescodes.CALLING) - return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend) + return await Api.SendReq(call, 'POST', usertosend) .then(({ res, body }) => { return { code: body.code, msg: body.msg } }).catch((error) => { @@ -259,7 +269,7 @@ namespace Actions { Mutations.mutations.setServerCode(rescodes.CALLING) - return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend) + return await Api.SendReq(call, 'POST', usertosend) .then(({ res, body }) => { // console.log("RITORNO 2 "); // mutations.setServerCode(myres); @@ -302,16 +312,18 @@ namespace Actions { Mutations.mutations.setServerCode(rescodes.CALLING) - let x_auth_token: string = '' - - return Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend) - .then(({ res, newuser }) => { + return Api.SendReq(call, 'POST', usertosend) + .then(({ res, body }) => { myres = res + const newuser = body + + console.log('newuser', newuser, 'body', body) + Mutations.mutations.setServerCode(myres.status) if (myres.status === 200) { - let userId = newuser.userId + let userId = newuser._id let username = authData.username if (process.env.DEV) { console.log('USERNAME = ' + username) @@ -319,9 +331,8 @@ namespace Actions { } Mutations.mutations.authUser({ - userId: userId, - username: username, - idToken: x_auth_token, + userId, + username, verified_email: false }) @@ -330,7 +341,7 @@ namespace Actions { const expirationDate = new Date(now.getTime() * 1000) localStorage.setItem(rescodes.localStorage.userId, userId) localStorage.setItem(rescodes.localStorage.username, username) - localStorage.setItem(rescodes.localStorage.token, x_auth_token) + localStorage.setItem(rescodes.localStorage.token, state.x_auth_token) localStorage.setItem(rescodes.localStorage.expirationDate, expirationDate.toString()) localStorage.setItem(rescodes.localStorage.verified_email, String(false)) state.isLogged = true @@ -355,104 +366,105 @@ namespace Actions { console.log('MYLANG = ' + state.lang) - const usertosend = { - username: authData.username, - password: authData.password, - idapp: process.env.APP_ID, - keyappid: process.env.PAO_APP_ID, - lang: state.lang - } + await navigator.serviceWorker.ready + .then(function (swreg) { + const sub = swreg.pushManager.getSubscription() + return sub + }) + .then((swreg) => { - console.log(usertosend) - - let myres: IResult - - Mutations.mutations.setServerCode(rescodes.CALLING) - - return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend, true) - .then(({ res, body }) => { - myres = res - if (res.code === serv_constants.RIS_CODE_LOGIN_ERR) { - Mutations.mutations.setServerCode(body.code) - return body.code + const options = { + title: translate('notification.title_subscribed'), + content: translate('notification.subscribed'), + openUrl: '/' } - Mutations.mutations.setServerCode(myres.status) + const usertosend = { + username: authData.username, + password: authData.password, + idapp: process.env.APP_ID, + keyappid: process.env.PAO_APP_ID, + lang: state.lang, + subs: swreg, + options + } - if (myres.status === 200) { - let myuser: IUserState = body.usertosend - if (myuser) { - let userId = myuser.userId - let username = authData.username - let verified_email = myuser.verified_email - if (process.env.DEV) { - console.log('USERNAME = ' + username) - console.log('IDUSER= ' + userId) - console.log('state.x_auth_token= ' + state.x_auth_token) - Mutations.mutations.authUser({ - userId, - username, - idToken: state.x_auth_token, - verified_email - }) + console.log(usertosend) + + Mutations.mutations.setServerCode(rescodes.CALLING) + + return usertosend + + }).then((usertosend) => { + let myres: IResult + + return Api.SendReq(call, 'POST', usertosend, true) + .then(({ res, body }) => { + myres = res + if (res.code === serv_constants.RIS_CODE_LOGIN_ERR) { + Mutations.mutations.setServerCode(body.code) + return body.code } - const now = new Date() - // const expirationDate = new Date(now.getTime() + myres.data.expiresIn * 1000); - const expirationDate = new Date(now.getTime() * 1000) - localStorage.setItem(rescodes.localStorage.userId, userId) - localStorage.setItem(rescodes.localStorage.username, username) - localStorage.setItem(rescodes.localStorage.token, state.x_auth_token) - localStorage.setItem(rescodes.localStorage.expirationDate, expirationDate.toString()) - localStorage.setItem(rescodes.localStorage.isLogged, String(true)) - localStorage.setItem(rescodes.localStorage.verified_email, String(verified_email)) + Mutations.mutations.setServerCode(myres.status) - setGlobal() + if (myres.status === 200) { + let myuser: IUserState = body.usertosend + if (myuser) { + let userId = myuser.userId + let username = authData.username + let verified_email = myuser.verified_email + if (process.env.DEV) { + console.log('USERNAME = ' + username) + console.log('IDUSER= ' + userId) + console.log('state.x_auth_token= ' + state.x_auth_token) + } - // dispatch('storeUser', authData); - // dispatch('setLogoutTimer', myres.data.expiresIn); - return rescodes.OK - } else { - return rescodes.ERR_GENERICO - } - } else if (myres.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) { - if (process.env.DEV) { - console.log('CODE = ' + body.code) - } - return body.code - } else { - if (process.env.DEV) { - console.log('CODE = ' + body.code) - } - return body.code - } - }) - .catch((error) => { - UserStore.mutations.setErrorCatch(error) - return UserStore.getters.getServerCode + Mutations.mutations.authUser({ + userId, + username, + verified_email + }) + + const now = new Date() + // const expirationDate = new Date(now.getTime() + myres.data.expiresIn * 1000); + const expirationDate = new Date(now.getTime() * 1000) + localStorage.setItem(rescodes.localStorage.userId, userId) + localStorage.setItem(rescodes.localStorage.username, username) + localStorage.setItem(rescodes.localStorage.token, state.x_auth_token) + localStorage.setItem(rescodes.localStorage.expirationDate, expirationDate.toString()) + localStorage.setItem(rescodes.localStorage.isLogged, String(true)) + localStorage.setItem(rescodes.localStorage.verified_email, String(verified_email)) + + setGlobal(true) + + // dispatch('storeUser', authData); + // dispatch('setLogoutTimer', myres.data.expiresIn); + return rescodes.OK + } else { + return rescodes.ERR_GENERICO + } + } else if (myres.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) { + if (process.env.DEV) { + console.log('CODE = ' + body.code) + } + return body.code + } else { + if (process.env.DEV) { + console.log('CODE = ' + body.code) + } + return body.code + } + }) + .catch((error) => { + UserStore.mutations.setErrorCatch(error) + return UserStore.getters.getServerCode + }) }) } async function logout(context) { - - let call = process.env.MONGODB_HOST + '/users/me/token' - console.log('CALL ' + call) - - let usertosend = { - keyappid: process.env.PAO_APP_ID, - idapp: process.env.APP_ID - } - - console.log(usertosend) - return await Api.SendReq(call, state.lang, Getters.getters.tok, 'DELETE', usertosend) - .then(({ res, body }) => { - console.log(res) - }).then(() => { - Mutations.mutations.clearAuthData() - }).catch((error) => { - UserStore.mutations.setErrorCatch(error) - return UserStore.getters.getServerCode - }) + console.log('logout') localStorage.removeItem(rescodes.localStorage.expirationDate) localStorage.removeItem(rescodes.localStorage.token) @@ -463,12 +475,33 @@ namespace Actions { localStorage.removeItem(rescodes.localStorage.verified_email) localStorage.removeItem(rescodes.localStorage.categorySel) - GlobalStore.actions.clearDataAfterLogout() + await GlobalStore.actions.clearDataAfterLogout() + + let call = process.env.MONGODB_HOST + '/users/me/token' + console.log('CALL ' + call) + + let usertosend = { + keyappid: process.env.PAO_APP_ID, + idapp: process.env.APP_ID + } + + console.log(usertosend) + const riscall = await Api.SendReq(call, 'DELETE', usertosend) + .then(({ res, body }) => { + console.log(res) + }).then(() => { + Mutations.mutations.clearAuthData() + }).catch((error) => { + UserStore.mutations.setErrorCatch(error) + return UserStore.getters.getServerCode + }) + + return riscall // this.$router.push('/signin') } - async function setGlobal() { + async function setGlobal(loggedWithNetwork: boolean) { state.isLogged = true GlobalStore.mutations.setleftDrawerOpen(localStorage.getItem(rescodes.localStorage.leftDrawerOpen) === 'true') GlobalStore.mutations.setCategorySel(localStorage.getItem(rescodes.localStorage.categorySel)) @@ -511,14 +544,15 @@ namespace Actions { console.log('autologin userId', userId) + UserStore.mutations.setAuth(token) + Mutations.mutations.authUser({ userId: userId, username: username, - idToken: token, verified_email: verified_email }) - await setGlobal() + await setGlobal(false) console.log('autologin userId STATE ', state.userId)