- cleaned some code.

- routing offline
- pushNotification
This commit is contained in:
Paolo Arena
2019-02-12 12:06:01 +01:00
parent e755ada1ff
commit a024b78e95
21 changed files with 560 additions and 247 deletions

View File

@@ -6,7 +6,7 @@
// Questo è il swSrc
console.log(' [ VER-0.0.17 ] _---------________-----------_________------------__________________________ PAO: this is my custom service worker');
console.log(' [ VER-0.0.21 ] _---------________-----------_________------------__________________________ PAO: this is my custom service worker');
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js'); //++Todo: Replace with local workbox.js
importScripts('../statics/js/idb.js');
@@ -31,7 +31,7 @@ async function readAllData(table) {
}
async function clearAllData(table) {
// console.log('clearAllData', table);
console.log('clearAllData', table);
await idbKeyval.clearalldata(table)
}
@@ -104,6 +104,7 @@ if (workbox) {
// console.log('registerRoute!')
// console.log('DATABODY:', args.event.request.body)
let myres = null
// return fetch(args.event.request, args.event.headers)
return fetch(args.event.request, args.event.headers)
.then(function (res) {
myres = res
@@ -117,7 +118,7 @@ if (workbox) {
}
})
.then((clonedRes) => {
if (clonedRes !== null)
if (clonedRes !== undefined)
return clonedRes.json();
return null
})
@@ -141,6 +142,32 @@ if (workbox) {
})
workbox.routing.registerRoute(function (routeData) {
return (routeData.event.request.headers.get('accept').includes('text/html'));
}, function (args) {
return caches.match(args.event.request)
.then(function (response) {
if (response) {
return response;
} else {
return fetch(args.event.request)
.then(function (res) {
return caches.open('dynamic')
.then(function (cache) {
cache.put(args.event.request.url, res.clone());
return res;
})
})
.catch(function (err) {
return caches.match('/offline')
.then(function (res) {
return res;
});
});
}
})
});
workbox.routing.registerRoute(
new RegExp(/.*\/(?:statics\/icons).*$/),
workbox.strategies.cacheFirst({
@@ -206,18 +233,18 @@ if (workbox) {
})
);
// workbox.routing.registerRoute(
// new RegExp(/^http/),
// workbox.strategies.networkFirst({
// cacheName: 'all-stuff',
// plugins: [
// new workbox.expiration.Plugin({
// maxAgeSeconds: 10 * 24 * 60 * 60,
// // Only cache 10 requests.
// }),
// ]
// })
// );
workbox.routing.registerRoute(
new RegExp(/^http/),
workbox.strategies.networkFirst({
cacheName: 'all-stuff',
plugins: [
new workbox.expiration.Plugin({
maxAgeSeconds: 10 * 24 * 60 * 60,
// Only cache 10 requests.
}),
]
})
);
workbox.routing.registerRoute(
@@ -234,15 +261,6 @@ if ('serviceWorker' in navigator) {
}
self.addEventListener('fetch', function (event) {
event.respondWith(
fetch(event.request, event.headers)
.catch(err => {
console.log('_______________________ ERRORE FETCH SW: ', event.request, err)
return caches.match(event.request);
})
);
});
// self.addEventListener('fetch', (event) => {
// if (event.request.url === '/') {
@@ -260,7 +278,7 @@ self.addEventListener('fetch', function (event) {
// }
// event.respondWith(caches.match(event.request));
// });
//
// const syncStore = {}
// self.addEventListener('message', event => {
@@ -274,6 +292,47 @@ self.addEventListener('fetch', function (event) {
// console.log(event.data)
// })
// addEventListener('fetch', event => {
// // Prevent the default, and handle the request ourselves.
// event.respondWith(async function() {
// // Try to get the response from a cache.
// const cachedResponse = await caches.match(event.request);
// // Return it if we found one.
// if (cachedResponse && (event.request.cache !== 'no-cache'))
// return cachedResponse;
//
// // If we didn't find a match in the cache, use the network.
// return fetch(event.request);
// }());
// });
// self.addEventListener('fetch', function (event) {
// event.respondWith(
// caches.match(event.request).then(function (response) {
// return response ||
// fetch(event.request, event.headers)
// .catch(err => {
// console.log('_______________________ ERRORE FETCH SW: ', event.request, err)
// writeData('config', { _id: 2, stateconn: 'offline' })
// return caches.match(event.request);
// })
// })
// );
// });
// self.addEventListener('fetch', function (event) {
// event.respondWith(
// fetch(event.request, event.headers)
// .catch(err => {
// console.log('_______________________ ERRORE FETCH SW: ', event.request, err)
// writeData('config', {_id: 2, stateconn: 'offline'})
// return caches.match(event.request);
// })
// );
// });
self.addEventListener('sync', function (event) {
console.log('[Service Worker V5] Background syncing', event.tag);
@@ -295,13 +354,14 @@ self.addEventListener('sync', function (event) {
headers.append('Accept', 'application/json')
headers.append('x-auth', token)
// console.log('A1) INIZIO.............................................................');
event.waitUntil(
readAllData(table)
.then(function (alldata) {
const myrecs = [...alldata]
// console.log('----------------------- LEGGO QUALCOSA DAL WAITUNTIL ')
console.log('----------------------- LEGGO QUALCOSA DAL WAITUNTIL ')
if (myrecs) {
for (let rec of myrecs) {
//console.log('syncing', table, '', rec.descr)
@@ -312,7 +372,7 @@ self.addEventListener('sync', function (event) {
console.log('++++++++++++++++++ SYNCING !!!! ', rec.descr, table, 'FETCH: ', method, link, 'data:')
console.log('DATATOSAVE:', JSON.stringify(rec))
// console.log('DATATOSAVE:', JSON.stringify(rec))
// Insert/Delete/Update table to the server
fetch(link, {
@@ -322,19 +382,28 @@ self.addEventListener('sync', function (event) {
body: JSON.stringify(rec)
})
.then(() => {
console.log('DELETE SWMSG: ', mystrparam)
deleteItemFromData(table, rec._id)
deleteItemFromData('swmsg', mystrparam)
// console.log('config WRITE ONLINE')
writeData('config', { _id: 2, stateconn: 'online' })
})
.catch(function (err) {
console.log('DELETE : ', table, mystrparam)
deleteItemFromData(table, rec._id)
console.log('err', err, err.message)
// console.log('DELETE : ', table, mystrparam)
if (err.message === 'Failed to fetch') {
// console.log('config WRITE OFFLINE')
writeData('config', { _id: 2, stateconn: 'offline' })
}
console.log('!!!!!!!!!!!!!!! Error while sending data', err);
})
}
}
})
);
console.log('A2) ?????????????????????????? ESCO DAL LOOP !!!!!!!!! err=')
// console.log('A2) ?????????????????????????? ESCO DAL LOOP !!!!!!!!! err=')
}
}
}

View File

@@ -182,10 +182,10 @@
}
create () {
mounted () {
// Test this by running the code snippet below and then
// use the "Offline" checkbox in DevTools Network panel
// use the "Offline" checkbox in DevTools Network panel
let mythis = this
console.log('Event LOAD')
@@ -195,12 +195,12 @@
function updateOnlineStatus(event) {
if (navigator.onLine) {
console.log('ONLINE!')
console.log('EVENT ONLINE!')
// handle online status
GlobalStore.mutations.setStateConnection('online')
mythis.changeIconConn()
} else {
console.log('OFFLINE!')
console.log('EVENT OFFLINE!')
// handle offline status
GlobalStore.mutations.setStateConnection('offline')
mythis.changeIconConn()

View File

@@ -0,0 +1 @@
export {default as Offline} from './offline.vue'

View File

@@ -0,0 +1,29 @@
.svgclass{
color: white;
transform: translateY(0px);
}
.svgclass_animate {
transform: translateY(-70px);
color: red;
}
#sun {
animation: gravity 5s infinite;
}
@keyframes gravity{
0%{
transform: rotateY(0deg);
}
100%{
transform: rotateY(360deg);
}
}
#smile{
opacity: 0.1 !important;
fill: red;
}

View File

@@ -0,0 +1,53 @@
import Vue from 'vue'
import { Component } from 'vue-property-decorator'
import { TimelineLite, Back } from 'gsap'
import $ from 'jquery'
import Timeout = NodeJS.Timeout
@Component({
})
export default class Offline extends Vue {
logoimg: string = ''
created() {
this.logoimg = 'statics/images/' + process.env.LOGO_REG
this.animate()
}
animate () {
const timeline = new TimelineLite()
/*
let mysmile = $('#smile')
mysmile.attr('class', 'smile_hide')
setTimeout(() => {
mysmile.removeClass('smilevisible')
mysmile.addClass('smile_hide')
}, 1000)
setTimeout(() => {
mysmile.addClass('smilevisible')
mysmile.removeClass('smile_hide')
}, 10000)
*/
/*
timeline.to('#smile', 5, {
cy: 20,
cx: 60,
ease: Back.easeInOut // Specify an ease
})
*/
}
}

View File

@@ -0,0 +1,11 @@
<template>
<div id="offline">
Offline Page !
</div>
</template>
<script lang="ts" src="./offline.ts">
</script>
<style lang="scss" scoped>
@import './offline.scss';
</style>

View File

@@ -39,6 +39,7 @@ export default class SingleTodo extends Vue {
public colProgress: string = 'blue'
public togglemenu: boolean = false
public percentageProgress: number = 0
public itemtodoPrec: ITodo
$q: any
@Prop({ required: true }) itemtodo: ITodo
@@ -292,6 +293,9 @@ export default class SingleTodo extends Vue {
this.itemtodo.descr = this.precDescr
console.log('updateTodo', this.precDescr, this.itemtodo.descr)
console.log('itemtodo', this.itemtodo)
console.log('Prec:', this.itemtodoPrec)
this.watchupdate()
this.inEdit = false
// this.precDescr = this.itemtodo.descr

View File

@@ -60,7 +60,7 @@
</div>
</div>
<!--<div class="flex-item btn-item">-->
<!--{{classPosItemPopup}}-->
<!--{{itemtodo.expiring_at}}-->
<!--</div>-->
<!--<div class="flex-item btn-item">-->
<!--<q-btn class="mybtn" round color="" icon="delete" @click.native="removeitem(itemtodo._id)"></q-btn>-->

View File

@@ -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

View File

@@ -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)

View File

@@ -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();
});

View File

@@ -13,7 +13,7 @@ export interface IGlobalState {
menuCollapse: boolean
leftDrawerOpen: boolean
category: string
stateConnection: StateConnection
stateConnection: string
posts: IPost[]
listatodo: ITodoList[]
}

View File

@@ -17,8 +17,6 @@ export interface IUserState {
lang?: string
repeatPassword?: string
idToken?: string
tokens?: IToken[]
verified_email?: boolean

View File

@@ -10,7 +10,7 @@ export interface ILinkReg {
}
export interface IIdToken {
idToken: string
x_auth_token: string
}
export interface IResult {

View File

@@ -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' }
}
/*
{

View File

@@ -105,6 +105,7 @@ let idbKeyval = (() => {
});
},
async clearalldata(table) {
console.log('clearalldata', table)
return await withStore('readwrite', table, store => {
store.clear();
});

View File

@@ -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

View File

@@ -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')
})

View File

@@ -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<IGlobalState>('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)
}

View File

@@ -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) {

View File

@@ -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)