From 4d5cea1c174d5fbe49c33a4348a2425eded823a6 Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Sat, 9 Feb 2019 18:04:49 +0100 Subject: [PATCH 1/8] - Manage multiple login, in different browsers... Multi Token... - visualization of the Connection State (Online, Offline) using fetch. --- .env.development | 2 +- src-pwa/custom-service-worker.js | 86 +++++++++----------- src/App.ts | 9 ++- src/common/axios.ts | 3 +- src/components/Header.vue | 106 ++++++++++++++++++++++++ src/components/todos/todo/todo.ts | 48 +++++------ src/globalroutines/indexdb.js | 2 + src/js/storage.js | 2 +- src/layouts/drawer/drawer.vue | 3 +- src/model/GlobalStore.ts | 3 + src/model/UserStore.ts | 1 + src/statics/i18n.js | 12 ++- src/store/Api/Inst-Pao.ts | 3 + src/store/Api/index.ts | 120 +++++++++++++++++----------- src/store/Modules/GlobalStore.ts | 33 ++++++-- src/store/Modules/Todos.ts | 30 ++++--- src/store/Modules/UserStore.ts | 106 +++++++++++++----------- src/store/Modules/rescodes.ts | 2 +- src/store/Modules/serv_constants.ts | 5 +- src/views/login/signin/signin.ts | 26 ++++-- 20 files changed, 393 insertions(+), 209 deletions(-) diff --git a/.env.development b/.env.development index 77ae56f..ad2fa59 100644 --- a/.env.development +++ b/.env.development @@ -1,4 +1,4 @@ -APP_VERSION="DEV 0.0.10" +APP_VERSION="DEV 0.0.13" SERVICE_WORKER_FILE='service-worker.js' APP_ID='1' APP_URL='https://freeplanet.app' diff --git a/src-pwa/custom-service-worker.js b/src-pwa/custom-service-worker.js index c1cdaa1..4118dca 100644 --- a/src-pwa/custom-service-worker.js +++ b/src-pwa/custom-service-worker.js @@ -1,4 +1,3 @@ - /* * This file (which will be your service worker) * is picked up by the build system ONLY if @@ -7,49 +6,48 @@ // Questo è il swSrc -console.log('SW-06 ___________________________ PAO: this is my custom service worker'); +console.log(' [ VER-0.0.12 ] _---------________-----------_________------------__________________________ 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'); importScripts('../statics/js/storage.js'); -console.log('SW-06 1'); +// console.log('SW-06 1'); const cfgenv = { serverweb: self.location.protocol + "//" + self.location.hostname + ':3000', dbname: 'mydb3', dbversion: 11, } -console.log('SW-06 2'); +// console.log('SW-06 2'); -console.log('SERVERWEB=', cfgenv.serverweb) +// console.log('SERVERWEB=', cfgenv.serverweb) // 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); } async function readAllData(table) { - console.log('readAllData', table); + // console.log('readAllData', table); return await idbKeyval.getalldata(table); } async function clearAllData(table) { - console.log('clearAllData', table); + // console.log('clearAllData', table); await idbKeyval.clearalldata(table) } async function deleteItemFromData(table, id) { - console.log('deleteItemFromData', table, 'ID:', id); + // console.log('deleteItemFromData', table, 'ID:', id); await idbKeyval.deletedata(table, id) } - // self.addEventListener('activate', function(event) { // event.waitUntil( // // createDB() @@ -58,7 +56,7 @@ async function deleteItemFromData(table, id) { if (!workbox) { let workbox = new self.WorkboxSW(); - console.log('SW-06 3'); + // console.log('SW-06 3'); } if (workbox) { @@ -109,15 +107,15 @@ if (workbox) { workbox.routing.registerRoute( new RegExp(cfgenv.serverweb + '/todos/'), function (args) { - console.log('registerRoute!') + // console.log('registerRoute!') return fetch(args.event.request, args.event.headers) .then(function (res) { - console.log('1° ******* [[[ SERVICE-WORKER ]]] registerRoute fetch: ', args.event) + console.log('1° ******* [[[ SERVICE-WORKER ]]] registerRoute fetch: -> ', args.event.headers) // LOAD FROM SERVER , AND SAVE INTO INDEXEDDB console.log('res.status', res.status) if (res.status === 200) { - var clonedRes = res.clone(); - clearAllData('todos') + const clonedRes = res.clone(); + return clearAllData('todos') .then(function () { return clonedRes.json(); }) @@ -129,8 +127,8 @@ if (workbox) { } } }); - return res } + return res }) } ); @@ -201,18 +199,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( @@ -225,14 +223,14 @@ if (workbox) { if ('serviceWorker' in navigator) { - console.log('***************** Entering in custom-service-worker.js:') + // console.log('***************** Entering in custom-service-worker.js:') } self.addEventListener('fetch', (event) => { if (event.request.url === '/') { const staleWhileRevalidate = new workbox.strategies.StaleWhileRevalidate(); - event.respondWith(staleWhileRevalidate.handle({event})); + event.respondWith(staleWhileRevalidate.handle({ event })); } }); @@ -280,13 +278,13 @@ self.addEventListener('sync', function (event) { headers.append('Accept', 'application/json') headers.append('x-auth', token) - console.log('A1) INIZIO.............................................................'); + // 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) @@ -304,18 +302,10 @@ self.addEventListener('sync', function (event) { mode: 'cors', // 'no-cors', body: JSON.stringify(rec) }) - .then(function (resData) { - // console.log('Result CALL ', method, ' OK? =', resData.ok); - - // Anyway Delete this, otherwise in some cases will return error, but it's not a problem. - // for example if I change a record and then I deleted ... - // if (resData.ok) { - deleteItemFromData(table, rec._id); - // } - + .then(resData => deleteItemFromData(table, rec._id)) + .then(() => { console.log('DELETE: ', mystrparam) deleteItemFromData('swmsg', mystrparam) - }) .catch(function (err) { console.log('!!!!!!!!!!!!!!! Error while sending data', err); @@ -360,7 +350,7 @@ self.addEventListener('sync', event => { }) */ -self.addEventListener('notificationclick', function(event) { +self.addEventListener('notificationclick', function (event) { var notification = event.notification; var action = event.action; @@ -373,8 +363,8 @@ self.addEventListener('notificationclick', function(event) { console.log(action); event.waitUntil( clients.matchAll() - .then(function(clis) { - var client = clis.find(function(c) { + .then(function (clis) { + var client = clis.find(function (c) { return c.visibilityState === 'visible'; }); @@ -390,14 +380,14 @@ self.addEventListener('notificationclick', function(event) { } }); -self.addEventListener('notificationclose', function(event) { +self.addEventListener('notificationclose', function (event) { console.log('Notification was closed', event); }); -self.addEventListener('push', function(event) { +self.addEventListener('push', function (event) { console.log('Push Notification received', event); - var data = {title: 'New!', content: 'Something new happened!', openUrl: '/'}; + var data = { title: 'New!', content: 'Something new happened!', openUrl: '/' }; if (event.data) { data = JSON.parse(event.data.text()); diff --git a/src/App.ts b/src/App.ts index 3fa8cf6..546226a 100644 --- a/src/App.ts +++ b/src/App.ts @@ -37,9 +37,9 @@ export default class App extends Vue { // console.info(process.env) } - UserStore.actions.autologin() - .then((loginEseguito) => { - if (loginEseguito) { + UserStore.actions.autologin_FromLocalStorage() + .then((loadstorage) => { + if (loadstorage) { globalroutines(this, 'loadapp', '') // this.$router.replace('/') @@ -48,6 +48,9 @@ export default class App extends Vue { } }) + // Calling the Server for updates ? + // Check the verified_email + } diff --git a/src/common/axios.ts b/src/common/axios.ts index 89ffac5..9986156 100644 --- a/src/common/axios.ts +++ b/src/common/axios.ts @@ -5,6 +5,7 @@ import { AxiosResponse } from 'axios' import { default as VueRouter } from 'vue-router' +import { serv_constants } from "@src/store/Modules/serv_constants" // import { TokenHelper } from "./token-helper"; let initialized: boolean = false @@ -54,7 +55,7 @@ export function UseAxios(router: VueRouter) { } } - if (response.status === 403 && handle(response.status, exclude)) { + if (response.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN && handle(response.status, exclude)) { window.setTimeout(() => router.replace('/forbidden'), 200) } diff --git a/src/components/Header.vue b/src/components/Header.vue index 7d2557b..7f14cd9 100644 --- a/src/components/Header.vue +++ b/src/components/Header.vue @@ -32,6 +32,17 @@
{{$t('msg.myDescriz')}} {{ getAppVersion() }}
+ + + + + - + 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) From 259e2dc4e2d0be42cda6ef2a94669fe677c4d48b Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Tue, 12 Feb 2019 19:09:43 +0100 Subject: [PATCH 4/8] ++ If press DELETE or BACKSPACE and is blank description, delete the Todos. - fix: if offline, doesn't save to cache?? if I refresh page, the data disappear - ++ field to the percent progress - fix: Refreshing 2 times the array todos.. because there is a filter --- src-pwa/custom-service-worker.js | 161 +++++++++--------- src/components/Header.vue | 6 +- src/components/todos/SingleTodo/SingleTodo.ts | 23 ++- .../todos/SingleTodo/SingleTodo.vue | 4 +- src/components/todos/SubMenus/SubMenus.scss | 7 +- src/components/todos/SubMenus/SubMenus.ts | 15 +- src/components/todos/SubMenus/SubMenus.vue | 24 ++- src/components/todos/todo/todo.ts | 18 +- src/components/todos/todo/todo.vue | 2 +- src/js/storage.js | 4 +- src/statics/js/storage.js | 2 +- src/store/Api/Inst-Pao.ts | 2 +- src/store/Api/index.ts | 99 ++++++----- src/store/Modules/GlobalStore.ts | 2 +- src/store/Modules/Todos.ts | 12 +- src/store/Modules/UserStore.ts | 55 +++--- src/views/login/requestresetpwd.vue | 4 +- 17 files changed, 252 insertions(+), 188 deletions(-) diff --git a/src-pwa/custom-service-worker.js b/src-pwa/custom-service-worker.js index f03c2e0..f5b24c0 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.21 ] _---------________-----------_________------------__________________________ 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) } @@ -108,9 +108,9 @@ if (workbox) { return fetch(args.event.request, args.event.headers) .then(function (res) { myres = res - console.log('1° ******* [[[ SERVICE-WORKER ]]] registerRoute fetch: -> ', args.event.request, res) + // console.log('1° ******* [[[ SERVICE-WORKER ]]] registerRoute fetch: -> ', args.event.request, res) // LOAD FROM SERVER , AND SAVE INTO INDEXEDDB - console.log('res.status', res.status) + // console.log('res.status', res.status) if (res.status === 200) { const clonedRes = res.clone(); clearAllData('todos') @@ -333,82 +333,83 @@ if ('serviceWorker' in navigator) { // }); -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 ') - 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, - mode: 'cors', // 'no-cors', - body: JSON.stringify(rec) - }) - .then(() => { - deleteItemFromData(table, rec._id) - deleteItemFromData('swmsg', mystrparam) - - // console.log('config WRITE ONLINE') - writeData('config', { _id: 2, stateconn: 'online' }) - }) - .catch(function (err) { - 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=') - } - } - } -}) -; +// 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=') +// } +// } +// } +// }) +// ; /* diff --git a/src/components/Header.vue b/src/components/Header.vue index 2b6b97c..1311774 100644 --- a/src/components/Header.vue +++ b/src/components/Header.vue @@ -191,16 +191,16 @@ console.log('Event LOAD') if (window) { window.addEventListener('load', function () { - console.log('2) ENTERING Event LOAD') + // console.log('2) ENTERING Event LOAD') function updateOnlineStatus(event) { if (navigator.onLine) { - console.log('EVENT ONLINE!') + // console.log('EVENT ONLINE!') // handle online status GlobalStore.mutations.setStateConnection('online') mythis.changeIconConn() } else { - console.log('EVENT OFFLINE!') + // console.log('EVENT OFFLINE!') // handle offline status GlobalStore.mutations.setStateConnection('offline') mythis.changeIconConn() diff --git a/src/components/todos/SingleTodo/SingleTodo.ts b/src/components/todos/SingleTodo/SingleTodo.ts index 1a0f6da..e3e9048 100644 --- a/src/components/todos/SingleTodo/SingleTodo.ts +++ b/src/components/todos/SingleTodo/SingleTodo.ts @@ -264,6 +264,15 @@ export default class SingleTodo extends Vue { } } */ + if (((e.keyCode === 8) || (e.keyCode === 46)) && (this.precDescr === '') && !e.shiftKey) { + e.preventDefault() + this.clickMenu(rescodes.MenuAction.DELETE) + .then(() => { + this.deselectRiga() + this.faiFocus('insertTask', true) + return + }) + } if (((e.key === 'Enter') || (e.key === 'Tab')) && !e.shiftKey) { this.updateTodo() @@ -344,16 +353,16 @@ export default class SingleTodo extends Vue { } - clickMenu(action) { + async clickMenu(action) { console.log('click menu: ', action) if (action === rescodes.MenuAction.DELETE) { - this.askConfirmDelete() + return this.askConfirmDelete() } else if (action === rescodes.MenuAction.TOGGLE_EXPIRING) { - this.enableExpiring() + return this.enableExpiring() } else if (action === rescodes.MenuAction.COMPLETED) { - this.setCompleted() + return this.setCompleted() } else if (action === rescodes.MenuAction.PROGRESS_BAR) { - this.updatedata() + return this.updatedata() } } @@ -369,11 +378,11 @@ export default class SingleTodo extends Vue { // this.$q.notify('setPriority: ' + elem) } - askConfirmDelete() { + async askConfirmDelete() { const deletestr = this.$t('dialog.delete') const cancelstr = this.$t('dialog.cancel') - askConfirm(this.$q, this.$t('dialog.msg.titledeleteTask'), this.$t('dialog.msg.deleteTask').toString(), deletestr, cancelstr) + await askConfirm(this.$q, this.$t('dialog.msg.titledeleteTask'), this.$t('dialog.msg.deleteTask').toString(), deletestr, cancelstr) .then(ris => { console.log('ris', ris) if (ris) diff --git a/src/components/todos/SingleTodo/SingleTodo.vue b/src/components/todos/SingleTodo/SingleTodo.vue index 1c8a0ea..4531097 100644 --- a/src/components/todos/SingleTodo/SingleTodo.vue +++ b/src/components/todos/SingleTodo/SingleTodo.vue @@ -23,7 +23,7 @@ - @@ -33,7 +33,7 @@ -
+
div:nth-child(2) > div > input { + min-width: 30px; + width: 30px; } diff --git a/src/components/todos/SubMenus/SubMenus.ts b/src/components/todos/SubMenus/SubMenus.ts index 2f18756..ffde880 100644 --- a/src/components/todos/SubMenus/SubMenus.ts +++ b/src/components/todos/SubMenus/SubMenus.ts @@ -2,8 +2,8 @@ import Vue from 'vue' import { Component, Prop } from 'vue-property-decorator' import { ITodo } from '../../../model/index' -import { rescodes } from "@src/store/Modules/rescodes" -import { UserStore } from "@store" +import { rescodes } from '@src/store/Modules/rescodes' +import { UserStore } from '@store' @Component({ @@ -14,7 +14,7 @@ export default class SubMenus extends Vue { public selectPriority: [] = rescodes.selectPriority[UserStore.state.lang] @Prop({ required: false }) menuPopupTodo: any[] - @Prop({ required: false }) itemtodo: ITodo[] + @Prop({ required: false }) itemtodo: ITodo $q: any clickMenu (field) { @@ -25,6 +25,15 @@ export default class SubMenus extends Vue { this.$emit('setPriority', field) } + KeychangeProgress (e) { + if (this.itemtodo.progress > 100) { + this.itemtodo.progress = 100 + } + if (this.itemtodo.progress < 0) { + this.itemtodo.progress = 0 + } + } + create () { this.selectPriority = rescodes.selectPriority[UserStore.state.lang] diff --git a/src/components/todos/SubMenus/SubMenus.vue b/src/components/todos/SubMenus/SubMenus.vue index 73c166d..51de6d1 100644 --- a/src/components/todos/SubMenus/SubMenus.vue +++ b/src/components/todos/SubMenus/SubMenus.vue @@ -18,14 +18,28 @@ - + + - -
- {{$parent.percentageProgress}}% + +
+
+ + + + + + @@ -61,6 +75,6 @@ - diff --git a/src/components/todos/todo/todo.ts b/src/components/todos/todo/todo.ts index 020485d..de67750 100644 --- a/src/components/todos/todo/todo.ts +++ b/src/components/todos/todo/todo.ts @@ -43,6 +43,7 @@ export default class Todo extends Vue { itemDragEnd: any = null selrowid: number = 0 polling = null + mytypetransgroup: string = 'crossfade' fieldtochange: String [] = ['descr', 'completed', 'category', 'expiring_at', 'priority', 'id_prev', 'id_next', 'pos', 'enableExpiring', 'progress'] @@ -65,7 +66,10 @@ export default class Todo extends Vue { @Watch('$route.params.category') changecat() { // console.log('changecat') - this.load() + this.mytypetransgroup = 'nessuno' + this.updatetable().then(() => { + this.mytypetransgroup = 'crossfade' + }) } get todos_changed() { @@ -82,7 +86,7 @@ export default class Todo extends Vue { // this.$q.notify('Changed...') - // console.log('Todos.state.todos_changed CHANGED!', value, oldValue) + console.log('Todos.state.todos_changed CHANGED!', value, oldValue) this.updatetable(true) } @@ -600,12 +604,16 @@ export default class Todo extends Vue { } async updatetable(refresh: boolean = false) { - // console.log('updatetable') + console.log('updatetable') this.prevRecords = [...this.todos_arr] return await Todos.actions.getTodosByCategory(this.getCategory()) - .then(arrtemp => { + .then(arrris => { + + this.todos_arr = [] + + let arrtemp = [...arrris] arrtemp = _.orderBy(arrtemp, ['completed', 'priority', 'pos'], ['asc', 'desc', 'asc']) @@ -620,6 +628,8 @@ export default class Todo extends Vue { this.todos_arr = [...arrtemp] // make copy + console.log('AGGIORNA todos_arr') + }) } diff --git a/src/components/todos/todo/todo.vue b/src/components/todos/todo/todo.vue index eb221c3..1e61910 100644 --- a/src/components/todos/todo/todo.vue +++ b/src/components/todos/todo/todo.vue @@ -12,7 +12,7 @@
- +
diff --git a/src/js/storage.js b/src/js/storage.js index 64b4ffe..9905be7 100644 --- a/src/js/storage.js +++ b/src/js/storage.js @@ -86,7 +86,7 @@ export let idbKeyval = (() => { async setdata(table, value) { let req; - console.log('setdata', table, value) + // console.log('setdata', table, value) await withStore('readwrite', table, store => { req = store.put(value); }); @@ -103,7 +103,7 @@ export let idbKeyval = (() => { }); }, async clearalldata(table) { - console.log('clearalldata', table) + // console.log('clearalldata', table) return await withStore('readwrite', table, store => { store.clear(); }); diff --git a/src/statics/js/storage.js b/src/statics/js/storage.js index 8dcbc4b..f9b3841 100644 --- a/src/statics/js/storage.js +++ b/src/statics/js/storage.js @@ -105,7 +105,7 @@ let idbKeyval = (() => { }); }, async clearalldata(table) { - console.log('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 6afdf65..871d025 100644 --- a/src/store/Api/Inst-Pao.ts +++ b/src/store/Api/Inst-Pao.ts @@ -9,7 +9,7 @@ async function sendRequest(url: string, lang: string, mytok: string, method: str authHeader.append('Accept', 'application/json') if (url !== process.env.MONGODB_HOST + '/users/login') { authHeader.append('x-auth', mytok) - console.log('TOK PASSATO ALLA FETCH:', mytok) + // console.log('TOK PASSATO ALLA FETCH:', mytok) } // authHeader.append('accept-language', lang) diff --git a/src/store/Api/index.ts b/src/store/Api/index.ts index 7ab6b24..1edd040 100644 --- a/src/store/Api/index.ts +++ b/src/store/Api/index.ts @@ -55,11 +55,11 @@ export namespace ApiTool { return sendRequest(url, UserStore.state.lang, UserStore.state.x_auth_token, method, mydata) .then(resreceived => { - console.log('resreceived', resreceived) + // console.log('resreceived', resreceived) ricevuto = true let res = resreceived.clone() if (process.env.DEV) { - console.log('SendReq RES [', res.status, ']', res) + // console.log('SendReq RES [', res.status, ']', res) } UserStore.mutations.setResStatus(res.status) @@ -143,66 +143,73 @@ export namespace ApiTool { // let lang = multiparams[3] if (cmd === 'sync-todos') { - console.log('[Alternative] Syncing', cmd, table, method) + // console.log('[Alternative] Syncing', cmd, table, method) const headers = new Headers() headers.append('content-Type', 'application/json') headers.append('Accept', 'application/json') headers.append('x-auth', token) + let errorfromserver = false + let lettoqualcosa = false + // console.log('A1) INIZIO.............................................................') - await globalroutines(null, 'readall', table, null) + globalroutines(null, 'readall', table, null) .then(function (alldata) { - const myrecs = [...alldata] - // console.log('----------------------- LEGGO QUALCOSA ') - if (myrecs) { - for (let rec of myrecs) { - // console.log('syncing', table, '', rec.descr) - let link = process.env.MONGODB_HOST + '/todos' + const myrecs = [...alldata] + // console.log('----------------------- LEGGO QUALCOSA ') - if (method !== 'POST') - link += '/' + rec._id + const promises = myrecs.map(rec => { + // console.log('syncing', table, '', rec.descr) + let link = process.env.MONGODB_HOST + '/todos' - console.log(' [Alternative] ++++++++++++++++++ SYNCING !!!! ', rec.descr, table, 'FETCH: ', method, link, 'data:') + if (method !== 'POST') + link += '/' + rec._id - let lettoqualcosa = false + // console.log(' [Alternative] ++++++++++++++++++ SYNCING !!!! ', rec.descr, table, 'FETCH: ', method, link, 'data:') - // 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(resData => { - lettoqualcosa = true + // Insert/Delete/Update table to the server + return fetch(link, { + method: method, + headers: headers, + cache: 'no-cache', + mode: 'cors', // 'no-cors', + body: JSON.stringify(rec) + }) + .then(() => { + globalroutines(null, 'delete', table, null, rec._id) + lettoqualcosa = true + }) + .then(() => { + globalroutines(null, 'delete', 'swmsg', null, mystrparam) + }) + .catch(function (err) { + if (err.message === 'Failed to fetch') { + errorfromserver = true + } + // console.log(' [Alternative] !!!!!!!!!!!!!!! Error while sending data', err, errorfromserver, 'lettoqualcosa', lettoqualcosa) + }) + }) - return globalroutines(null, 'delete', 'swmsg', null, mystrparam) - }).then(() => globalroutines(null, 'delete', table, null, rec._id)) - .then((ris) => { - return globalroutines(null, 'write', 'config', { _id: 2, stateconn: 'online' }) - }) - .then(() => { - // console.log('Clear', 'swmsg', method) - GlobalStore.mutations.setStateConnection(lettoqualcosa ? 'online' : 'offline') - }) - .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') - }) + // CALL ALL THE PROMISES + return Promise.all(promises).then(() => { + return (errorfromserver && !lettoqualcosa) + }).catch(err => { + return (errorfromserver && !lettoqualcosa) + }) - } - } - } - ).catch(e => { - console.log('ERROR:', e) + }).catch(e => { + // console.log('ERROR:', e) + return (errorfromserver && !lettoqualcosa) + }) + .then((errorfromserver) => { + // console.log('¨¨¨¨¨¨¨¨¨¨¨¨¨¨ errorfromserver:', errorfromserver) + const mystate = errorfromserver ? 'offline' : 'online' + globalroutines(null, 'write', 'config', { _id: 2, stateconn: mystate }) + GlobalStore.mutations.setStateConnection(mystate) }) - console.log(' [Alternative] A2) ?????????????????????????? ESCO DAL LOOP !!!!!!!!! err=') + // console.log(' [Alternative] A2) ?????????????????????????? ESCO DAL LOOP !!!!!!!!!') } } diff --git a/src/store/Modules/GlobalStore.ts b/src/store/Modules/GlobalStore.ts index 7d147ad..425fbb9 100644 --- a/src/store/Modules/GlobalStore.ts +++ b/src/store/Modules/GlobalStore.ts @@ -135,7 +135,7 @@ namespace Actions { mystate.isSubscribed = !(subscription === null) if (mystate.isSubscribed) { - console.log('User is already Subscribed!') + // console.log('User is already Subscribed!') } else { // Create a new subscription let convertedVapidPublicKey = urlBase64ToUint8Array(mykey) diff --git a/src/store/Modules/Todos.ts b/src/store/Modules/Todos.ts index 194801c..8e79f88 100644 --- a/src/store/Modules/Todos.ts +++ b/src/store/Modules/Todos.ts @@ -43,7 +43,7 @@ namespace Mutations { function setTodos_changed(state: ITodosState) { state.todos_changed++ mutations.setTestpao('Cambiato : ' + String(state.todos_changed)) - console.log('******************************* state.todos_changed', state.todos_changed) + console.log('******* state.todos_changed', state.todos_changed) } export const mutations = { @@ -195,16 +195,16 @@ namespace Actions { state.networkDataReceived = false let ris = await Api.SendReq(call, 'GET', null) - .then(({ resData, body, status }) => { + .then(({ res, body, status }) => { state.networkDataReceived = true - // console.log('******* UPDATE TODOS.STATE.TODOS !:', resData.todos) + // console.log('******* UPDATE TODOS.STATE.TODOS !:', res.todos) if (body.todos) { state.todos = [...body.todos] Todos.mutations.setTodos_changed() } - console.log('********** resData', resData, 'state.todos', state.todos, 'checkPending', checkPending) + console.log('********** res', res, 'state.todos', state.todos, 'checkPending', checkPending) // After Login will store into the indexedDb... @@ -216,8 +216,8 @@ namespace Actions { return { status } }) - console.log('ris : ', ris) - console.log('ris STATUS: ', ris.status) + // console.log('ris : ', ris) + // console.log('ris STATUS: ', ris.status) if (!Todos.state.networkDataReceived) { diff --git a/src/store/Modules/UserStore.ts b/src/store/Modules/UserStore.ts index da8f436..3309f98 100644 --- a/src/store/Modules/UserStore.ts +++ b/src/store/Modules/UserStore.ts @@ -111,7 +111,7 @@ namespace Mutations { if (!state.tokens) { state.tokens = [] } - state.tokens.push({ access: 'auth ' + navigator.userAgent, token: data.x_auth_token, 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) { @@ -227,7 +227,7 @@ namespace Actions { }) .catch((error) => { UserStore.mutations.setErrorCatch(error) - return UserStore.getters.getServerCode + return { code: UserStore.getters.getServerCode, msg: error } }) } @@ -366,7 +366,7 @@ namespace Actions { console.log('MYLANG = ' + state.lang) - await navigator.serviceWorker.ready + return await navigator.serviceWorker.ready .then(function (swreg) { const sub = swreg.pushManager.getSubscription() return sub @@ -408,7 +408,26 @@ namespace Actions { Mutations.mutations.setServerCode(myres.status) - if (myres.status === 200) { + if (myres.status !== 200) { + return Promise.reject(rescodes.ERR_GENERICO) + } + return { res, body } + + }).then(({ res, body }) => { + + 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 (res.status !== 200) { + if (process.env.DEV) { + console.log('CODE = ' + body.code) + } + return body.code + } + + if (res.status === 200) { let myuser: IUserState = body.usertosend if (myuser) { let userId = myuser.userId @@ -436,24 +455,19 @@ namespace Actions { 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 + return rescodes.OK + + }).then(code => { + if (code === rescodes.OK) { + return setGlobal(true) + .then(() => { + return code + }) } else { - if (process.env.DEV) { - console.log('CODE = ' + body.code) - } - return body.code + return code } }) .catch((error) => { @@ -507,7 +521,6 @@ namespace Actions { GlobalStore.mutations.setCategorySel(localStorage.getItem(rescodes.localStorage.categorySel)) - await GlobalStore.actions.loadAfterLogin() .then(() => { Todos.actions.dbLoadTodo(true) diff --git a/src/views/login/requestresetpwd.vue b/src/views/login/requestresetpwd.vue index 14033e2..793e5f1 100644 --- a/src/views/login/requestresetpwd.vue +++ b/src/views/login/requestresetpwd.vue @@ -104,8 +104,8 @@ if (ris.code === serv_constants.RIS_CODE_OK) this.emailsent = true; this.$q.loading.hide(); - }).catch(error => { - console.log("ERROR = " + error); + }).catch(err => { + console.log("ERROR = " + err.error); this.$q.loading.hide(); }); From 06635c87d47f87c9754b52a8908714996b0404ff Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Wed, 13 Feb 2019 01:51:59 +0100 Subject: [PATCH 5/8] - Created Test Environment un Server test.freeplanet.app - mongodb open 2 connections port (3000 and 3001) - 27017 and 27018 --- .gitignore | 7 ++++++- package.json | 1 + quasar.conf.js | 1 + src-pwa/custom-service-worker.js | 6 +++++- 4 files changed, 13 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index d03be54..b327f0b 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,9 @@ .thumbs.db .env .env.production +.env.production.bak +.env.prod.bak +.env.test node_modules /dist /src-cordova/node_modules @@ -28,4 +31,6 @@ coverage /_PROVE /_LOCALE deploy.sh -deploy_production.sh +deploy_on_production.sh +deploy_on_test_server.sh +send_to_production.sh diff --git a/package.json b/package.json index 4bdad00..cb30e46 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "serve": "quasar serve ./dist/pwa-mat", "serve:coverage": "quasar serve test/coverage/lcov-report/ --cache 0 --port 8788", "deploy": "deploy.sh", + "deploy_server_test": "NODE_ENV=test quasar build -m pwa", "generate-sw": "workbox generateSW workbox-config.js" }, "dependencies": { diff --git a/quasar.conf.js b/quasar.conf.js index 3dbbc0d..815f50a 100644 --- a/quasar.conf.js +++ b/quasar.conf.js @@ -195,6 +195,7 @@ module.exports = function (ctx) { }, manifest: { name: 'Free Planet', + version: '0.0.14', short_name: 'freeplanet', description: 'Social project in order to connecting people each others (working in progress...)', display: 'standalone', diff --git a/src-pwa/custom-service-worker.js b/src-pwa/custom-service-worker.js index f5b24c0..5aa6dd3 100644 --- a/src-pwa/custom-service-worker.js +++ b/src-pwa/custom-service-worker.js @@ -13,9 +13,13 @@ importScripts('../statics/js/idb.js'); importScripts('../statics/js/storage.js'); +let port = 3001; +if (self.location.hostname === 'localhost') { + port = 3000; +} // console.log('SW-06 1'); const cfgenv = { - serverweb: self.location.protocol + "//" + self.location.hostname + ':3000', + serverweb: self.location.protocol + "//" + self.location.hostname + ':' + port, dbname: 'mydb3', dbversion: 11, } From e8d2d49829adbdbfb80692df94adbfd2229859b5 Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Wed, 13 Feb 2019 18:48:30 +0100 Subject: [PATCH 6/8] fix: WebPush Notification --- src-pwa/custom-service-worker.js | 10 +- src/App.ts | 1 - src/components/Header.vue | 2 +- src/model/GlobalStore.ts | 3 +- src/root/home/home.ts | 2 +- src/store/Api/index.ts | 3 +- src/store/Modules/GlobalStore.ts | 74 +++++++----- src/store/Modules/UserStore.ts | 199 ++++++++++++++++--------------- src/store/Modules/rescodes.ts | 1 + src/views/login/signin/signin.ts | 15 ++- 10 files changed, 170 insertions(+), 140 deletions(-) diff --git a/src-pwa/custom-service-worker.js b/src-pwa/custom-service-worker.js index 5aa6dd3..8ab8af3 100644 --- a/src-pwa/custom-service-worker.js +++ b/src-pwa/custom-service-worker.js @@ -13,9 +13,9 @@ importScripts('../statics/js/idb.js'); importScripts('../statics/js/storage.js'); -let port = 3001; -if (self.location.hostname === 'localhost') { - port = 3000; +let port = 3000; +if (self.location.hostname === 'test.freeplanet.app') { + port = 3001; } // console.log('SW-06 1'); const cfgenv = { @@ -481,7 +481,7 @@ self.addEventListener('notificationclose', function (event) { self.addEventListener('push', function (event) { console.log('Push Notification received', event); - var data = { title: 'New!', content: 'Something new happened!', openUrl: '/' }; + var data = { title: 'New!', content: 'Something new happened!', url: '/' }; if (event.data) { data = JSON.parse(event.data.text()); @@ -492,7 +492,7 @@ self.addEventListener('push', function (event) { icon: '/statics/icons/android-chrome-192x192.png', badge: '/statics/icons/android-chrome-192x192.png', data: { - url: data.openUrl + url: data.url } }; diff --git a/src/App.ts b/src/App.ts index 546226a..bee552c 100644 --- a/src/App.ts +++ b/src/App.ts @@ -23,7 +23,6 @@ import { GlobalStore } from './store/Modules' export default class App extends Vue { public backgroundColor = 'whitesmoke' - public isSubscribed = false public $q diff --git a/src/components/Header.vue b/src/components/Header.vue index 1311774..4f5a7bd 100644 --- a/src/components/Header.vue +++ b/src/components/Header.vue @@ -188,7 +188,7 @@ // use the "Offline" checkbox in DevTools Network panel let mythis = this - console.log('Event LOAD') + // console.log('Event LOAD') if (window) { window.addEventListener('load', function () { // console.log('2) ENTERING Event LOAD') diff --git a/src/model/GlobalStore.ts b/src/model/GlobalStore.ts index a52a16c..ee9ebc8 100644 --- a/src/model/GlobalStore.ts +++ b/src/model/GlobalStore.ts @@ -6,7 +6,8 @@ export type StateConnection = 'online' | 'offline' export interface IGlobalState { conta: number - isSubscribed: boolean + wasAlreadySubOnDb: boolean + wasAlreadySubscribed: boolean isLoginPage: boolean layoutNeeded: boolean mobileMode: boolean diff --git a/src/root/home/home.ts b/src/root/home/home.ts index 30ac694..0851073 100644 --- a/src/root/home/home.ts +++ b/src/root/home/home.ts @@ -57,7 +57,7 @@ export default class Home extends Vue { initprompt() { window.addEventListener('beforeinstallprompt', function (event) { - console.log('******************************** beforeinstallprompt fired') + // console.log('******************************** beforeinstallprompt fired') event.preventDefault() console.log('§§§§§§§§§§§§§§§§§§§§ IMPOSTA DEFERRED PROMPT !!!!!!!!!!!!!!!!! ') return false diff --git a/src/store/Api/index.ts b/src/store/Api/index.ts index 1edd040..f495e52 100644 --- a/src/store/Api/index.ts +++ b/src/store/Api/index.ts @@ -55,7 +55,7 @@ export namespace ApiTool { return sendRequest(url, UserStore.state.lang, UserStore.state.x_auth_token, method, mydata) .then(resreceived => { - // console.log('resreceived', resreceived) + console.log('resreceived', resreceived) ricevuto = true let res = resreceived.clone() if (process.env.DEV) { @@ -103,6 +103,7 @@ export namespace ApiTool { return res.json() .then((body) => { + // console.log('BODY RES = ', body) return resolve({ res, body, status: res.status }) }) .catch(e => { diff --git a/src/store/Modules/GlobalStore.ts b/src/store/Modules/GlobalStore.ts index 425fbb9..3dbdc93 100644 --- a/src/store/Modules/GlobalStore.ts +++ b/src/store/Modules/GlobalStore.ts @@ -8,8 +8,10 @@ import translate from './../../globalroutines/util' import urlBase64ToUint8Array from '../../js/utility' import messages from '../../statics/i18n' -import { UserStore } from '@store' +import { GlobalStore, UserStore } from '@store' import globalroutines from './../../globalroutines/index' +import Api from "@api" +import { rescodes } from "@src/store/Modules/rescodes" const allTables = ['todos', 'sync_todos', 'sync_todos_patch', 'delete_todos', 'config', 'swmsg'] const allTablesAfterLogin = ['todos', 'sync_todos', 'sync_todos_patch', 'delete_todos', 'config', 'swmsg'] @@ -32,7 +34,8 @@ getstateConnSaved() const state: IGlobalState = { conta: 0, - isSubscribed: false, + wasAlreadySubscribed: false, + wasAlreadySubOnDb: false, isLoginPage: false, layoutNeeded: true, mobileMode: false, @@ -98,11 +101,16 @@ namespace Mutations { } } + function SetwasAlreadySubOnDb(state: IGlobalState, subscrib: boolean) { + state.wasAlreadySubOnDb = subscrib + } + export const mutations = { setConta: b.commit(setConta), setleftDrawerOpen: b.commit(setleftDrawerOpen), setCategorySel: b.commit(setCategorySel), - setStateConnection: b.commit(setStateConnection) + setStateConnection: b.commit(setStateConnection), + SetwasAlreadySubOnDb: b.commit(SetwasAlreadySubOnDb) } } @@ -113,6 +121,13 @@ namespace Actions { } function createPushSubscription(context) { + + // If Already subscribed, don't send to the Server DB + if (state.wasAlreadySubOnDb) { + // console.log('wasAlreadySubOnDb!') + return + } + if (!('serviceWorker' in navigator)) { return } @@ -132,10 +147,11 @@ namespace Actions { return swreg.pushManager.getSubscription() }) .then(function (subscription) { - mystate.isSubscribed = !(subscription === null) + mystate.wasAlreadySubscribed = !(subscription === null) - if (mystate.isSubscribed) { - // console.log('User is already Subscribed!') + if (mystate.wasAlreadySubOnDb) { + // console.log('User is already SAVED Subscribe on DB!') + return null } else { // Create a new subscription let convertedVapidPublicKey = urlBase64ToUint8Array(mykey) @@ -146,17 +162,7 @@ namespace Actions { } }) .then(function (newSub) { - // console.log('newSub', newSub) - if (newSub) { - saveNewSubscriptionToServer(context, newSub) - .then(ris => { - mystate.isSubscribed = true - }) - .catch(e => { - console.log('Error during Subscription!', e) - }) - } - return null + saveNewSubscriptionToServer(context, newSub) }) .catch(function (err) { console.log(err) @@ -165,8 +171,12 @@ namespace Actions { // Calling the Server to Save in the MongoDB the Subscriber function saveNewSubscriptionToServer(context, newSub) { + // If already subscribed, exit + if (!newSub) + return + console.log('saveSubscriptionToServer: ', newSub) - console.log('context', context) + // console.log('context', context) const options = { title: translate('notification.title_subscribed'), @@ -180,19 +190,21 @@ namespace Actions { others: { userId: UserStore.state.userId, access: UserStore.state.tokens[0].access - } + }, } - return fetch(process.env.MONGODB_HOST + '/subscribe', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Accept': 'application/json' - }, - body: JSON.stringify(myres) + let call = process.env.MONGODB_HOST + '/subscribe' - }) + return Api.SendReq(call, 'POST', myres) + .then(({ res, body }) => { + state.wasAlreadySubscribed = true + state.wasAlreadySubOnDb = true + localStorage.setItem(rescodes.localStorage.wasAlreadySubOnDb, String(state.wasAlreadySubOnDb)) + }) + .catch(e => { + console.log('Error during Subscription!', e) + }) } async function deleteSubscriptionToServer(context) { @@ -242,14 +254,14 @@ namespace Actions { // REMOVE ALL SUBSCRIPTION console.log('REMOVE ALL SUBSCRIPTION...') - await navigator.serviceWorker.ready.then(function(reg) { + await navigator.serviceWorker.ready.then(function (reg) { console.log('... Ready') - reg.pushManager.getSubscription().then(function(subscription) { + reg.pushManager.getSubscription().then(function (subscription) { console.log(' Found Subscription...') - subscription.unsubscribe().then(function(successful) { + subscription.unsubscribe().then(function (successful) { // You've successfully unsubscribed console.log('You\'ve successfully unsubscribed') - }).catch(function(e) { + }).catch(function (e) { // Unsubscription failed }) }) diff --git a/src/store/Modules/UserStore.ts b/src/store/Modules/UserStore.ts index 3309f98..636d794 100644 --- a/src/store/Modules/UserStore.ts +++ b/src/store/Modules/UserStore.ts @@ -90,7 +90,7 @@ namespace Mutations { state.category = data.categorySel 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) + // console.log('state.tokens', state.tokens) } function setpassword(state: IUserState, newstr: string) { @@ -318,7 +318,7 @@ namespace Actions { const newuser = body - console.log('newuser', newuser, 'body', body) + console.log('newuser', newuser) Mutations.mutations.setServerCode(myres.status) @@ -366,114 +366,117 @@ namespace Actions { console.log('MYLANG = ' + state.lang) - return await navigator.serviceWorker.ready + let sub = null + + sub = await navigator.serviceWorker.ready .then(function (swreg) { const sub = swreg.pushManager.getSubscription() return sub }) - .then((swreg) => { + .catch(e => { + sub = null + }) - const options = { - title: translate('notification.title_subscribed'), - content: translate('notification.subscribed'), - openUrl: '/' + const options = { + title: translate('notification.title_subscribed'), + content: translate('notification.subscribed'), + openUrl: '/' + } + + const usertosend = { + username: authData.username, + password: authData.password, + idapp: process.env.APP_ID, + keyappid: process.env.PAO_APP_ID, + lang: state.lang, + subs: sub, + options + } + + console.log(usertosend) + + Mutations.mutations.setServerCode(rescodes.CALLING) + + let myres: IResult + + return Api.SendReq(call, 'POST', usertosend, true) + .then(({ res, body }) => { + myres = res + + if (body.code === serv_constants.RIS_CODE_LOGIN_ERR) { + Mutations.mutations.setServerCode(body.code) + return { myres, body } } - 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 + Mutations.mutations.setServerCode(myres.status) + + if (myres.status !== 200) { + return Promise.reject(rescodes.ERR_GENERICO) + } + return { myres, body } + + }).then(({ myres, body }) => { + + 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 (myres.status !== 200) { + if (process.env.DEV) { + console.log('CODE = ' + body.code) + } + return body.code } - console.log(usertosend) + if (myres.status === 200) { + GlobalStore.mutations.SetwasAlreadySubOnDb(body.subsExistonDb) - 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 + 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, 'IDUSER= ' + userId) + // console.log('state.x_auth_token= ' + state.x_auth_token) } - Mutations.mutations.setServerCode(myres.status) + Mutations.mutations.authUser({ + userId, + username, + verified_email + }) - if (myres.status !== 200) { - return Promise.reject(rescodes.ERR_GENERICO) - } - return { res, body } + 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)) + localStorage.setItem(rescodes.localStorage.wasAlreadySubOnDb, String(GlobalStore.state.wasAlreadySubOnDb)) - }).then(({ res, body }) => { + } + } - 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 (res.status !== 200) { - if (process.env.DEV) { - console.log('CODE = ' + body.code) - } - return body.code - } + return rescodes.OK - if (res.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, - 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)) - - } - } - - return rescodes.OK - - }).then(code => { - if (code === rescodes.OK) { - return setGlobal(true) - .then(() => { - return code - }) - } else { + }).then(code => { + if (code === rescodes.OK) { + return setGlobal(true) + .then(() => { return code - } - }) - .catch((error) => { - UserStore.mutations.setErrorCatch(error) - return UserStore.getters.getServerCode - }) + }) + } else { + return code + } + }) + .catch((error) => { + UserStore.mutations.setErrorCatch(error) + return UserStore.getters.getServerCode }) } @@ -488,6 +491,8 @@ namespace Actions { // localStorage.removeItem(rescodes.localStorage.leftDrawerOpen) localStorage.removeItem(rescodes.localStorage.verified_email) localStorage.removeItem(rescodes.localStorage.categorySel) + localStorage.removeItem(rescodes.localStorage.wasAlreadySubOnDb) + await GlobalStore.actions.clearDataAfterLogout() @@ -530,7 +535,7 @@ namespace Actions { async function autologin_FromLocalStorage(context) { try { - console.log('*** autologin_FromLocalStorage ***') + // console.log('*** autologin_FromLocalStorage ***') // INIT UserStore.mutations.setlang(process.env.LANG_DEFAULT) @@ -555,14 +560,16 @@ namespace Actions { const username = String(localStorage.getItem(rescodes.localStorage.username)) const verified_email = localStorage.getItem(rescodes.localStorage.verified_email) === 'true' - console.log('autologin userId', userId) + GlobalStore.state.wasAlreadySubOnDb = localStorage.getItem(rescodes.localStorage.wasAlreadySubOnDb) === 'true' + + console.log('************* autologin userId', userId) UserStore.mutations.setAuth(token) Mutations.mutations.authUser({ userId: userId, username: username, - verified_email: verified_email + verified_email: verified_email, }) await setGlobal(false) diff --git a/src/store/Modules/rescodes.ts b/src/store/Modules/rescodes.ts index 52d35f5..13ef138 100644 --- a/src/store/Modules/rescodes.ts +++ b/src/store/Modules/rescodes.ts @@ -13,6 +13,7 @@ export const rescodes = { localStorage: { verified_email: 'vf', + wasAlreadySubOnDb: 'sb', categorySel: 'cs', isLogged: 'ilog', expirationDate: 'expdate', diff --git a/src/views/login/signin/signin.ts b/src/views/login/signin/signin.ts index 8ace175..0ef5e6b 100644 --- a/src/views/login/signin/signin.ts +++ b/src/views/login/signin/signin.ts @@ -80,8 +80,17 @@ export default class Signin extends Vue { this.showNotif({ type: 'positive', message: this.$t('login.completato') }) this.$router.push('/') } else if (riscode === serv_constants.RIS_CODE_LOGIN_ERR) { - this.showNotif(this.$t('login.errato')) - this.$router.push('/signin') + + // Wait N seconds to avoid calling many times... + return new Promise(function (resolve, reject) { + setTimeout(function () { + resolve('anything') + }, 1000) + }).then(() => { + this.showNotif(this.$t('login.errato')) + this.$router.push('/signin') + }) + } else if (riscode === rescodes.ERR_SERVERFETCH) { this.showNotif(this.$t('fetch.errore_server')) } else if (riscode === rescodes.ERR_GENERICO) { @@ -127,7 +136,7 @@ export default class Signin extends Vue { console.log(this.signin) UserStore.actions.signin(this.signin) .then((riscode) => { - console.log('riscode=', riscode) + // console.log('riscode=', riscode) if (riscode === rescodes.OK) { router.push('/signin') } From 6931d5700593657c15050aaf8a5176d11fa0f5ab Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Thu, 14 Feb 2019 18:38:23 +0100 Subject: [PATCH 7/8] Fix: Todo Multi refresh ... fix some promises problem --- .env.development | 2 +- src-pwa/custom-service-worker.js | 62 ++++++++----- src/App.ts | 33 ++++--- src/components/Header.vue | 12 +-- .../todos/SingleTodo/SingleTodo.scss | 6 +- src/components/todos/SingleTodo/SingleTodo.ts | 10 +-- .../todos/SingleTodo/SingleTodo.vue | 20 ++--- src/components/todos/todo/todo.ts | 88 ++++++++++++++----- src/components/todos/todo/todo.vue | 27 ++++-- src/css/themes/common.variables.styl | 1 + src/model/Todos.ts | 2 +- src/model/other.ts | 1 + src/root/home/home.ts | 18 ++-- src/root/home/home.vue | 8 ++ src/statics/i18n.js | 6 +- src/statics/js/storage.js | 1 + src/store/Api/index.ts | 8 +- src/store/Modules/GlobalStore.ts | 61 +++++++------ src/store/Modules/Todos.ts | 14 +-- src/store/Modules/UserStore.ts | 24 ++--- src/views/login/signin/signin.ts | 11 ++- src/views/login/vreg/vreg.ts | 29 +++--- 22 files changed, 281 insertions(+), 163 deletions(-) diff --git a/.env.development b/.env.development index c1e8448..e032ebc 100644 --- a/.env.development +++ b/.env.development @@ -1,4 +1,4 @@ -APP_VERSION="DEV 0.0.17" +APP_VERSION="DEV 0.0.27" SERVICE_WORKER_FILE='service-worker.js' APP_ID='1' APP_URL='https://freeplanet.app' diff --git a/src-pwa/custom-service-worker.js b/src-pwa/custom-service-worker.js index 8ab8af3..43ee1de 100644 --- a/src-pwa/custom-service-worker.js +++ b/src-pwa/custom-service-worker.js @@ -6,11 +6,11 @@ // Questo è il swSrc -console.log(' [ VER-0.0.21 ] _---------________------ PAO: this is my custom service worker'); +console.log(' [ VER-0.0.27 ] _---------________------ 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'); importScripts('../statics/js/storage.js'); +importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js'); //++Todo: Replace with local workbox.js let port = 3000; @@ -24,6 +24,9 @@ const cfgenv = { dbversion: 11, } +// console.log('serverweb', cfgenv.serverweb) + + async function writeData(table, data) { // console.log('writeData', table, data); await idbKeyval.setdata(table, data); @@ -54,10 +57,10 @@ async function deleteItemFromData(table, id) { if (!workbox) { let workbox = new self.WorkboxSW(); - // console.log('SW-06 3'); } if (workbox) { + // console.log('WORKBOX PRESENT') // const url = new URL(location.href); // const debug = url.searchParams.has('debug'); const debug = false; @@ -101,11 +104,12 @@ if (workbox) { }) ); + // console.log(' routing.registerRoute function declaration:') workbox.routing.registerRoute( new RegExp(cfgenv.serverweb + '/todos/'), function (args) { - // console.log('registerRoute!') + console.log('registerRoute! ', cfgenv.serverweb + '/todos/') // console.log('DATABODY:', args.event.request.body) let myres = null // return fetch(args.event.request, args.event.headers) @@ -117,8 +121,11 @@ if (workbox) { // console.log('res.status', res.status) if (res.status === 200) { const clonedRes = res.clone(); - clearAllData('todos') - return clonedRes + + return clearAllData('todos') + .then(() => { + return clonedRes + }) } }) .then((clonedRes) => { @@ -126,12 +133,12 @@ if (workbox) { return clonedRes.json(); return null }) - .then(data => { + .then(async data => { if (data) { if (data.todos) { - console.log('Records TODOS Received from Server [', data.todos.length, 'record]', data.todos) - for (let key in data.todos) { - writeData('todos', data.todos[key]) + console.log('***********************+++++++++++++++++++++++++++++++++++++++++++++++++++********** Records TODOS Received from Server [', data.todos.length, 'record]', data.todos) + for (const key in data.todos) { + await writeData('todos', data.todos[key]) } } } @@ -483,21 +490,30 @@ self.addEventListener('push', function (event) { var data = { title: 'New!', content: 'Something new happened!', url: '/' }; - if (event.data) { - data = JSON.parse(event.data.text()); - } + try { - var options = { - body: data.content, - icon: '/statics/icons/android-chrome-192x192.png', - badge: '/statics/icons/android-chrome-192x192.png', - data: { - url: data.url + if (event.data) { + try { + data = JSON.parse(event.data.text()); + } catch (e) { + data = event.data.text(); + } } - }; - event.waitUntil( - self.registration.showNotification(data.title, options) - ); + var options = { + body: data.content, + icon: '/statics/icons/android-chrome-192x192.png', + badge: '/statics/icons/android-chrome-192x192.png', + data: { + url: data.url + } + }; + + event.waitUntil( + self.registration.showNotification(data.title, options) + ); + } catch (e) { + console.log('Error on event push:', e) + } }); diff --git a/src/App.ts b/src/App.ts index bee552c..3ce9f38 100644 --- a/src/App.ts +++ b/src/App.ts @@ -12,7 +12,6 @@ import globalroutines from './globalroutines/index' import { GlobalStore } from './store/Modules' - @Component({ components: { appHeader: Header @@ -25,6 +24,7 @@ export default class App extends Vue { public backgroundColor = 'whitesmoke' public $q + public listaRoutingNoLogin = ['/vreg?', '/offline'] created() { if (process.env.DEV) { @@ -36,16 +36,30 @@ export default class App extends Vue { // console.info(process.env) } - UserStore.actions.autologin_FromLocalStorage() - .then((loadstorage) => { - if (loadstorage) { - globalroutines(this, 'loadapp', '') - // this.$router.replace('/') + // Make autologin only if some routing + + // console.log('window.location.href', window.location.href) + + let chiamaautologin = true + this.listaRoutingNoLogin.forEach(mystr => { + if (window.location.href.includes(mystr)) { + chiamaautologin = false + } + }) + + if (chiamaautologin) { + console.log('CHIAMA autologin_FromLocalStorage') + UserStore.actions.autologin_FromLocalStorage() + .then((loadstorage) => { + if (loadstorage) { + globalroutines(this, 'loadapp', '') + // this.$router.replace('/') // Create Subscription to Push Notification - GlobalStore.actions.createPushSubscription() - } - }) + GlobalStore.actions.createPushSubscription() + } + }) + } // Calling the Server for updates ? // Check the verified_email @@ -53,5 +67,4 @@ export default class App extends Vue { } - } diff --git a/src/components/Header.vue b/src/components/Header.vue index 4f5a7bd..049b2ae 100644 --- a/src/components/Header.vue +++ b/src/components/Header.vue @@ -111,11 +111,11 @@ this.strConn = value - this.$q.notify({ - color : 'primary', - icon: 'wifi', - message: "CAMBIATOO! " + value - }) + // this.$q.notify({ + // color : 'primary', + // icon: 'wifi', + // message: "CAMBIATOO! " + value + // }) } @@ -124,7 +124,7 @@ changeconn_changed(value: string, oldValue: string) { if (value != oldValue) { - console.log('SSSSSSSS: ', value, oldValue) + // console.log('SSSSSSSS: ', value, oldValue) const color = (value === 'online') ? 'positive' : 'warning' diff --git a/src/components/todos/SingleTodo/SingleTodo.scss b/src/components/todos/SingleTodo/SingleTodo.scss index 9ea75a7..4eebdb8 100644 --- a/src/components/todos/SingleTodo/SingleTodo.scss +++ b/src/components/todos/SingleTodo/SingleTodo.scss @@ -78,7 +78,10 @@ $heightitem: 19px; padding: 0px; text-align: center; vertical-align: middle; - display: none; + display: block; + @media screen and (min-width: 600px) { + display: none; + } color: #777; height: 100%; //visibility: hidden; @@ -291,6 +294,7 @@ $heightitem: 19px; } + /* .container { background-color: #ccc; diff --git a/src/components/todos/SingleTodo/SingleTodo.ts b/src/components/todos/SingleTodo/SingleTodo.ts index e3e9048..813ab95 100644 --- a/src/components/todos/SingleTodo/SingleTodo.ts +++ b/src/components/todos/SingleTodo/SingleTodo.ts @@ -266,9 +266,9 @@ export default class SingleTodo extends Vue { */ if (((e.keyCode === 8) || (e.keyCode === 46)) && (this.precDescr === '') && !e.shiftKey) { e.preventDefault() + this.deselectRiga() this.clickMenu(rescodes.MenuAction.DELETE) .then(() => { - this.deselectRiga() this.faiFocus('insertTask', true) return }) @@ -356,13 +356,13 @@ export default class SingleTodo extends Vue { async clickMenu(action) { console.log('click menu: ', action) if (action === rescodes.MenuAction.DELETE) { - return this.askConfirmDelete() + return await this.askConfirmDelete() } else if (action === rescodes.MenuAction.TOGGLE_EXPIRING) { - return this.enableExpiring() + return await this.enableExpiring() } else if (action === rescodes.MenuAction.COMPLETED) { - return this.setCompleted() + return await this.setCompleted() } else if (action === rescodes.MenuAction.PROGRESS_BAR) { - return this.updatedata() + return await this.updatedata() } } diff --git a/src/components/todos/SingleTodo/SingleTodo.vue b/src/components/todos/SingleTodo/SingleTodo.vue index 4531097..68ffee7 100644 --- a/src/components/todos/SingleTodo/SingleTodo.vue +++ b/src/components/todos/SingleTodo/SingleTodo.vue @@ -4,16 +4,6 @@ -
- - - - - - -
+
+ + + + + + +
diff --git a/src/components/todos/todo/todo.ts b/src/components/todos/todo/todo.ts index de67750..b9f12f5 100644 --- a/src/components/todos/todo/todo.ts +++ b/src/components/todos/todo/todo.ts @@ -20,7 +20,7 @@ import VueIdb from 'vue-idb' import globalroutines from '../../../globalroutines/index' import $ from 'jquery' -import Api from "@api" +import Api from '@api' @Component({ @@ -43,7 +43,9 @@ export default class Todo extends Vue { itemDragEnd: any = null selrowid: number = 0 polling = null - mytypetransgroup: string = 'crossfade' + mytypetransgroup: string = 'flip-list' + tmpstrTodos: string = '' + loadDone: boolean = false fieldtochange: String [] = ['descr', 'completed', 'category', 'expiring_at', 'priority', 'id_prev', 'id_next', 'pos', 'enableExpiring', 'progress'] @@ -67,7 +69,7 @@ export default class Todo extends Vue { @Watch('$route.params.category') changecat() { // console.log('changecat') this.mytypetransgroup = 'nessuno' - this.updatetable().then(() => { + this.updatetable(false, '$route.params.category').then(() => { this.mytypetransgroup = 'crossfade' }) } @@ -80,23 +82,31 @@ export default class Todo extends Vue { return Todos.state.reload_fromServer } + set reload_fromServer(value: number) { + Todos.state.reload_fromServer = value + } + @Watch('todos_changed', { immediate: true, deep: true }) - changetodos_changed(value: string, oldValue: string) { + changetodos_changed(value: number, oldValue: number) { // this.$q.notify('Changed...') - console.log('Todos.state.todos_changed CHANGED!', value, oldValue) - this.updatetable(true) + if ((value > 1) && (this.loadDone)) { + // console.log('Todos.state.todos_changed CHANGED!', value, oldValue) + this.updatetable(true, 'todos_changed') + } } @Watch('reload_fromServer', { immediate: true }) - reload_fromServer_changed(value: string, oldValue: string) { - console.log('reload_fromServer_changed!', value, oldValue) - // if (value) { - Todos.actions.dbLoadTodo(false) + reload_fromServer_changed(value: number, oldValue: number) { + if (value > 0) { + // console.log('reload_fromServer_changed!', value, oldValue) + // if (value) { + Todos.actions.dbLoadTodo(false) - Todos.actions.updateArrayInMemory() + Todos.actions.updateArrayInMemory() + } // } } @@ -108,7 +118,37 @@ export default class Todo extends Vue { @Watch('testPao', { immediate: true, deep: true }) changedTestpao(value: string, oldValue: string) { // console.log('testpao CHANGED', value, oldValue) - this.updatetable(true) + // this.updatetable(true, 'testPao') + } + + getArrTodos() { + + let mystr = '' + let mythis = this + + mythis.tmpstrTodos = '' + globalroutines(null, 'readall', 'todos', null) + .then(function (alldata) { + const myrecs = [...alldata] + + myrecs.forEach(rec => { + mystr = mystr + rec.descr + '] [' + }) + + mythis.tmpstrTodos = 'TODOS: ' + mystr + }) + } + + setArrTodos() { + + let mystr = '' + let mythis = this + + mythis.tmpstrTodos = '' + globalroutines(null, 'write', 'todos', this.todos_arr[0]) + .then(function (alldata) { + mythis.getArrTodos() + }) } getCategory() { @@ -283,7 +323,7 @@ export default class Todo extends Vue { // Updated only elements modified await this.updateModifyRecords(true) - this.updatetable() + this.updatetable(false, 'onEnd') } @@ -299,7 +339,7 @@ export default class Todo extends Vue { }) if (update) - await this.updatetable(refresh) + await this.updatetable(refresh, 'updateModifyRecords') } @@ -322,6 +362,7 @@ export default class Todo extends Vue { async load() { + this.todos_arr = [...Todos.state.todos] // Set last category selected @@ -334,7 +375,7 @@ export default class Todo extends Vue { this.setarrPriority() this.clearArr() - await this.updatetable() + await this.updatetable(false, 'load') this.checkUpdate_everytime() @@ -345,6 +386,7 @@ export default class Todo extends Vue { }) */ + this.loadDone = true } // Call to check if need to refresh @@ -356,8 +398,8 @@ export default class Todo extends Vue { initcat() { - var tomorrow = new Date(); - tomorrow.setDate(tomorrow.getDate() + 1); + let tomorrow = new Date(); + tomorrow.setDate(tomorrow.getDate() + 1) const objtodo: ITodo = { @@ -433,7 +475,7 @@ export default class Todo extends Vue { const rismod = await this.modify(lastelem, false) this.saveItemToSyncAndDb(rescodes.DB.TABLE_SYNC_TODOS, 'POST', objtodo, true) - this.updatetable(false) + this.updatetable(false, 'insertTodo') // console.log('ESCO.........') @@ -582,7 +624,7 @@ export default class Todo extends Vue { // Delete item await globalroutines(this, 'delete', 'todos', null, id) .then((ris) => { - mythis.updatetable() + mythis.updatetable(false, 'deleteitem') }).catch((error) => { console.log('err: ', error) }) @@ -603,8 +645,8 @@ export default class Todo extends Vue { return itemnew.pos !== itemold.pos } - async updatetable(refresh: boolean = false) { - console.log('updatetable') + async updatetable(refresh: boolean = false, strpos = '') { + console.log('updatetable', strpos) this.prevRecords = [...this.todos_arr] @@ -808,7 +850,7 @@ export default class Todo extends Vue { // console.log('SET MODIFIED FALSE') if (update) - this.updatetable(false) + this.updatetable(false, 'modify') }) }) @@ -829,7 +871,7 @@ export default class Todo extends Vue { } clicktest2() { - this.updatetable(false) + this.updatetable(false, 'clicktest') console.log('Todos.state.todos', Todos.state.todos) } diff --git a/src/components/todos/todo/todo.vue b/src/components/todos/todo/todo.vue index 1e61910..0eedb26 100644 --- a/src/components/todos/todo/todo.vue +++ b/src/components/todos/todo/todo.vue @@ -12,7 +12,7 @@
- +
@@ -35,15 +35,24 @@ :after="[{icon: 'arrow_forward', content: true, handler () {}}]" v-on:keyup.enter="insertTodo"/> - - - + -
- - - -
+ + + + + + + + + + + + + + + +
diff --git a/src/css/themes/common.variables.styl b/src/css/themes/common.variables.styl index 4d659aa..6b8b26a 100644 --- a/src/css/themes/common.variables.styl +++ b/src/css/themes/common.variables.styl @@ -23,3 +23,4 @@ $positive = #21BA45 $negative = #DB2828 $info = #31CCEC $warning = #F2C037 + diff --git a/src/model/Todos.ts b/src/model/Todos.ts index f62482b..0634125 100644 --- a/src/model/Todos.ts +++ b/src/model/Todos.ts @@ -22,7 +22,7 @@ export interface ITodosState { networkDataReceived: boolean todos: ITodo[] todos_changed: number - reload_fromServer: boolean + reload_fromServer: number testpao: String insidePending: boolean } diff --git a/src/model/other.ts b/src/model/other.ts index dc9e839..6086868 100644 --- a/src/model/other.ts +++ b/src/model/other.ts @@ -1,5 +1,6 @@ export interface IToken { access: string + // browser: string token: string data_login: Date } diff --git a/src/root/home/home.ts b/src/root/home/home.ts index 0851073..8f62da5 100644 --- a/src/root/home/home.ts +++ b/src/root/home/home.ts @@ -59,7 +59,8 @@ export default class Home extends Vue { window.addEventListener('beforeinstallprompt', function (event) { // console.log('******************************** beforeinstallprompt fired') event.preventDefault() - console.log('§§§§§§§§§§§§§§§§§§§§ IMPOSTA DEFERRED PROMPT !!!!!!!!!!!!!!!!! ') + // console.log('§§§§§§§§§§§§§§§§§§§§ IMPOSTA DEFERRED PROMPT !!!!!!!!!!!!!!!!! ') + // #Todo++ IMPOSTA DEFERRED PROMPT return false }) @@ -69,6 +70,10 @@ export default class Home extends Vue { return Notification.permission } + NotServiceWorker () { + return (!('serviceWorker' in navigator)) + } + displayConfirmNotification() { let options = null if ('serviceWorker' in navigator) { @@ -88,10 +93,12 @@ export default class Home extends Vue { ] } - navigator.serviceWorker.ready - .then(function (swreg) { - swreg.showNotification('Successfully subscribed!', options) - }) + if ('serviceWorker' in navigator) { + navigator.serviceWorker.ready + .then(function (swreg) { + swreg.showNotification('Successfully subscribed!', options) + }) + } } } @@ -168,7 +175,6 @@ export default class Home extends Vue { } - test_fetch() { fetch('https:/httpbin.org/post', { method: 'POST', diff --git a/src/root/home/home.vue b/src/root/home/home.vue index 1aa581b..7813d58 100644 --- a/src/root/home/home.vue +++ b/src/root/home/home.vue @@ -5,6 +5,8 @@ + +
@@ -16,6 +18,12 @@ :label="$t('notification.titlegranted')" helper="Stato Notifiche"> + +
diff --git a/src/statics/i18n.js b/src/statics/i18n.js index 8f08e32..e10e65c 100644 --- a/src/statics/i18n.js +++ b/src/statics/i18n.js @@ -17,7 +17,7 @@ const messages = { msg: { hello: 'Buongiorno', myAppName: 'FreePlanet', - myDescriz: 'La prima App Libera' + myDescriz: '' }, pages: { home: 'Principale', @@ -143,7 +143,7 @@ const messages = { msg: { hello: 'Buenos Días', myAppName: 'FreePlanet', - myDescriz: 'La primera App Libera' + myDescriz: '' }, pages: { home: 'Principal', @@ -269,7 +269,7 @@ const messages = { msg: { hello: 'Hello!', myAppName: 'FreePlanet', - myDescriz: 'The first Free app' + myDescriz: '' }, pages: { home: 'Dashboard One', diff --git a/src/statics/js/storage.js b/src/statics/js/storage.js index f9b3841..88d097f 100644 --- a/src/statics/js/storage.js +++ b/src/statics/js/storage.js @@ -1,5 +1,6 @@ let idbKeyval = (() => { let db; + // console.log('idbKeyval...') function getDB() { if (!db) { diff --git a/src/store/Api/index.ts b/src/store/Api/index.ts index f495e52..0274374 100644 --- a/src/store/Api/index.ts +++ b/src/store/Api/index.ts @@ -155,7 +155,7 @@ export namespace ApiTool { let lettoqualcosa = false // console.log('A1) INIZIO.............................................................') - globalroutines(null, 'readall', table, null) + return globalroutines(null, 'readall', table, null) .then(function (alldata) { const myrecs = [...alldata] // console.log('----------------------- LEGGO QUALCOSA ') @@ -178,11 +178,11 @@ export namespace ApiTool { body: JSON.stringify(rec) }) .then(() => { - globalroutines(null, 'delete', table, null, rec._id) lettoqualcosa = true + return globalroutines(null, 'delete', table, null, rec._id) }) .then(() => { - globalroutines(null, 'delete', 'swmsg', null, mystrparam) + return globalroutines(null, 'delete', 'swmsg', null, mystrparam) }) .catch(function (err) { if (err.message === 'Failed to fetch') { @@ -206,8 +206,8 @@ export namespace ApiTool { .then((errorfromserver) => { // console.log('¨¨¨¨¨¨¨¨¨¨¨¨¨¨ errorfromserver:', errorfromserver) const mystate = errorfromserver ? 'offline' : 'online' - globalroutines(null, 'write', 'config', { _id: 2, stateconn: mystate }) GlobalStore.mutations.setStateConnection(mystate) + return globalroutines(null, 'write', 'config', { _id: 2, stateconn: mystate }) }) // console.log(' [Alternative] A2) ?????????????????????????? ESCO DAL LOOP !!!!!!!!!') diff --git a/src/store/Modules/GlobalStore.ts b/src/store/Modules/GlobalStore.ts index 3dbdc93..6c5aaa6 100644 --- a/src/store/Modules/GlobalStore.ts +++ b/src/store/Modules/GlobalStore.ts @@ -123,10 +123,10 @@ namespace Actions { function createPushSubscription(context) { // If Already subscribed, don't send to the Server DB - if (state.wasAlreadySubOnDb) { - // console.log('wasAlreadySubOnDb!') - return - } + // if (state.wasAlreadySubOnDb) { + // // console.log('wasAlreadySubOnDb!') + // return + // } if (!('serviceWorker' in navigator)) { return @@ -141,7 +141,7 @@ namespace Actions { let reg const mykey = process.env.PUBLICKEY_PUSH const mystate = state - navigator.serviceWorker.ready + return navigator.serviceWorker.ready .then(function (swreg) { reg = swreg return swreg.pushManager.getSubscription() @@ -149,11 +149,13 @@ namespace Actions { .then(function (subscription) { mystate.wasAlreadySubscribed = !(subscription === null) - if (mystate.wasAlreadySubOnDb) { - // console.log('User is already SAVED Subscribe on DB!') - return null + if (mystate.wasAlreadySubscribed) { + console.log('User is already SAVED Subscribe on DB!') + // return null + return subscription } else { // Create a new subscription + console.log('Create a new subscription') let convertedVapidPublicKey = urlBase64ToUint8Array(mykey) return reg.pushManager.subscribe({ userVisibleOnly: true, @@ -165,7 +167,7 @@ namespace Actions { saveNewSubscriptionToServer(context, newSub) }) .catch(function (err) { - console.log(err) + console.log('ERR createPushSubscription:', err) }) } @@ -178,11 +180,16 @@ namespace Actions { console.log('saveSubscriptionToServer: ', newSub) // console.log('context', context) - const options = { - title: translate('notification.title_subscribed'), - content: translate('notification.subscribed'), - openUrl: '/' - } + let options = null + + // If is not already stored in DB, then show the message to the user. + // if (!state.wasAlreadySubscribed) { + options = { + title: translate('notification.title_subscribed'), + content: translate('notification.subscribed'), + openUrl: '/' + } + // } let myres = { options: { ...options }, @@ -252,20 +259,22 @@ namespace Actions { 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 + if ('serviceWorker' in navigator) { + // 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) diff --git a/src/store/Modules/Todos.ts b/src/store/Modules/Todos.ts index 8e79f88..fd466bc 100644 --- a/src/store/Modules/Todos.ts +++ b/src/store/Modules/Todos.ts @@ -14,7 +14,7 @@ const state: ITodosState = { networkDataReceived: false, todos: [], todos_changed: 1, - reload_fromServer: false, + reload_fromServer: 0, testpao: 'Test', insidePending: false } @@ -43,7 +43,7 @@ namespace Mutations { function setTodos_changed(state: ITodosState) { state.todos_changed++ mutations.setTestpao('Cambiato : ' + String(state.todos_changed)) - console.log('******* state.todos_changed', state.todos_changed) + // console.log('******* state.todos_changed', state.todos_changed) } export const mutations = { @@ -78,10 +78,10 @@ namespace Actions { let count = await checkPendingMsg(null) if (count > 0) { - return navigator.serviceWorker.ready + return await navigator.serviceWorker.ready .then(function (sw) { - globalroutines(null, 'readall', 'swmsg') + return globalroutines(null, 'readall', 'swmsg') .then(function (arr_recmsg) { // let recclone = [...arr_recmsg] if (arr_recmsg.length > 0) { @@ -119,11 +119,11 @@ namespace Actions { .then(ris => { if (ris) { console.log('risPending = ', ris) - const result = sendSwMsgIfAvailable() + return sendSwMsgIfAvailable() .then(something => { if (something) { // Refresh data - waitAndRefreshData(context) + return waitAndRefreshData(context) } }) } @@ -204,7 +204,7 @@ namespace Actions { Todos.mutations.setTodos_changed() } - console.log('********** res', res, 'state.todos', state.todos, 'checkPending', checkPending) + console.log('********** res', 'state.todos', state.todos, 'checkPending', checkPending) // After Login will store into the indexedDb... diff --git a/src/store/Modules/UserStore.ts b/src/store/Modules/UserStore.ts index 636d794..8930196 100644 --- a/src/store/Modules/UserStore.ts +++ b/src/store/Modules/UserStore.ts @@ -89,7 +89,7 @@ namespace Mutations { state.verified_email = data.verified_email state.category = data.categorySel resetArrToken(state.tokens) - state.tokens.push({ access: 'auth ' + navigator.userAgent, token: state.x_auth_token, date_login: new Date() }) + state.tokens.push({ access: 'auth', token: state.x_auth_token, date_login: new Date() }) // console.log('state.tokens', state.tokens) } @@ -111,7 +111,7 @@ namespace Mutations { if (!state.tokens) { state.tokens = [] } - state.tokens.push({ access: 'auth ' + navigator.userAgent, token: data.x_auth_token, data_login: new Date() }) + state.tokens.push({ access: 'auth', token: data.x_auth_token, data_login: new Date() }) } function setServerCode(state: IUserState, num: number) { @@ -135,7 +135,7 @@ namespace Mutations { // Take only the others access (from others Browser) return arrtokens.filter((token: IToken) => { - return token.access !== 'auth ' + navigator.userAgent + return token.access !== 'auth' }) } @@ -368,14 +368,16 @@ namespace Actions { let sub = null - sub = await navigator.serviceWorker.ready - .then(function (swreg) { - const sub = swreg.pushManager.getSubscription() - return sub - }) - .catch(e => { - sub = null - }) + if ('serviceWorker' in navigator) { + sub = await navigator.serviceWorker.ready + .then(function (swreg) { + const sub = swreg.pushManager.getSubscription() + return sub + }) + .catch(e => { + sub = null + }) + } const options = { title: translate('notification.title_subscribed'), diff --git a/src/views/login/signin/signin.ts b/src/views/login/signin/signin.ts index 0ef5e6b..c85632e 100644 --- a/src/views/login/signin/signin.ts +++ b/src/views/login/signin/signin.ts @@ -148,9 +148,16 @@ export default class Signin extends Vue { .then((riscode) => { if (riscode === rescodes.OK) { GlobalStore.actions.createPushSubscription() + .then(ris => { + }) + .catch(e => { + console.log('ERROR = ' + e) + }) + .then(() => { + this.checkErrors(riscode) + this.$q.loading.hide() + }) } - this.checkErrors(riscode) - this.$q.loading.hide() }) .catch(error => { console.log('ERROR = ' + error) diff --git a/src/views/login/vreg/vreg.ts b/src/views/login/vreg/vreg.ts index 6578ff1..ab836e8 100644 --- a/src/views/login/vreg/vreg.ts +++ b/src/views/login/vreg/vreg.ts @@ -8,9 +8,7 @@ import { serv_constants } from '../../../store/Modules/serv_constants' import './vreg.css' import { ILinkReg } from '../../../model/other' -@Component({ - -}) +@Component({}) export default class Vreg extends Vue { public risultato: string = '---' public riscode: number = 0 @@ -43,20 +41,21 @@ export default class Vreg extends Vue { let param: ILinkReg param = { idlink: this.$route.query.idlink.toString() } console.log('idlink = ', param) - UserStore.actions.vreg(param).then((ris) => { - this.riscode = ris.code - this.risultato = ris.msg - console.log('RIS = ') - console.log(ris) + return UserStore.actions.vreg(param) + .then((ris) => { + this.riscode = ris.code + this.risultato = ris.msg + console.log('RIS = ') + console.log(ris) - if (this.verificatook) { - setTimeout(() => { - this.$router.replace('/signin') - }, 3000) - } + if (this.verificatook) { + setTimeout(() => { + this.$router.replace('/signin') + }, 3000) + } - }).catch((err) => { - console.log('ERR = ' + err) + }).catch((err) => { + console.log('ERR = ' + err) }) } } From bfa8a48211200df7e3e758c8e54b0815d7eae91b Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Thu, 14 Feb 2019 19:01:32 +0100 Subject: [PATCH 8/8] Fix: Todo Multi refresh ... fix some promises problem --- src/components/todos/todo/todo.ts | 7 +------ src/store/Modules/GlobalStore.ts | 6 +++--- src/store/Modules/Todos.ts | 2 +- 3 files changed, 5 insertions(+), 10 deletions(-) diff --git a/src/components/todos/todo/todo.ts b/src/components/todos/todo/todo.ts index b9f12f5..36e1a2e 100644 --- a/src/components/todos/todo/todo.ts +++ b/src/components/todos/todo/todo.ts @@ -363,7 +363,7 @@ export default class Todo extends Vue { async load() { - this.todos_arr = [...Todos.state.todos] + // this.todos_arr = [...Todos.state.todos] // Set last category selected localStorage.setItem(rescodes.localStorage.categorySel, this.getCategory()) @@ -380,11 +380,6 @@ export default class Todo extends Vue { this.checkUpdate_everytime() - /* - this.todos_arr.forEach((elem, index) => { - this.logelem('LOAD ' + index, elem) - }) - */ this.loadDone = true } diff --git a/src/store/Modules/GlobalStore.ts b/src/store/Modules/GlobalStore.ts index 6c5aaa6..0ebe182 100644 --- a/src/store/Modules/GlobalStore.ts +++ b/src/store/Modules/GlobalStore.ts @@ -183,16 +183,16 @@ namespace Actions { let options = null // If is not already stored in DB, then show the message to the user. - // if (!state.wasAlreadySubscribed) { + if (!state.wasAlreadySubscribed) { options = { title: translate('notification.title_subscribed'), content: translate('notification.subscribed'), openUrl: '/' } - // } + } let myres = { - options: { ...options }, + options, subs: newSub, others: { userId: UserStore.state.userId, diff --git a/src/store/Modules/Todos.ts b/src/store/Modules/Todos.ts index fd466bc..7c26958 100644 --- a/src/store/Modules/Todos.ts +++ b/src/store/Modules/Todos.ts @@ -201,7 +201,7 @@ namespace Actions { // console.log('******* UPDATE TODOS.STATE.TODOS !:', res.todos) if (body.todos) { state.todos = [...body.todos] - Todos.mutations.setTodos_changed() + // Todos.mutations.setTodos_changed() } console.log('********** res', 'state.todos', state.todos, 'checkPending', checkPending)