From e8d2d49829adbdbfb80692df94adbfd2229859b5 Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Wed, 13 Feb 2019 18:48:30 +0100 Subject: [PATCH] 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') }