fix: WebPush Notification

This commit is contained in:
Paolo Arena
2019-02-13 18:48:30 +01:00
parent 06635c87d4
commit e8d2d49829
10 changed files with 170 additions and 140 deletions

View File

@@ -13,9 +13,9 @@ importScripts('../statics/js/idb.js');
importScripts('../statics/js/storage.js'); importScripts('../statics/js/storage.js');
let port = 3001; let port = 3000;
if (self.location.hostname === 'localhost') { if (self.location.hostname === 'test.freeplanet.app') {
port = 3000; port = 3001;
} }
// console.log('SW-06 1'); // console.log('SW-06 1');
const cfgenv = { const cfgenv = {
@@ -481,7 +481,7 @@ self.addEventListener('notificationclose', function (event) {
self.addEventListener('push', function (event) { self.addEventListener('push', function (event) {
console.log('Push Notification received', 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) { if (event.data) {
data = JSON.parse(event.data.text()); data = JSON.parse(event.data.text());
@@ -492,7 +492,7 @@ self.addEventListener('push', function (event) {
icon: '/statics/icons/android-chrome-192x192.png', icon: '/statics/icons/android-chrome-192x192.png',
badge: '/statics/icons/android-chrome-192x192.png', badge: '/statics/icons/android-chrome-192x192.png',
data: { data: {
url: data.openUrl url: data.url
} }
}; };

View File

@@ -23,7 +23,6 @@ import { GlobalStore } from './store/Modules'
export default class App extends Vue { export default class App extends Vue {
public backgroundColor = 'whitesmoke' public backgroundColor = 'whitesmoke'
public isSubscribed = false
public $q public $q

View File

@@ -188,7 +188,7 @@
// use the "Offline" checkbox in DevTools Network panel // use the "Offline" checkbox in DevTools Network panel
let mythis = this let mythis = this
console.log('Event LOAD') // console.log('Event LOAD')
if (window) { if (window) {
window.addEventListener('load', function () { window.addEventListener('load', function () {
// console.log('2) ENTERING Event LOAD') // console.log('2) ENTERING Event LOAD')

View File

@@ -6,7 +6,8 @@ export type StateConnection = 'online' | 'offline'
export interface IGlobalState { export interface IGlobalState {
conta: number conta: number
isSubscribed: boolean wasAlreadySubOnDb: boolean
wasAlreadySubscribed: boolean
isLoginPage: boolean isLoginPage: boolean
layoutNeeded: boolean layoutNeeded: boolean
mobileMode: boolean mobileMode: boolean

View File

@@ -57,7 +57,7 @@ export default class Home extends Vue {
initprompt() { initprompt() {
window.addEventListener('beforeinstallprompt', function (event) { window.addEventListener('beforeinstallprompt', function (event) {
console.log('******************************** beforeinstallprompt fired') // console.log('******************************** beforeinstallprompt fired')
event.preventDefault() event.preventDefault()
console.log('§§§§§§§§§§§§§§§§§§§§ IMPOSTA DEFERRED PROMPT !!!!!!!!!!!!!!!!! ') console.log('§§§§§§§§§§§§§§§§§§§§ IMPOSTA DEFERRED PROMPT !!!!!!!!!!!!!!!!! ')
return false return false

View File

@@ -55,7 +55,7 @@ export namespace ApiTool {
return sendRequest(url, UserStore.state.lang, UserStore.state.x_auth_token, method, mydata) return sendRequest(url, UserStore.state.lang, UserStore.state.x_auth_token, method, mydata)
.then(resreceived => { .then(resreceived => {
// console.log('resreceived', resreceived) console.log('resreceived', resreceived)
ricevuto = true ricevuto = true
let res = resreceived.clone() let res = resreceived.clone()
if (process.env.DEV) { if (process.env.DEV) {
@@ -103,6 +103,7 @@ export namespace ApiTool {
return res.json() return res.json()
.then((body) => { .then((body) => {
// console.log('BODY RES = ', body)
return resolve({ res, body, status: res.status }) return resolve({ res, body, status: res.status })
}) })
.catch(e => { .catch(e => {

View File

@@ -8,8 +8,10 @@ import translate from './../../globalroutines/util'
import urlBase64ToUint8Array from '../../js/utility' import urlBase64ToUint8Array from '../../js/utility'
import messages from '../../statics/i18n' import messages from '../../statics/i18n'
import { UserStore } from '@store' import { GlobalStore, UserStore } from '@store'
import globalroutines from './../../globalroutines/index' 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 allTables = ['todos', 'sync_todos', 'sync_todos_patch', 'delete_todos', 'config', 'swmsg']
const allTablesAfterLogin = ['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 = { const state: IGlobalState = {
conta: 0, conta: 0,
isSubscribed: false, wasAlreadySubscribed: false,
wasAlreadySubOnDb: false,
isLoginPage: false, isLoginPage: false,
layoutNeeded: true, layoutNeeded: true,
mobileMode: false, mobileMode: false,
@@ -98,11 +101,16 @@ namespace Mutations {
} }
} }
function SetwasAlreadySubOnDb(state: IGlobalState, subscrib: boolean) {
state.wasAlreadySubOnDb = subscrib
}
export const mutations = { export const mutations = {
setConta: b.commit(setConta), setConta: b.commit(setConta),
setleftDrawerOpen: b.commit(setleftDrawerOpen), setleftDrawerOpen: b.commit(setleftDrawerOpen),
setCategorySel: b.commit(setCategorySel), 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) { function createPushSubscription(context) {
// If Already subscribed, don't send to the Server DB
if (state.wasAlreadySubOnDb) {
// console.log('wasAlreadySubOnDb!')
return
}
if (!('serviceWorker' in navigator)) { if (!('serviceWorker' in navigator)) {
return return
} }
@@ -132,10 +147,11 @@ namespace Actions {
return swreg.pushManager.getSubscription() return swreg.pushManager.getSubscription()
}) })
.then(function (subscription) { .then(function (subscription) {
mystate.isSubscribed = !(subscription === null) mystate.wasAlreadySubscribed = !(subscription === null)
if (mystate.isSubscribed) { if (mystate.wasAlreadySubOnDb) {
// console.log('User is already Subscribed!') // console.log('User is already SAVED Subscribe on DB!')
return null
} else { } else {
// Create a new subscription // Create a new subscription
let convertedVapidPublicKey = urlBase64ToUint8Array(mykey) let convertedVapidPublicKey = urlBase64ToUint8Array(mykey)
@@ -146,17 +162,7 @@ namespace Actions {
} }
}) })
.then(function (newSub) { .then(function (newSub) {
// console.log('newSub', newSub)
if (newSub) {
saveNewSubscriptionToServer(context, newSub) saveNewSubscriptionToServer(context, newSub)
.then(ris => {
mystate.isSubscribed = true
})
.catch(e => {
console.log('Error during Subscription!', e)
})
}
return null
}) })
.catch(function (err) { .catch(function (err) {
console.log(err) console.log(err)
@@ -165,8 +171,12 @@ namespace Actions {
// Calling the Server to Save in the MongoDB the Subscriber // Calling the Server to Save in the MongoDB the Subscriber
function saveNewSubscriptionToServer(context, newSub) { function saveNewSubscriptionToServer(context, newSub) {
// If already subscribed, exit
if (!newSub)
return
console.log('saveSubscriptionToServer: ', newSub) console.log('saveSubscriptionToServer: ', newSub)
console.log('context', context) // console.log('context', context)
const options = { const options = {
title: translate('notification.title_subscribed'), title: translate('notification.title_subscribed'),
@@ -180,19 +190,21 @@ namespace Actions {
others: { others: {
userId: UserStore.state.userId, userId: UserStore.state.userId,
access: UserStore.state.tokens[0].access 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) { async function deleteSubscriptionToServer(context) {
@@ -242,14 +254,14 @@ namespace Actions {
// REMOVE ALL SUBSCRIPTION // REMOVE ALL SUBSCRIPTION
console.log('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') console.log('... Ready')
reg.pushManager.getSubscription().then(function(subscription) { reg.pushManager.getSubscription().then(function (subscription) {
console.log(' Found Subscription...') console.log(' Found Subscription...')
subscription.unsubscribe().then(function(successful) { subscription.unsubscribe().then(function (successful) {
// You've successfully unsubscribed // You've successfully unsubscribed
console.log('You\'ve successfully unsubscribed') console.log('You\'ve successfully unsubscribed')
}).catch(function(e) { }).catch(function (e) {
// Unsubscription failed // Unsubscription failed
}) })
}) })

View File

@@ -90,7 +90,7 @@ namespace Mutations {
state.category = data.categorySel state.category = data.categorySel
resetArrToken(state.tokens) resetArrToken(state.tokens)
state.tokens.push({ access: 'auth ' + navigator.userAgent, token: state.x_auth_token, date_login: new Date() }) 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) { function setpassword(state: IUserState, newstr: string) {
@@ -318,7 +318,7 @@ namespace Actions {
const newuser = body const newuser = body
console.log('newuser', newuser, 'body', body) console.log('newuser', newuser)
Mutations.mutations.setServerCode(myres.status) Mutations.mutations.setServerCode(myres.status)
@@ -366,12 +366,16 @@ namespace Actions {
console.log('MYLANG = ' + state.lang) console.log('MYLANG = ' + state.lang)
return await navigator.serviceWorker.ready let sub = null
sub = await navigator.serviceWorker.ready
.then(function (swreg) { .then(function (swreg) {
const sub = swreg.pushManager.getSubscription() const sub = swreg.pushManager.getSubscription()
return sub return sub
}) })
.then((swreg) => { .catch(e => {
sub = null
})
const options = { const options = {
title: translate('notification.title_subscribed'), title: translate('notification.title_subscribed'),
@@ -385,7 +389,7 @@ namespace Actions {
idapp: process.env.APP_ID, idapp: process.env.APP_ID,
keyappid: process.env.PAO_APP_ID, keyappid: process.env.PAO_APP_ID,
lang: state.lang, lang: state.lang,
subs: swreg, subs: sub,
options options
} }
@@ -393,17 +397,15 @@ namespace Actions {
Mutations.mutations.setServerCode(rescodes.CALLING) Mutations.mutations.setServerCode(rescodes.CALLING)
return usertosend
}).then((usertosend) => {
let myres: IResult let myres: IResult
return Api.SendReq(call, 'POST', usertosend, true) return Api.SendReq(call, 'POST', usertosend, true)
.then(({ res, body }) => { .then(({ res, body }) => {
myres = res myres = res
if (res.code === serv_constants.RIS_CODE_LOGIN_ERR) {
if (body.code === serv_constants.RIS_CODE_LOGIN_ERR) {
Mutations.mutations.setServerCode(body.code) Mutations.mutations.setServerCode(body.code)
return body.code return { myres, body }
} }
Mutations.mutations.setServerCode(myres.status) Mutations.mutations.setServerCode(myres.status)
@@ -411,32 +413,33 @@ namespace Actions {
if (myres.status !== 200) { if (myres.status !== 200) {
return Promise.reject(rescodes.ERR_GENERICO) return Promise.reject(rescodes.ERR_GENERICO)
} }
return { res, body } return { myres, body }
}).then(({ res, body }) => { }).then(({ myres, body }) => {
if (myres.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) { if (myres.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) {
if (process.env.DEV) { if (process.env.DEV) {
console.log('CODE = ' + body.code) console.log('CODE = ' + body.code)
} }
return body.code return body.code
} else if (res.status !== 200) { } else if (myres.status !== 200) {
if (process.env.DEV) { if (process.env.DEV) {
console.log('CODE = ' + body.code) console.log('CODE = ' + body.code)
} }
return body.code return body.code
} }
if (res.status === 200) { if (myres.status === 200) {
GlobalStore.mutations.SetwasAlreadySubOnDb(body.subsExistonDb)
let myuser: IUserState = body.usertosend let myuser: IUserState = body.usertosend
if (myuser) { if (myuser) {
let userId = myuser.userId let userId = myuser.userId
let username = authData.username let username = authData.username
let verified_email = myuser.verified_email let verified_email = myuser.verified_email
if (process.env.DEV) { if (process.env.DEV) {
console.log('USERNAME = ' + username) console.log('USERNAME = ' + username, 'IDUSER= ' + userId)
console.log('IDUSER= ' + userId) // console.log('state.x_auth_token= ' + state.x_auth_token)
console.log('state.x_auth_token= ' + state.x_auth_token)
} }
Mutations.mutations.authUser({ Mutations.mutations.authUser({
@@ -454,6 +457,7 @@ namespace Actions {
localStorage.setItem(rescodes.localStorage.expirationDate, expirationDate.toString()) localStorage.setItem(rescodes.localStorage.expirationDate, expirationDate.toString())
localStorage.setItem(rescodes.localStorage.isLogged, String(true)) localStorage.setItem(rescodes.localStorage.isLogged, String(true))
localStorage.setItem(rescodes.localStorage.verified_email, String(verified_email)) localStorage.setItem(rescodes.localStorage.verified_email, String(verified_email))
localStorage.setItem(rescodes.localStorage.wasAlreadySubOnDb, String(GlobalStore.state.wasAlreadySubOnDb))
} }
} }
@@ -474,7 +478,6 @@ namespace Actions {
UserStore.mutations.setErrorCatch(error) UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode return UserStore.getters.getServerCode
}) })
})
} }
async function logout(context) { async function logout(context) {
@@ -488,6 +491,8 @@ namespace Actions {
// localStorage.removeItem(rescodes.localStorage.leftDrawerOpen) // localStorage.removeItem(rescodes.localStorage.leftDrawerOpen)
localStorage.removeItem(rescodes.localStorage.verified_email) localStorage.removeItem(rescodes.localStorage.verified_email)
localStorage.removeItem(rescodes.localStorage.categorySel) localStorage.removeItem(rescodes.localStorage.categorySel)
localStorage.removeItem(rescodes.localStorage.wasAlreadySubOnDb)
await GlobalStore.actions.clearDataAfterLogout() await GlobalStore.actions.clearDataAfterLogout()
@@ -530,7 +535,7 @@ namespace Actions {
async function autologin_FromLocalStorage(context) { async function autologin_FromLocalStorage(context) {
try { try {
console.log('*** autologin_FromLocalStorage ***') // console.log('*** autologin_FromLocalStorage ***')
// INIT // INIT
UserStore.mutations.setlang(process.env.LANG_DEFAULT) UserStore.mutations.setlang(process.env.LANG_DEFAULT)
@@ -555,14 +560,16 @@ namespace Actions {
const username = String(localStorage.getItem(rescodes.localStorage.username)) const username = String(localStorage.getItem(rescodes.localStorage.username))
const verified_email = localStorage.getItem(rescodes.localStorage.verified_email) === 'true' 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) UserStore.mutations.setAuth(token)
Mutations.mutations.authUser({ Mutations.mutations.authUser({
userId: userId, userId: userId,
username: username, username: username,
verified_email: verified_email verified_email: verified_email,
}) })
await setGlobal(false) await setGlobal(false)

View File

@@ -13,6 +13,7 @@ export const rescodes = {
localStorage: { localStorage: {
verified_email: 'vf', verified_email: 'vf',
wasAlreadySubOnDb: 'sb',
categorySel: 'cs', categorySel: 'cs',
isLogged: 'ilog', isLogged: 'ilog',
expirationDate: 'expdate', expirationDate: 'expdate',

View File

@@ -80,8 +80,17 @@ export default class Signin extends Vue {
this.showNotif({ type: 'positive', message: this.$t('login.completato') }) this.showNotif({ type: 'positive', message: this.$t('login.completato') })
this.$router.push('/') this.$router.push('/')
} else if (riscode === serv_constants.RIS_CODE_LOGIN_ERR) { } else if (riscode === serv_constants.RIS_CODE_LOGIN_ERR) {
// 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.showNotif(this.$t('login.errato'))
this.$router.push('/signin') this.$router.push('/signin')
})
} else if (riscode === rescodes.ERR_SERVERFETCH) { } else if (riscode === rescodes.ERR_SERVERFETCH) {
this.showNotif(this.$t('fetch.errore_server')) this.showNotif(this.$t('fetch.errore_server'))
} else if (riscode === rescodes.ERR_GENERICO) { } else if (riscode === rescodes.ERR_GENERICO) {
@@ -127,7 +136,7 @@ export default class Signin extends Vue {
console.log(this.signin) console.log(this.signin)
UserStore.actions.signin(this.signin) UserStore.actions.signin(this.signin)
.then((riscode) => { .then((riscode) => {
console.log('riscode=', riscode) // console.log('riscode=', riscode)
if (riscode === rescodes.OK) { if (riscode === rescodes.OK) {
router.push('/signin') router.push('/signin')
} }