Merge pull request #16 from paoloar77/Precache

PushNotif
This commit is contained in:
Paolo Arena
2019-02-08 17:14:31 +01:00
committed by GitHub
70 changed files with 2591 additions and 950 deletions

View File

@@ -1,12 +1,14 @@
SERVICE_WORKER_FILE='sw.js' APP_VERSION="DEV 0.0.10"
SERVICE_WORKER_FILE='service-worker.js'
APP_ID='1' APP_ID='1'
VUE_APP_URL='prova SVILUPPO!' APP_URL='https://freeplanet.app'
PROVA_PAOLO='PROVA SVILUPPO' PROVA_PAOLO='PROVA SVILUPPO'
LANG_DEFAULT='it' LANG_DEFAULT='it'
MONGODB_HOST='http://localhost:3000'
PAO_APP_ID='KKPPAA5KJK435J3KSS9F9D8S9F8SD98F9SDF' PAO_APP_ID='KKPPAA5KJK435J3KSS9F9D8S9F8SD98F9SDF'
MASTER_KEY='KKPPSS5KJK435J3KSS9F9D8S9F8SD3CR3T' MASTER_KEY='KKPPSS5KJK435J3KSS9F9D8S9F8SD3CR3T'
MONGODB_HOST='http://localhost:3000'
LOGO_REG='freeplanet-logo-full.svg' LOGO_REG='freeplanet-logo-full.svg'
TEST_EMAIL='paolo.arena77@gmail.com' TEST_EMAIL='paolo.arena77@gmail.com'
TEST_USERNAME='paoloar77' TEST_USERNAME='paoloar77'
TEST_PASSWORD='mypassword@1A' TEST_PASSWORD='mypassword@1A'
PUBLICKEY_PUSH='BGxRrFWnPoa_ImUaWXmeEOFVI9VNKVKaAPsvsM1XY6wn24yxp9MyOQ4crNYCJKxSXV65Y1GblW5_VLoamedcZ1I'

View File

@@ -9,7 +9,8 @@ switch (process.env.NODE_ENV) {
path = `.env.development` path = `.env.development`
break break
default: default:
path = `.env` path = `.env.production`
break
} }
// console.log("PATH", path) // console.log("PATH", path)

36
package-lock.json generated
View File

@@ -1,6 +1,6 @@
{ {
"name": "freeplanet", "name": "freeplanet",
"version": "0.0.1", "version": "0.0.2",
"lockfileVersion": 1, "lockfileVersion": 1,
"requires": true, "requires": true,
"dependencies": { "dependencies": {
@@ -11193,6 +11193,11 @@
} }
} }
}, },
"idb-keyval": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/idb-keyval/-/idb-keyval-3.1.0.tgz",
"integrity": "sha512-iFwFN5n00KNNnVxlOOK280SJJfXWY7pbMUOQXdIXehvvc/mGCV/6T2Ae+Pk2KwAkkATDTwfMavOiDH5lrJKWXQ=="
},
"ieee754": { "ieee754": {
"version": "1.1.12", "version": "1.1.12",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.12.tgz", "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.12.tgz",
@@ -11216,6 +11221,15 @@
"resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
"integrity": "sha1-nbHb0Pr43m++D13V5Wu2BigN5ps=" "integrity": "sha1-nbHb0Pr43m++D13V5Wu2BigN5ps="
}, },
"immortal-db": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/immortal-db/-/immortal-db-1.0.2.tgz",
"integrity": "sha512-7EaVr6vUaaqsl9Jnp+CY4FzA1jIQD+o1tFEY2+O4ibYgmVB+FEWDoyUNN/naq9ZfiYKw4+uly1fpxk0xyE358w==",
"requires": {
"idb-keyval": "3.1.0",
"js-cookie": "2.2.0"
}
},
"import-cwd": { "import-cwd": {
"version": "2.1.0", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/import-cwd/-/import-cwd-2.1.0.tgz", "resolved": "https://registry.npmjs.org/import-cwd/-/import-cwd-2.1.0.tgz",
@@ -21098,7 +21112,7 @@
"dependencies": { "dependencies": {
"minimist": { "minimist": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "http://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz",
"integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=",
"dev": true "dev": true
} }
@@ -24014,7 +24028,7 @@
"graceful-fs": "4.1.15", "graceful-fs": "4.1.15",
"make-dir": "1.3.0", "make-dir": "1.3.0",
"unique-string": "1.0.0", "unique-string": "1.0.0",
"write-file-atomic": "2.3.0", "write-file-atomic": "2.4.2",
"xdg-basedir": "3.0.0" "xdg-basedir": "3.0.0"
} }
}, },
@@ -24028,9 +24042,9 @@
} }
}, },
"write-file-atomic": { "write-file-atomic": {
"version": "2.3.0", "version": "2.4.2",
"resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.2.tgz",
"integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", "integrity": "sha512-s0b6vB3xIVRLWywa6X9TOMA7k9zio0TMOsl9ZnDkliA/cfJlpHXAscj0gbHVJiTdIuAYpIyqS5GW91fqm6gG5g==",
"dev": true, "dev": true,
"requires": { "requires": {
"graceful-fs": "4.1.15", "graceful-fs": "4.1.15",
@@ -25489,9 +25503,9 @@
}, },
"dependencies": { "dependencies": {
"ansi-escapes": { "ansi-escapes": {
"version": "3.1.0", "version": "3.2.0",
"resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz",
"integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==", "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==",
"dev": true "dev": true
}, },
"chardet": { "chardet": {
@@ -25502,7 +25516,7 @@
}, },
"external-editor": { "external-editor": {
"version": "2.2.0", "version": "2.2.0",
"resolved": "http://registry.npmjs.org/external-editor/-/external-editor-2.2.0.tgz", "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-2.2.0.tgz",
"integrity": "sha512-bSn6gvGxKt+b7+6TKEv1ZycHleA7aHhRHyAqJyp5pbUFuYYNIzpZnQDk7AsYckyWdEnTeAnay0aCy2aV6iTk9A==", "integrity": "sha512-bSn6gvGxKt+b7+6TKEv1ZycHleA7aHhRHyAqJyp5pbUFuYYNIzpZnQDk7AsYckyWdEnTeAnay0aCy2aV6iTk9A==",
"dev": true, "dev": true,
"requires": { "requires": {
@@ -25537,7 +25551,7 @@
"integrity": "sha512-h+xtnyk4EwKvFWHrUYsWErEVR+igKtLdchu+o0Z1RL7VU/jVMFbYir2bp6bAj8efFNxWqHX0dIss6fJQ+/+qeQ==", "integrity": "sha512-h+xtnyk4EwKvFWHrUYsWErEVR+igKtLdchu+o0Z1RL7VU/jVMFbYir2bp6bAj8efFNxWqHX0dIss6fJQ+/+qeQ==",
"dev": true, "dev": true,
"requires": { "requires": {
"ansi-escapes": "3.1.0", "ansi-escapes": "3.2.0",
"chalk": "2.4.1", "chalk": "2.4.1",
"cli-cursor": "2.1.0", "cli-cursor": "2.1.0",
"cli-width": "2.2.0", "cli-width": "2.2.0",

View File

@@ -1,7 +1,13 @@
{ {
"name": "freeplanet", "name": "freeplanet",
"version": "0.0.1", "version": "0.0.4",
"private": true, "private": true,
"keywords": [
"freeplanet",
"free social"
],
"author": "Paolo Arena",
"license": "MIT",
"scripts": { "scripts": {
"lint": "tslint --project tsconfig.json", "lint": "tslint --project tsconfig.json",
"lint:fix": "tslint --project tsconfig.json --fix", "lint:fix": "tslint --project tsconfig.json --fix",
@@ -10,11 +16,12 @@
"pwa": "NODE_ENV=development NODE_OPTIONS=--max_old_space_size=4096 DEBUG=v8:* quasar dev -m pwa", "pwa": "NODE_ENV=development NODE_OPTIONS=--max_old_space_size=4096 DEBUG=v8:* quasar dev -m pwa",
"test:unit": "jest", "test:unit": "jest",
"test:cover": "jest --coverage", "test:cover": "jest --coverage",
"build": "quasar build -m pwa && workbox generateSW workbox-config.js", "build": "quasar build -m pwa",
"build:clean": "quasar clean", "build:clean": "quasar clean",
"serve": "quasar serve ./dist/pwa-mat", "serve": "quasar serve ./dist/pwa-mat",
"serve:coverage": "quasar serve test/coverage/lcov-report/ --cache 0 --port 8788", "serve:coverage": "quasar serve test/coverage/lcov-report/ --cache 0 --port 8788",
"deploy": "deploy.sh" "deploy": "deploy.sh",
"generate-sw": "workbox generateSW workbox-config.js"
}, },
"dependencies": { "dependencies": {
"@types/vuelidate": "^0.7.0", "@types/vuelidate": "^0.7.0",
@@ -29,6 +36,7 @@
"graphql": "^0.13.2", "graphql": "^0.13.2",
"graphql-tag": "^2.8.0", "graphql-tag": "^2.8.0",
"gsap": "^2.0.2", "gsap": "^2.0.2",
"immortal-db": "^1.0.2",
"jquery": "^3.3.1", "jquery": "^3.3.1",
"js-cookie": "^2.2.0", "js-cookie": "^2.2.0",
"localforage": "^1.7.3", "localforage": "^1.7.3",

View File

@@ -59,7 +59,7 @@ module.exports = function (ctx) {
store: 'src/store/index.ts' store: 'src/store/index.ts'
}, },
// app plugins (/src/plugins) // app plugins (/src/plugins)
plugins: ['i18n', 'axios', 'vee-validate', 'myconfig', 'local-storage', 'error-handler', 'indexdb', 'vue-idb'], plugins: ['i18n', 'axios', 'vee-validate', 'myconfig', 'local-storage', 'error-handler', 'globalroutines', 'vue-idb'],
css: [ css: [
'app.styl' 'app.styl'
], ],
@@ -88,6 +88,7 @@ module.exports = function (ctx) {
.alias .alias
.set('~', __dirname) .set('~', __dirname)
.set('@', path.resolve(__dirname, 'src')) .set('@', path.resolve(__dirname, 'src'))
// .set('env', path.resolve(__dirname, 'config/helpers/env.js'))
config.module config.module
.rule('template-engine') .rule('template-engine')
.test(/\.pug$/) .test(/\.pug$/)
@@ -180,8 +181,18 @@ module.exports = function (ctx) {
} }
}, },
pwa: { pwa: {
// runtimeCaching: [
// {
// urlPattern: '/statics',
// handler: 'networkFirst'
// }
// ],
// workboxPluginMode: 'GenerateSW',
workboxPluginMode: 'InjectManifest', workboxPluginMode: 'InjectManifest',
// workboxOptions: {}, workboxOptions: {
// swSrc: 'src/sw.js',
},
manifest: { manifest: {
name: 'Free Planet', name: 'Free Planet',
short_name: 'freeplanet', short_name: 'freeplanet',

View File

@@ -1,24 +1,419 @@
/* /*
* This file (which will be your service worker) * This file (which will be your service worker)
* is picked up by the build system ONLY if * is picked up by the build system ONLY if
* quasar.conf > pwa > workboxPluginMode is set to "InjectManifest" * quasar.conf > pwa > workboxPluginMode is set to "InjectManifest"
*/ */
self.addEventListener('install', function(event) { // Questo è il swSrc
console.log('[Service Worker] Installing Service Worker ...', event);
});
self.addEventListener('activate', function(event) { console.log('SW-06 ___________________________ PAO: this is my custom service worker');
console.log('[Service Worker] Activating Service Worker ...', event);
return self.clients.claim();
});
self.addEventListener('fetch', function(event) { importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js'); //++Todo: Replace with local workbox.js
//console.log('[Service Worker] Fetching something ....', event); importScripts('../statics/js/idb.js');
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') { importScripts('../statics/js/storage.js');
console.log('SAME ORIGIN!', event);
return;
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('SERVERWEB=', cfgenv.serverweb)
// console.log('serverweb', cfgenv.serverweb)
async function writeData(table, data) {
console.log('writeData', table, data);
await idbKeyval.setdata(table, data);
}
async function readAllData(table) {
console.log('readAllData', table);
return await idbKeyval.getalldata(table);
}
async function clearAllData(table) {
console.log('clearAllData', table);
await idbKeyval.clearalldata(table)
}
async function deleteItemFromData(table, id) {
console.log('deleteItemFromData', table, 'ID:', id);
await idbKeyval.deletedata(table, id)
}
// self.addEventListener('activate', function(event) {
// event.waitUntil(
// // createDB()
// );
// });
if (!workbox) {
let workbox = new self.WorkboxSW();
console.log('SW-06 3');
}
if (workbox) {
// const url = new URL(location.href);
// const debug = url.searchParams.has('debug');
const debug = false;
workbox.setConfig({ debug: debug });
workbox.core.setCacheNameDetails({ prefix: "freeplanet" });
/**
* The workboxSW.precacheAndRoute() method efficiently caches and responds to
* requests for URLs in the manifest.
* See https://goo.gl/S9QRab
*/
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
// workbox.routing.registerRoute(/^http/, workbox.strategies.networkFirst(), 'GET');
workbox.routing.registerRoute(
new RegExp(/\.(?:png|gif|jpg|jpeg|svg)$/),
workbox.strategies.staleWhileRevalidate({
cacheName: 'images',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
}),
],
}),
);
workbox.routing.registerRoute(
new RegExp(/.*(?:googleapis|gstatic)\.com.*$/),
workbox.strategies.staleWhileRevalidate({
cacheName: 'google-fonts',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 30,
}),
]
})
);
workbox.routing.registerRoute(
new RegExp(cfgenv.serverweb + '/todos/'),
function (args) {
console.log('registerRoute!')
return fetch(args.event.request, args.event.headers)
.then(function (res) {
console.log('1° ******* [[[ SERVICE-WORKER ]]] registerRoute fetch: ', args.event)
// LOAD FROM SERVER , AND SAVE INTO INDEXEDDB
console.log('res.status', res.status)
if (res.status === 200) {
var clonedRes = res.clone();
clearAllData('todos')
.then(function () {
return clonedRes.json();
})
.then(function (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])
}
}
});
return res
}
})
}
);
workbox.routing.registerRoute(
new RegExp(/.*\/(?:statics\/icons).*$/),
workbox.strategies.cacheFirst({
cacheName: 'image-cache',
plugins: [
new workbox.expiration.Plugin({
maxAgeSeconds: 30 * 24 * 60 * 60,
}),
]
})
);
workbox.routing.registerRoute(
new RegExp(/.*\/(?:css|font).*/),
workbox.strategies.cacheFirst({
cacheName: 'css-fonts',
plugins: [
new workbox.expiration.Plugin({
maxAgeSeconds: 30 * 24 * 60 * 60,
}),
]
})
);
workbox.routing.registerRoute(
new RegExp('https://cdnjs.coudflare.com/ajax/libs/material-design-lite/1.3.0/material.indigo-pink.min.css'),
workbox.strategies.staleWhileRevalidate({
cacheName: 'material-css',
plugins: [
new workbox.expiration.Plugin({
maxAgeSeconds: 30 * 24 * 60 * 60,
}),
]
})
);
// Storage
workbox.routing.registerRoute(
new RegExp(/.*(?:storage\.freeplanet)\.app.*$/),
workbox.strategies.staleWhileRevalidate({
cacheName: 'storage',
plugins: [
new workbox.expiration.Plugin({
maxAgeSeconds: 30 * 24 * 60 * 60,
// Only cache 10 requests.
maxEntries: 200,
}),
]
})
);
workbox.routing.registerRoute(
new RegExp(/.*\/(?:statics).*$/),
workbox.strategies.cacheFirst({
cacheName: 'statics',
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(
new RegExp('/admin/'),
workbox.strategies.networkOnly()
);
}
if ('serviceWorker' in navigator) {
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(fetch(event.request)); });
// self.addEventListener('fetch', function (event) {
// console.log('[Service Worker] Fetching something ....', event);
// console.log('event.request.cache=', event.request.cache)
// if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') {
// console.log('SAME ORIGIN!', event);
// return;
// }
// event.respondWith(caches.match(event.request));
// });
// const syncStore = {}
// self.addEventListener('message', event => {
// if (event.data.type === 'sync') {
// // get a unique id to save the data
// const id = uuid()
// syncStore[id] = event.data
// // register a sync and pass the id as tag for it to get the data
// self.registration.sync.register(id)
// }
// console.log(event.data)
// })
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:')
// Insert/Delete/Update table to the server
fetch(link, {
method: method,
headers: headers,
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);
// }
console.log('DELETE: ', mystrparam)
deleteItemFromData('swmsg', mystrparam)
})
.catch(function (err) {
console.log('!!!!!!!!!!!!!!! Error while sending data', err);
});
}
}
})
);
console.log('A2) ?????????????????????????? ESCO DAL LOOP !!!!!!!!! err=')
}
}
}
})
;
/*
// send message to serviceWorker
function sync (url, options) {
navigator.serviceWorker.controller.postMessage({type: 'sync', url, options})
}
const syncStore = {}
self.addEventListener('message', event => {
if(event.data.type === 'sync') {
// get a unique id to save the data
const id = uuid()
syncStore[id] = event.data
// register a sync and pass the id as tag for it to get the data
self.registration.sync.register(id)
}
console.log(event.data)
})
self.addEventListener('sync', event => {
// get the data by tag
const {url, options} = syncStore[event.tag]
event.waitUntil(fetch(url, options))
})
*/
self.addEventListener('notificationclick', function(event) {
var notification = event.notification;
var action = event.action;
console.log(notification);
if (action === 'confirm') {
console.log('Confirm was chosen');
notification.close();
} else {
console.log(action);
event.waitUntil(
clients.matchAll()
.then(function(clis) {
var client = clis.find(function(c) {
return c.visibilityState === 'visible';
});
if (client !== undefined) {
client.navigate(notification.data.url);
client.focus();
} else {
clients.openWindow(notification.data.url);
}
notification.close();
})
);
}
});
self.addEventListener('notificationclose', function(event) {
console.log('Notification was closed', event);
});
self.addEventListener('push', function(event) {
console.log('Push Notification received', event);
var data = {title: 'New!', content: 'Something new happened!', openUrl: '/'};
if (event.data) {
data = JSON.parse(event.data.text());
}
var options = {
body: data.content,
icon: '/statics/icons/android-chrome-192x192.png',
badge: '/statics/icons/android-chrome-192x192.png',
data: {
url: data.openUrl
}
};
event.waitUntil(
self.registration.showNotification(data.title, options)
);
}); });

View File

@@ -3,22 +3,25 @@
* when building for PRODUCTION * when building for PRODUCTION
*/ */
import {register} from 'register-service-worker' import { register } from 'register-service-worker'
register(process.env.SERVICE_WORKER_FILE, { register(process.env.SERVICE_WORKER_FILE, {
ready() { ready() {
console.log('READY::: App is being served from cache by a service worker.') console.log('READY::: App is being served from cache by a service worker.')
}, },
registered(registration) { // registration -> a ServiceWorkerRegistration instance registered(registration) { // registration -> a ServiceWorkerRegistration instance
console.log('REGISTERED::: !!!') console.log('REGISTERED::: !!!', process.env.SERVICE_WORKER_FILE)
}, },
cached(registration) { // registration -> a ServiceWorkerRegistration instance cached(registration) {
console.log('CACHED::: Content has been cached for offline use.') console.log('CACHED::: Content has been cached for offline use.')
}, },
updatefound(registration) { // registration -> a ServiceWorkerRegistration instance updatefound(registration) {
console.log('UPDATEFOUND::: New content is downloading.') console.log('UPDATEFOUND::: New content is downloading.')
}, },
updated(registration) { // registration -> a ServiceWorkerRegistration instance updated(registration) {
console.log('New content is available; please refresh.') console.log('New content is available; please refresh.')
}, },
offline() { offline() {
@@ -33,3 +36,4 @@ register(process.env.SERVICE_WORKER_FILE, {
// ServiceWorkerRegistration: https://developer.mozilla.org/en-uk/docs/Web/API/ServiceWorkerRegistration // ServiceWorkerRegistration: https://developer.mozilla.org/en-uk/docs/Web/API/ServiceWorkerRegistration
// "build": "quasar build -m pwa && workbox generateSW workbox-config.js",

41
src/App.scss Normal file
View File

@@ -0,0 +1,41 @@
.fade-enter-active, .fade-leave-active {
transition: opacity .2s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */
{
opacity: 0;
}
.slide-enter {
}
.slide-enter-active {
animation: slide-in 0.2s ease-out forwards;
}
.slide-leave {
}
.slide-leave-active {
animation: slide-out 0.5s ease-out forwards;
}
@keyframes slide-in {
from {
transform: translateX(-500px);
}
to {
transform: translateX(0);
}
}
@keyframes slide-out {
from {
transform: translateX(0);
}
to {
transform: translateX(1600px);
}
}

55
src/App.ts Normal file
View File

@@ -0,0 +1,55 @@
import Vue from 'vue'
import { Component } from 'vue-property-decorator'
import { UserStore } from '@store'
import { EventBus, RootState, storeBuilder, DebugMode } from '@store'
import router from './router'
import $ from 'jquery'
import Header from './components/Header.vue'
import globalroutines from './globalroutines/index'
import { GlobalStore } from './store/Modules'
@Component({
components: {
appHeader: Header
},
router
})
export default class App extends Vue {
public backgroundColor = 'whitesmoke'
public isSubscribed = false
public $q
created() {
if (process.env.DEV) {
console.info('SESSIONE IN SVILUPPO ! (DEV)')
console.info(process.env)
}
if (process.env.PROD) {
console.info('SESSIONE IN PRODUZIONE!')
// console.info(process.env)
}
UserStore.actions.autologin()
.then((loginEseguito) => {
if (loginEseguito) {
globalroutines(this, 'loadapp', '')
// this.$router.replace('/')
// Create Subscription to Push Notification
GlobalStore.actions.createPushSubscription()
}
})
}
}

View File

@@ -15,89 +15,8 @@
</div> </div>
</template> </template>
<script lang="ts"> <script lang="ts" src="./App.ts">
import Vue from "vue"
import { Component } from 'vue-property-decorator'
import { UserStore } from '@store'
import { EventBus, RootState, storeBuilder, DebugMode } from '@store'
import router from "./router"
import $ from "jquery"
import Header from './components/Header.vue'
@Component({
components: {
appHeader: Header,
},
router
})
export default class App extends Vue {
public backgroundColor = 'whitesmoke'
created() {
//this.title = 'My Vue and CosmosDB Heroes App'
if (process.env.DEV) {
console.info("SESSIONE IN SVILUPPO ! (DEV)")
console.info(process.env)
}
if (process.env.PROD) {
console.info("SESSIONE IN PRODUZIONE!")
console.info(process.env)
}
UserStore.actions.autologin()
.then((loginEseguito) => {
if (loginEseguito) {
// this.$router.replace('/')
}
})
}
}
</script> </script>
<style lang="scss" scoped>
<style> @import './App.scss';
.fade-enter-active, .fade-leave-active {
transition: opacity .2s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */
{
opacity: 0;
}
.slide-enter {
}
.slide-enter-active {
animation: slide-in 0.2s ease-out forwards;
}
.slide-leave {
}
.slide-leave-active {
animation: slide-out 0.5s ease-out forwards;
}
@keyframes slide-in {
from {
transform: translateX(-500px);
}
to {
transform: translateX(0);
}
}
@keyframes slide-out {
from {
transform: translateX(0);
}
to {
transform: translateX(1600px);
}
}
</style> </style>

View File

@@ -29,7 +29,7 @@
<q-toolbar-title> <q-toolbar-title>
{{$t('msg.myAppName')}} {{$t('msg.myAppName')}}
<div slot="subtitle">{{$t('msg.myDescriz')}}</div> <div slot="subtitle">{{$t('msg.myDescriz')}} {{ getAppVersion() }}</div>
</q-toolbar-title> </q-toolbar-title>
<q-select class="sel_lang" v-model="lang" stack-label="" :options="selectOpLang"/> <q-select class="sel_lang" v-model="lang" stack-label="" :options="selectOpLang"/>
@@ -96,6 +96,10 @@
localStorage.setItem(rescodes.localStorage.leftDrawerOpen, value.toString()) localStorage.setItem(rescodes.localStorage.leftDrawerOpen, value.toString())
} }
getAppVersion() {
// return "AA"
return "[" + process.env.APP_VERSION + "]"
}
get lang() { get lang() {
return this.$q.i18n.lang return this.$q.i18n.lang
} }
@@ -106,7 +110,7 @@
// dynamic import, so loading on demand only // dynamic import, so loading on demand only
import(`quasar-framework/i18n/${lang}`).then(lang => { import(`quasar-framework/i18n/${lang}`).then(lang => {
this.$q.i18n.set(lang.default) this.$q.i18n.set(lang.default)
import(`src/i18n`).then(function () { import(`src/statics/i18n`).then(function () {
}) })
}) })
} }

View File

@@ -80,7 +80,7 @@ export default class Category extends Vue {
} }
async loadCat() { async loadCat() {
await this.$db.categories.toArray().then(ris => this.categories_loc = ris) // await this.$db.categories.toArray().then(ris => this.categories_loc = ris)
this.updatetable() this.updatetable()
} }

View File

@@ -53,7 +53,7 @@
</q-table> </q-table>
<!-- <SingleTodo :itemcat='mycat' v-for="mycat of categories_arr" :key="mycat.id"/> --> <!-- <SingleTodo :itemcat='mycat' v-for="mycat of categories_arr" :key="mycat._id"/> -->
</div> </div>
</q-page> </q-page>

View File

@@ -100,7 +100,7 @@ export default class Tabledata extends Vue {
objcat.descr_it = this.category objcat.descr_it = this.category
// Add to Indexdb // Add to Indexdb
await this.$db.categories.add(objcat await this.$db.categories.put(objcat
).then(ris => { ).then(ris => {
myid = ris myid = ris
}) })

View File

@@ -13,7 +13,7 @@ export default class Logo extends Vue {
logoimg: string = '' logoimg: string = ''
created() { created() {
this.logoimg = 'statics/' + process.env.LOGO_REG this.logoimg = 'statics/images/' + process.env.LOGO_REG
this.animate() this.animate()
} }

View File

@@ -57,15 +57,7 @@ $heightitem: 19px;
font-size: 0.75rem; font-size: 0.75rem;
} }
.todo-menu {
min-width: 202px;
}
.item-menu{
font-size: 1rem;
}
.titleLista-item { .titleLista-item {
max-width: 92px; max-width: 92px;
@@ -144,9 +136,6 @@ $heightitem: 19px;
color: #888; color: #888;
} }
.menuProgress {
}
.colProgress { .colProgress {
} }

View File

@@ -130,7 +130,7 @@ export default class SingleTodo extends Vue {
// this.classDescr += ' show' // this.classDescr += ' show'
// } // }
// this.getinputdescr = 'inputdescr' + this.itemtodo.id // this.getinputdescr = 'inputdescr' + this.itemtodo._id
// console.log('classDescrEdit = ', this.classDescrEdit) // console.log('classDescrEdit = ', this.classDescrEdit)
// console.log('classDescr', this.classDescr) // console.log('classDescr', this.classDescr)
@@ -234,6 +234,8 @@ export default class SingleTodo extends Vue {
exitEdit(singola: boolean = false) { exitEdit(singola: boolean = false) {
if (this.inEdit) { if (this.inEdit) {
if (this.precDescr !== this.itemtodo.descr)
this.updateTodo()
// console.log('exitEdit') // console.log('exitEdit')
this.inEdit = false this.inEdit = false
this.updateClasses this.updateClasses
@@ -243,11 +245,30 @@ export default class SingleTodo extends Vue {
keyDownArea(e) { keyDownArea(e) {
if (e.key === 'Enter' && !e.shiftKey) { /*
e.preventDefault() if ((e.key === 'ArrowUp') && !e.shiftKey) {
e.key = 'Tab'
e.shiftKey = true
}
if ((e.key === 'ArrowDown') && !e.shiftKey) {
let nextInput = inputs.get(inputs.index(this) + 1)
if (nextInput) {
nextInput.focus()
}
}
*/
if (((e.key === 'Enter') || (e.key === 'Tab')) && !e.shiftKey) {
this.updateTodo() this.updateTodo()
this.deselectRiga()
this.faiFocus('insertTask', true) if ((e.key === 'Tab') && !e.shiftKey) {
} else {
e.preventDefault()
this.deselectRiga()
this.faiFocus('insertTask', true)
}
} }
// console.log('keyDownArea', e) // console.log('keyDownArea', e)
@@ -261,6 +282,9 @@ export default class SingleTodo extends Vue {
} }
updateTodo() { updateTodo() {
if (this.itemtodo.descr === this.precDescr)
return
this.itemtodo.descr = this.precDescr this.itemtodo.descr = this.precDescr
console.log('updateTodo', this.precDescr, this.itemtodo.descr) console.log('updateTodo', this.precDescr, this.itemtodo.descr)
this.watchupdate() this.watchupdate()
@@ -284,7 +308,7 @@ export default class SingleTodo extends Vue {
} }
updateicon() { updateicon() {
console.log('updateicon') // console.log('updateicon')
if (this.itemtodo.completed) if (this.itemtodo.completed)
this.iconCompleted = 'check_circle' this.iconCompleted = 'check_circle'
else else
@@ -344,7 +368,7 @@ export default class SingleTodo extends Vue {
.then(ris => { .then(ris => {
console.log('ris', ris) console.log('ris', ris)
if (ris) if (ris)
this.removeitem(this.itemtodo.id) this.removeitem(this.itemtodo._id)
}).catch(err => { }).catch(err => {
}) })

View File

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

View File

@@ -0,0 +1,16 @@
.todo-menu {
min-width: 202px;
}
.item-menu{
font-size: 1rem;
}
.item-menu:hover {
cursor: pointer;
}
.menuProgress {
}

View File

@@ -30,7 +30,7 @@
<q-item v-if="(field.value === 100)" :icon="field.icon" v-close-overlay <q-item v-if="(field.value === 100)" :icon="field.icon" v-close-overlay
@click.native="clickMenu(field.value)"> @click.native="clickMenu(field.value)">
<q-item-side :icon="field.icon"/> <q-item-side :icon="field.icon"/>
<q-item-tile label class="item-menu">{{field.label}}</q-item-tile> <q-item-main label class="item-menu">{{field.label}}</q-item-main>
</q-item> </q-item>
<q-item v-if="(field.value === 130)" :icon="field.icon" <q-item v-if="(field.value === 130)" :icon="field.icon"
@click.native="clickMenu(field.value)"> @click.native="clickMenu(field.value)">
@@ -60,3 +60,7 @@
<script lang="ts" src="./SubMenus.ts"> <script lang="ts" src="./SubMenus.ts">
</script> </script>
<style lang="scss" scoped>
@import './SubMenus.scss';
</style>

View File

@@ -1,18 +1,26 @@
import Vue from 'vue' import Vue from 'vue'
import { Component, Prop, Watch } from 'vue-property-decorator' import { Component, Watch } from 'vue-property-decorator'
import { SingleTodo } from '../SingleTodo' import { SingleTodo } from '../SingleTodo'
import { ITodo } from '@src/model' import { ITodo } from '@src/model'
import { rescodes } from '../../../store/Modules/rescodes' import { rescodes } from '../../../store/Modules/rescodes'
import { UserStore } from '@modules' import { Todos } from '@store'
import { UserStore } from '@store'
import objectId from '../../../js/objectId.js'
import _ from 'lodash' import _ from 'lodash'
import draggable from 'vuedraggable' import draggable from 'vuedraggable'
import VueIdb from 'vue-idb'
import globalroutines from '../../../globalroutines/index'
import $ from 'jquery' import $ from 'jquery'
import Api from "@api"
@Component({ @Component({
@@ -25,6 +33,7 @@ export default class Todo extends Vue {
title: string = '' title: string = ''
todo: string = '' todo: string = ''
todos_arr: ITodo[] = [] todos_arr: ITodo[] = []
prevRecords: ITodo[] = []
drag: boolean = true drag: boolean = true
startpos: number = 0 startpos: number = 0
listPriorityLabel: number[] = [] listPriorityLabel: number[] = []
@@ -33,6 +42,10 @@ export default class Todo extends Vue {
itemDragStart: any = null itemDragStart: any = null
itemDragEnd: any = null itemDragEnd: any = null
selrowid: number = 0 selrowid: number = 0
polling = null
fieldtochange: String [] = ['descr', 'completed', 'category', 'expiring_at', 'priority', 'id_prev', 'id_next', 'pos', 'enableExpiring', 'progress']
// @Prop({ required: false }) category: string // @Prop({ required: false }) category: string
@@ -44,11 +57,56 @@ export default class Todo extends Vue {
console.log('drag = ' + this.drag) console.log('drag = ' + this.drag)
} }
@Watch('$route', { immediate: true, deep: true })
onUrlChange(newVal: any) {
// Some action
}
@Watch('$route.params.category') changecat() { @Watch('$route.params.category') changecat() {
console.log('changecat') // console.log('changecat')
this.load() this.load()
} }
get todos_changed() {
return Todos.state.todos_changed
}
get reload_fromServer() {
return Todos.state.reload_fromServer
}
@Watch('todos_changed', { immediate: true, deep: true })
changetodos_changed(value: string, oldValue: string) {
this.$q.notify('Changed...')
// console.log('Todos.state.todos_changed CHANGED!', value, oldValue)
this.updatetable(true)
}
@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)
Todos.actions.updateArrayInMemory()
// }
}
get testPao() {
return Todos.state.testpao
}
@Watch('testPao', { immediate: true, deep: true })
changedTestpao(value: string, oldValue: string) {
// console.log('testpao CHANGED', value, oldValue)
this.updatetable(true)
}
getCategory() { getCategory() {
return this.$route.params.category return this.$route.params.category
// return this.category // return this.category
@@ -90,10 +148,10 @@ export default class Todo extends Vue {
async updateLinkedList(init: boolean, arr: ITodo[] = this.todos_arr) { async updateLinkedList(init: boolean, arr: ITodo[] = this.todos_arr) {
console.log('updateLinkedList', this.todos_arr) // console.log('updateLinkedList', this.todos_arr)
let idprev = -1 let idprev = ''
let idnext = -1 let idnext = ''
let pos = 1 let pos = 1
if (arr.length > 0) { if (arr.length > 0) {
idprev = arr[0].id_prev idprev = arr[0].id_prev
@@ -104,32 +162,39 @@ export default class Todo extends Vue {
idprev = rescodes.LIST_START idprev = rescodes.LIST_START
} else { } else {
const elemprev = this.getelem(index - 1, arr) const elemprev = this.getelem(index - 1, arr)
idprev = elemprev.id idprev = elemprev._id
} }
if (index === arr.length - 1) { if (index === arr.length - 1) {
idnext = rescodes.LIST_END idnext = rescodes.LIST_END
} else { } else {
const elemnext = this.getelem(index + 1, arr) const elemnext = this.getelem(index + 1, arr)
idnext = elemnext.id idnext = elemnext._id
} }
elem.modified = ((elem.id_prev !== idprev) || (elem.id_next !== idnext) || (elem.pos !== pos)) ? true : elem.modified // elem.modified = ((elem.id_prev !== idprev) || (elem.id_next !== idnext) || (elem.pos !== pos)) ? true : elem.modified
// elem.modified = elem.pos !== pos ? true : elem.modified
// if (elem.modified)
// console.log('MODIFICATO QUIIIIIIIIIIIIIIIIIIII', elem.id_prev, idprev, elem.id_next, idnext, elem.pos, pos)
elem.id_prev = idprev elem.id_prev = idprev
elem.id_next = idnext elem.id_next = idnext
elem.pos = pos if (elem.pos !== pos) {
elem.modified = true
elem.pos = pos
}
if (init) { if (init) {
elem.modified = false elem.modified = false
} }
pos++ pos++
this.logelem('updateLinked', elem) // this.logelem('updateLinked', elem)
}) })
} }
logelem(mystr, elem) { logelem(mystr, elem) {
console.log(mystr, 'elem [', elem.id, '] ', elem.descr, ' Pr(', this.getPriorityByInd(elem.priority), ') [', elem.id_prev, '-', elem.id_next, '] modif=', elem.modified) console.log(mystr, 'elem [', elem._id, '] ', elem.descr, ' Pr(', this.getPriorityByInd(elem.priority), ') [', elem.id_prev, '-', elem.id_next, '] modif=', elem.modified)
} }
getPriorityToSet(ind1, ind2) { getPriorityToSet(ind1, ind2) {
@@ -164,7 +229,7 @@ export default class Todo extends Vue {
} }
getTitlePriority (priority) { getTitlePriority(priority) {
let cl = '' let cl = ''
if (priority === rescodes.Todos.PRIORITY_HIGH) if (priority === rescodes.Todos.PRIORITY_HIGH)
@@ -196,7 +261,7 @@ export default class Todo extends Vue {
myobj.modified = (myobj.completed !== completed) ? true : myobj.modified myobj.modified = (myobj.completed !== completed) ? true : myobj.modified
myobj.completed = completed myobj.completed = completed
changecompleted = true changecompleted = true
console.log('Newcompleted: ', completed) console.log('Newcompleted: ', completed, 'modif', myobj.modified)
} }
if (!changecompleted) { if (!changecompleted) {
@@ -214,14 +279,18 @@ export default class Todo extends Vue {
// Updated only elements modified // Updated only elements modified
await this.updateModifyRecords(true) await this.updateModifyRecords(true)
this.updatetable()
} }
async updateModifyRecords(refresh: boolean = false) { async updateModifyRecords(refresh: boolean = false) {
let update = false let update = false
await this.todos_arr.forEach((elem: ITodo) => { await this.todos_arr.forEach((elem: ITodo) => {
if (elem.modified) { if (elem.modified) {
console.log('calling MODIFY 3')
this.modify(elem, false) this.modify(elem, false)
update = true update = true
elem.modified = false
} }
}) })
@@ -240,50 +309,86 @@ export default class Todo extends Vue {
arr.forEach(rec => { arr.forEach(rec => {
this.arrPrior.push(rec.value) this.arrPrior.push(rec.value)
}) })
console.log('Array PRIOR:', this.arrPrior) // console.log('Array PRIOR:', this.arrPrior)
} }
beforedestroy() {
clearInterval(this.polling)
}
async load() { async load() {
this.todos_arr = [...Todos.state.todos]
// Set last category selected // Set last category selected
localStorage.setItem(rescodes.localStorage.categorySel, this.getCategory()) localStorage.setItem(rescodes.localStorage.categorySel, this.getCategory())
for (let todosKey in rescodes.Todos) { for (let todosKey in rescodes.Todos) {
this.listPriorityLabel.push(rescodes.Todos[todosKey]) this.listPriorityLabel.push(rescodes.Todos[todosKey])
} }
console.log('Priority:' + this.listPriorityLabel) // console.log('Priority:' + this.listPriorityLabel)
this.setarrPriority() this.setarrPriority()
this.clearArr() this.clearArr()
await this.updatetable() await this.updatetable()
this.todos_arr.forEach((elem, index) => {
this.logelem('LOAD ' + index, elem) this.checkUpdate_everytime()
})
/*
this.todos_arr.forEach((elem, index) => {
this.logelem('LOAD ' + index, elem)
})
*/
} }
// Call to check if need to refresh
checkUpdate_everytime() {
this.polling = setInterval(() => {
this.checkUpdate()
}, 10000)
}
copy(o) {
let output, v, key
output = Array.isArray(o) ? [] : {}
for (key in o) {
v = o[key]
output[key] = (typeof v === 'object') ? this.copy(v) : v
}
return output
}
initcat() { initcat() {
const mydateexp = new Date().setDate((new Date()).getDate() + 1)
let mydatenow = new Date().getDate()
let mydateexp = new Date().getDate() + 10
console.log('User:' + UserStore.state.userId)
const objtodo: ITodo = { const objtodo: ITodo = {
// _id: new Date().toISOString(), // Create NEW
_id: objectId(),
userId: UserStore.state.userId, userId: UserStore.state.userId,
descr: '', descr: '',
priority: rescodes.Todos.PRIORITY_NORMAL, priority: rescodes.Todos.PRIORITY_NORMAL,
completed: false, completed: false,
created_at: new Date(), created_at: mydatenow,
modify_at: mydatenow,
completed_at: 0,
category: '', category: '',
modify_at: new Date(),
expiring_at: mydateexp, expiring_at: mydateexp,
enableExpiring: false, enableExpiring: false,
id_prev: 0, id_prev: '',
id_next: 0, id_next: '',
pos: 0, pos: 0,
modified: true, modified: false,
progress: 0 progress: 0
} }
return objtodo return this.copy(objtodo)
} }
@@ -296,42 +401,173 @@ export default class Todo extends Vue {
return '' return ''
} }
isRegistered() {
return localStorage.getItem(rescodes.localStorage.userId) !== ''
}
async insertTodo() { async insertTodo() {
if (this.todo.trim() === '') if (this.todo.trim() === '')
return return
if (!this.isRegistered()) {
// Not logged
this.$q.notify(this.$t('user.notregistered'))
return
}
const objtodo = this.initcat() const objtodo = this.initcat()
console.log('insertTodo ', UserStore.state.userId)
objtodo.descr = this.todo objtodo.descr = this.todo
objtodo.category = this.getCategory() objtodo.category = this.getCategory()
const lastelem = this.getLastList() const lastelem: ITodo = this.getLastList()
objtodo.id_prev = (lastelem !== null) ? lastelem.id : rescodes.LIST_START objtodo.id_prev = (lastelem !== null) ? lastelem._id : rescodes.LIST_START
objtodo.id_next = rescodes.LIST_END objtodo.id_next = rescodes.LIST_END
objtodo.pos = (lastelem !== null) ? lastelem.pos + 1 : 1 objtodo.pos = (lastelem !== null) ? lastelem.pos + 1 : 1
objtodo.modified = true objtodo.modified = false
if (objtodo.userId === undefined) {
this.$q.notify(this.$t('todo.usernotdefined'))
return
}
await globalroutines(this, 'write', 'todos', objtodo)
.then((id) => {
console.log('*** IDNEW (3) = ', id)
// update also the last elem
if (lastelem !== null) {
lastelem.id_next = id
// lastelem.modified = true
console.log('calling MODIFY 4', lastelem)
}
// Add to Indexdb
await this.$db.todos.add(objtodo
).then((id) => {
console.log('*** IDNEW = ', id)
if (lastelem !== null) {
lastelem.id_next = id
lastelem.modified = true
this.modify(lastelem, false) this.modify(lastelem, false)
} .then(ris => {
this.modify(objtodo, true) console.log('END calling MODIFY 4')
}).catch(err => {
console.log('Errore: ' + err.message) this.saveItemToSyncAndDb(rescodes.DB.TABLE_SYNC_TODOS, 'POST', objtodo, true)
}) this.updatetable(false)
})
}).catch(err => {
console.log('Errore: ' + err.message)
})
// console.log('ESCO.........')
// empty the field // empty the field
this.todo = '' this.todo = ''
} }
async cmdToSyncAndDb(cmd, table, method, item: ITodo, id, msg: String, update: boolean) {
// Send to Server to Sync
console.log('cmdToSyncAndDb', cmd, table, method, item.descr, id, msg)
let cmdSw = cmd
if ((cmd === rescodes.DB.CMD_SYNC_NEW_TODOS) || (cmd === rescodes.DB.CMD_DELETE_TODOS)) {
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!')
}
const mythis = this
if ('serviceWorker' in navigator) {
await navigator.serviceWorker.ready
.then(function (sw) {
// _id: new Date().toISOString(),
console.log('---------------------- navigator.serviceWorker.ready')
// mythis.sendMessageToSW(item, method)
globalroutines(mythis, 'write', table, item, id)
.then(function (id) {
// console.log('id', id)
})
const sep = '|'
let multiparams = cmdSw + sep + table + sep + method + sep + UserStore.state.idToken + 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 {
// #Todo ++ Alternative 2 to SyncManager
Api.syncAlternative(multiparams)
}
})
.then(function () {
let snackbarContainer = document.querySelector('#confirmation-toast')
let data = { message: msg }
// snackbarContainer.MaterialSnackbar.showSnackbar(data)
})
.catch(function (err) {
console.error('Errore in globalroutines', table, err)
})
})
if (update) {
// // Update the array in memory, from todos table from IndexedDb
Todos.actions.updateArrayInMemory()
.then((ris) => {
return ris
})
}
} else {
if (cmd === rescodes.DB.CMD_SYNC_NEW_TODOS) {
if (method === 'POST')
Todos.actions.dbInsertTodo(item)
else if (method === 'PATCH')
Todos.actions.dbSaveTodo(item)
} else if (cmd === rescodes.DB.CMD_DELETE_TODOS)
Todos.actions.dbDeleteTodo(item)
}
}
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)
}
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)
}
/*
sendMessageToSW(recdata, method) {
navigator.serviceWorker.controller.postMessage({
type: 'sync',
recdata,
method,
cmd: 'sync-new-todos',
token: UserStore.state.idToken,
lang: UserStore.state.lang
})
}
*/
getElemById(id, lista = this.todos_arr) { getElemById(id, lista = this.todos_arr) {
let myobj: ITodo let myobj: ITodo
for (myobj of lista) { for (myobj of lista) {
if (myobj.id === id) { if (myobj._id === id) {
return myobj return myobj
} }
} }
@@ -351,23 +587,23 @@ export default class Todo extends Vue {
if (myobjprev !== null) { if (myobjprev !== null) {
myobjprev.id_next = myobjtrov.id_next myobjprev.id_next = myobjtrov.id_next
myobjprev.modified = true myobjprev.modified = true
console.log('calling MODIFY 2')
this.modify(myobjprev, false) this.modify(myobjprev, false)
} }
if (myobjnext !== null) { if (myobjnext !== null) {
myobjnext.id_prev = myobjtrov.id_prev myobjnext.id_prev = myobjtrov.id_prev
myobjnext.modified = true myobjnext.modified = true
console.log('calling MODIFY 1')
this.modify(myobjnext, false) this.modify(myobjnext, false)
} }
console.log('ENTRATO') this.deleteItemToSyncAndDb(rescodes.DB.TABLE_DELETE_TODOS, myobjtrov, id, true)
const mythis = this const mythis = this
// Delete item // Delete item
await this.$db.todos await globalroutines(this, 'delete', 'todos', null, id)
.where('id').equals(id) .then((ris) => {
.delete()
.then(() => {
console.log('UpdateTable')
mythis.updatetable() mythis.updatetable()
}).catch((error) => { }).catch((error) => {
console.log('err: ', error) console.log('err: ', error)
@@ -377,12 +613,44 @@ export default class Todo extends Vue {
console.log('FINE deleteitem') console.log('FINE deleteitem')
} }
getElem(myarray: ITodo[], id) {
for (let i = 0; i < myarray.length - 1; i++) {
if (myarray[i]._id === id)
return myarray[i]
}
return null
}
isRecordModifPos(itemnew: ITodo, itemold: ITodo) {
return itemnew.pos !== itemold.pos
}
async updatetable(refresh: boolean = false) { async updatetable(refresh: boolean = false) {
await this.filtertodos(refresh) // console.log('updatetable')
this.prevRecords = [...this.todos_arr]
return await Todos.actions.getTodosByCategory(this.getCategory())
.then(arrtemp => {
arrtemp = _.orderBy(arrtemp, ['completed', 'priority', 'pos'], ['asc', 'desc', 'asc'])
this.updateLinkedList(true, arrtemp)
// If changed the position, then set modified
arrtemp.forEach(itemNew => {
const itemOld = this.getElem(this.prevRecords, itemNew._id)
if (itemOld)
itemNew.modified = this.isRecordModifPos(itemNew, itemOld) ? true : false
})
this.todos_arr = [...arrtemp] // make copy
})
} }
clearArr() { clearArr() {
this.todos_arr = [] // this.todos_arr = []
} }
existArr(x) { existArr(x) {
@@ -428,7 +696,7 @@ export default class Todo extends Vue {
current = this.getElemById(current.id_next, arrris) current = this.getElemById(current.id_next, arrris)
if (current === null) if (current === null)
break break
if (current.id === currentprec.id) if (current._id === currentprec._id)
break break
myarr.push(current) myarr.push(current)
currentprec = current currentprec = current
@@ -441,48 +709,9 @@ export default class Todo extends Vue {
} }
async filtertodos(refresh: boolean = false) {
console.log('filtertodos')
let arrtemp = []
if (this.filter) {
// #Todo If need to filter the output database ...
await this.$db.todos
.where('userId').equals(UserStore.state.userId)
.and(todo => todo.category === this.getCategory())
.toArray()
.then((response) => {
Promise.all(response.map(key => key))
.then((ristodos) => {
arrtemp = ristodos
})
})
} else {
await this.$db.todos
.where('userId').equals(UserStore.state.userId)
.and(todo => todo.category === this.getCategory())
.toArray().then(ristodos => {
arrtemp = ristodos
})
arrtemp = _.orderBy(arrtemp, ['completed', 'priority', 'pos'], ['asc', 'desc', 'asc'])
}
this.updateLinkedList(true, arrtemp)
// set array
// arrtemp = this.setArrayFinale(arrtemp)
this.todos_arr = [...arrtemp] // make copy
return []
}
sortarr(arr, field) { sortarr(arr, field) {
return arr.slice().sort(function(a, b) { return arr.slice().sort(function (a, b) {
return a[field] - b[field] return a[field] - b[field]
}) })
@@ -514,21 +743,21 @@ export default class Todo extends Vue {
// } // }
// //
deselectAllRows(item, check, onlythis: boolean = false) { deselectAllRows(item: ITodo, check, onlythis: boolean = false) {
console.log('deselectAllRows : ', item) // console.log('deselectAllRows : ', item)
for (let i = 0; i < this.$refs.single.length; i++) { for (let i = 0; i < this.$refs.single.length; i++) {
let contr = <SingleTodo>this.$refs.single[i] let contr = <SingleTodo>this.$refs.single[i]
// @ts-ignore // @ts-ignore
let id = contr.itemtodo.id let id = contr.itemtodo._id
// Don't deselect the actual clicked! // Don't deselect the actual clicked!
let des = false let des = false
if (onlythis) { if (onlythis) {
des = item.id === id des = item._id === id
}else { } else {
des = ((check && (item.id !== id)) || (!check)) des = ((check && (item._id !== id)) || (!check))
} }
if (des) { if (des) {
// @ts-ignore // @ts-ignore
@@ -541,7 +770,7 @@ export default class Todo extends Vue {
// let index = -1 // let index = -1
// // get index // // get index
// this.$refs.single.forEach( (singletodo: SingleTodo) => { // this.$refs.single.forEach( (singletodo: SingleTodo) => {
// if (singletodo.itemtodo.id === rec.id) // if (singletodo.itemtodo._id === rec._id)
// index = -1 // index = -1
// }) // })
// //
@@ -549,41 +778,77 @@ export default class Todo extends Vue {
modifyField(recOut, recIn, field) { modifyField(recOut, recIn, field) {
if (recOut[field] !== recIn[field]) { if (recOut[field] !== recIn[field]) {
console.log('*************** CAMPO ', field, 'MODIFICATO!', recOut[field], recIn[field])
recOut.modified = true recOut.modified = true
recOut[field] = recIn[field] recOut[field] = recIn[field]
return true
} }
return false
} }
async modify(myobj: ITodo, update: boolean) { async modify(myobj: ITodo, update: boolean) {
await this.$db.transaction('rw', [this.$db.todos], async () => { if (myobj === null)
const miorec = await this.$db.todos.get(myobj.id) return new Promise(function (resolve, reject) {
resolve()
})
await globalroutines(this, 'read', 'todos', null, myobj._id)
.then(miorec => {
if (miorec === undefined) {
console.log('~~~~~~~~~~~~~~~~~~~~ !!!!!!!!!!!!!!!!!! Record not Found !!!!!! id=', myobj._id)
return
}
this.modifyField(miorec, myobj, 'descr') if (this.modifyField(miorec, myobj, 'completed'))
this.modifyField(miorec, myobj, 'completed') miorec.completed_at = new Date().getDate()
this.modifyField(miorec, myobj, 'category')
this.modifyField(miorec, myobj, 'expiring_at') this.fieldtochange.forEach(field => {
this.modifyField(miorec, myobj, 'priority') this.modifyField(miorec, myobj, field)
this.modifyField(miorec, myobj, 'id_prev') })
this.modifyField(miorec, myobj, 'id_next')
this.modifyField(miorec, myobj, 'pos')
this.modifyField(miorec, myobj, 'enableExpiring')
this.modifyField(miorec, myobj, 'progress')
if (miorec.modified) { if (miorec.modified) {
miorec.modify_at = new Date() console.log('Todo MODIFICATO! ', miorec.descr, 'SALVALO SULLA IndexedDB todos')
miorec.modify_at = new Date().getDate()
miorec.modified = false
this.logelem('modify', miorec) // this.logelem('modify', miorec)
await this.$db.todos.put(miorec) globalroutines(this, 'write', 'todos', miorec)
.then(ris => {
if (update) this.saveItemToSyncAndDb(rescodes.DB.TABLE_SYNC_TODOS_PATCH, 'PATCH', miorec, update)
await this.updatetable(false) .then(() => {
} // console.log('SET MODIFIED FALSE')
})
if (update)
this.updatetable(false)
})
})
}
})
} }
clicktest() {
console.log('clicktest!')
const objtodo = this.initcat()
objtodo.descr = 'PROVA'
objtodo.category = this.getCategory()
Todos.state.todos.push(objtodo)
Todos.mutations.setTodos_changed()
console.log('Todos.state.todos', Todos.state.todos)
}
clicktest2() {
this.updatetable(false)
console.log('Todos.state.todos', Todos.state.todos)
}
checkUpdate() {
Todos.actions.waitAndcheckPendingMsg()
}
} }

View File

@@ -13,7 +13,7 @@
<draggable v-model="todos_arr" :options="{draggable:'.myitemdrag'}" <draggable v-model="todos_arr" :options="{draggable:'.myitemdrag'}"
@start="onStart" @end="onEnd" class="dragArea"> @start="onStart" @end="onEnd" class="dragArea">
<transition-group> <transition-group>
<div :id="getmyid(mytodo.id)" :key="mytodo.id" v-for="mytodo in todos_arr" class="myitemdrag"> <div :id="getmyid(mytodo._id)" :key="mytodo._id" v-for="mytodo in todos_arr" class="myitemdrag">
<div v-if="(prior !== mytodo.priority) && !mytodo.completed" :class="getTitlePriority(mytodo.priority)"> <div v-if="(prior !== mytodo.priority) && !mytodo.completed" :class="getTitlePriority(mytodo.priority)">
<label>{{getPriorityByInd(mytodo.priority)}}</label> <label>{{getPriorityByInd(mytodo.priority)}}</label>
@@ -35,6 +35,16 @@
:after="[{icon: 'arrow_forward', content: true, handler () {}}]" :after="[{icon: 'arrow_forward', content: true, handler () {}}]"
v-on:keyup.enter="insertTodo"/> v-on:keyup.enter="insertTodo"/>
<q-input v-model="testPao" float-label="testPao"/>
<q-input v-model="todos_changed" float-label="todos_changed"/>
<q-input v-model="reload_fromServer" float-label="reload_fromServer"/>
<div class="flex-item btn-item">
<!--<q-btn class="mybtn" round color="" icon="lock" @click="clicktest()"></q-btn>-->
<!--<q-btn class="mybtn" round color="" icon="person" @click="clicktest2()"></q-btn>-->
<q-btn class="mybtn" round color="" icon="list" @click="checkUpdate()"></q-btn>
</div>
</div> </div>
</q-page> </q-page>

View File

@@ -0,0 +1,7 @@
import indexdb from './indexdb'
export default async (context, cmd, table, data = null, id = '') => {
const descr = data !== null ? data.descr : ''
// console.log('globalroutines', cmd, table, descr, id)
return await indexdb(context, cmd, table, data, id)
}

View File

@@ -0,0 +1,79 @@
import store from '../store'
import _ from 'lodash'
import { UserStore, Todos } from '@store'
import { i18n } from '../plugins/i18n'
import {idbKeyval as storage} from '../js/storage.js';
function saveConfigIndexDb(context) {
let data = []
data['_id'] = 1
data['lang'] = UserStore.state.lang
data['token'] = UserStore.state.idToken
data['userId'] = UserStore.state.userId
writeConfigIndexDb('config', data)
}
function writeConfigIndexDb(context, data) {
// console.log('writeConfigIndexDb', data)
storage.setdata('config', data)
.then(ris => {
return true
})
}
async function readfromIndexDbToStateTodos(context, table) {
// console.log('*** read from IndexDb to state.todos')
return await storage.getalldata(table)
.then(records => {
// console.log('&&&&&&& readfromIndexDbToStateTodos OK: Num RECORD: ', records.length)
if (table === 'todos') {
Todos.state.todos = [...records]
Todos.mutations.setTodos_changed()
// console.log('Todos.state.todos_changed:', Todos.state.todos_changed)
// setTimeout(testfunc2, 3000)
}
}).catch((error) => {
console.log('err: ', error)
})
}
function consolelogpao(str, str2 = '', str3 = '') {
console.log(str, str2, str3)
// Todos.mutations.setTestpao(str + str2 + str3)
}
function testfunc2 () {
consolelogpao('testfunc2')
Todos.mutations.setTodos_changed()
consolelogpao('testfunc2: Todos.state.todos_changed:', Todos.state.todos_changed)
}
export default async (context, cmd, table, datakey = null, id = '') => {
if (cmd === 'loadapp') {
// ****** LOAD APP AL CARICAMENTO ! *******
return saveConfigIndexDb(context, datakey)
} else if (cmd === 'write') {
return await storage.setdata(table, datakey)
} else if (cmd === 'updateinMemory') {
return await readfromIndexDbToStateTodos(context, table)
} else if (cmd === 'readall') {
return await storage.getalldata(table)
} else if (cmd === 'count') {
return await storage.count(table)
} else if (cmd === 'read') {
return await storage.getdata(table, id)
} else if (cmd === 'delete') {
return await storage.deletedata(table, id)
} else if (cmd === 'log') {
consolelogpao(table)
}
}

View File

@@ -0,0 +1,18 @@
import { UserStore } from "../store/Modules";
import messages from "../statics/i18n";
function translate(params) {
let msg = params.split('.')
let lang = UserStore.state.lang
let stringa = messages[lang]
let ris = stringa
msg.forEach(param => {
ris = ris[param]
})
return ris
}
export default translate

View File

@@ -10,15 +10,25 @@
<meta name="viewport" <meta name="viewport"
content="user-scalable=no, initial-scale=1, minimum-scale=1, width=device-width<% if (htmlWebpackPlugin.options.ctx.mode.cordova) { %>, viewport-fit=cover<% } %>"> content="user-scalable=no, initial-scale=1, minimum-scale=1, width=device-width<% if (htmlWebpackPlugin.options.ctx.mode.cordova) { %>, viewport-fit=cover<% } %>">
<link rel="icon" href="statics/freeplanet-logo.png" type="image/x-icon"> <link rel="icon" href="/statics/icons/favicon.ico" type="image/x-icon">
<link rel="icon" type="image/png" sizes="32x32" href="statics/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="32x32" href="/statics/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="statics/icons/favicon-16x16.png"> <link rel="icon" type="image/png" sizes="16x16" href="/statics/icons/favicon-16x16.png">
<script defer src="statics/js/material.min.js"></script> <script defer src="/statics/js/material.min.js"></script>
<script src="statics/js/promise.js"></script> <script src="/statics/js/promise.js"></script>
<script src="statics/js/fetch.js"></script> <script src="/statics/js/fetch.js"></script>
<script src="statics/js/idb.js"></script> <script src="/statics/js/idb.js"></script>
<script src="/statics/js/storage.js"></script>
<!--
<script src="/statics/js/immortal-db.min.js"></script>
<script>
;(async () => {
const db = ImmortalDB.ImmortalDB
await db.set('hi', 'lolsup')
})()
</script>
-->
<link type="text/css" rel="stylesheet" href="statics/firebaseui.css" /> <!--<link type="text/css" rel="stylesheet" href="statics/firebaseui.css" />-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head> </head>

View File

@@ -295,7 +295,7 @@
} }
// HTTP methods whose capitalization should be normalized // HTTP methods whose capitalization should be normalized
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'] var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'PATCH']
function normalizeMethod(method) { function normalizeMethod(method) {
var upcased = method.toUpperCase() var upcased = method.toUpperCase()

View File

@@ -1,311 +0,0 @@
'use strict';
(function() {
function toArray(arr) {
return Array.prototype.slice.call(arr);
}
function promisifyRequest(request) {
return new Promise(function(resolve, reject) {
request.onsuccess = function() {
resolve(request.result);
};
request.onerror = function() {
reject(request.error);
};
});
}
function promisifyRequestCall(obj, method, args) {
var request;
var p = new Promise(function(resolve, reject) {
request = obj[method].apply(obj, args);
promisifyRequest(request).then(resolve, reject);
});
p.request = request;
return p;
}
function promisifyCursorRequestCall(obj, method, args) {
var p = promisifyRequestCall(obj, method, args);
return p.then(function(value) {
if (!value) return;
return new Cursor(value, p.request);
});
}
function proxyProperties(ProxyClass, targetProp, properties) {
properties.forEach(function(prop) {
Object.defineProperty(ProxyClass.prototype, prop, {
get: function() {
return this[targetProp][prop];
},
set: function(val) {
this[targetProp][prop] = val;
}
});
});
}
function proxyRequestMethods(ProxyClass, targetProp, Constructor, properties) {
properties.forEach(function(prop) {
if (!(prop in Constructor.prototype)) return;
ProxyClass.prototype[prop] = function() {
return promisifyRequestCall(this[targetProp], prop, arguments);
};
});
}
function proxyMethods(ProxyClass, targetProp, Constructor, properties) {
properties.forEach(function(prop) {
if (!(prop in Constructor.prototype)) return;
ProxyClass.prototype[prop] = function() {
return this[targetProp][prop].apply(this[targetProp], arguments);
};
});
}
function proxyCursorRequestMethods(ProxyClass, targetProp, Constructor, properties) {
properties.forEach(function(prop) {
if (!(prop in Constructor.prototype)) return;
ProxyClass.prototype[prop] = function() {
return promisifyCursorRequestCall(this[targetProp], prop, arguments);
};
});
}
function Index(index) {
this._index = index;
}
proxyProperties(Index, '_index', [
'name',
'keyPath',
'multiEntry',
'unique'
]);
proxyRequestMethods(Index, '_index', IDBIndex, [
'get',
'getKey',
'getAll',
'getAllKeys',
'count'
]);
proxyCursorRequestMethods(Index, '_index', IDBIndex, [
'openCursor',
'openKeyCursor'
]);
function Cursor(cursor, request) {
this._cursor = cursor;
this._request = request;
}
proxyProperties(Cursor, '_cursor', [
'direction',
'key',
'primaryKey',
'value'
]);
proxyRequestMethods(Cursor, '_cursor', IDBCursor, [
'update',
'delete'
]);
// proxy 'next' methods
['advance', 'continue', 'continuePrimaryKey'].forEach(function(methodName) {
if (!(methodName in IDBCursor.prototype)) return;
Cursor.prototype[methodName] = function() {
var cursor = this;
var args = arguments;
return Promise.resolve().then(function() {
cursor._cursor[methodName].apply(cursor._cursor, args);
return promisifyRequest(cursor._request).then(function(value) {
if (!value) return;
return new Cursor(value, cursor._request);
});
});
};
});
function ObjectStore(store) {
this._store = store;
}
ObjectStore.prototype.createIndex = function() {
return new Index(this._store.createIndex.apply(this._store, arguments));
};
ObjectStore.prototype.index = function() {
return new Index(this._store.index.apply(this._store, arguments));
};
proxyProperties(ObjectStore, '_store', [
'name',
'keyPath',
'indexNames',
'autoIncrement'
]);
proxyRequestMethods(ObjectStore, '_store', IDBObjectStore, [
'put',
'add',
'delete',
'clear',
'get',
'getAll',
'getKey',
'getAllKeys',
'count'
]);
proxyCursorRequestMethods(ObjectStore, '_store', IDBObjectStore, [
'openCursor',
'openKeyCursor'
]);
proxyMethods(ObjectStore, '_store', IDBObjectStore, [
'deleteIndex'
]);
function Transaction(idbTransaction) {
this._tx = idbTransaction;
this.complete = new Promise(function(resolve, reject) {
idbTransaction.oncomplete = function() {
resolve();
};
idbTransaction.onerror = function() {
reject(idbTransaction.error);
};
idbTransaction.onabort = function() {
reject(idbTransaction.error);
};
});
}
Transaction.prototype.objectStore = function() {
return new ObjectStore(this._tx.objectStore.apply(this._tx, arguments));
};
proxyProperties(Transaction, '_tx', [
'objectStoreNames',
'mode'
]);
proxyMethods(Transaction, '_tx', IDBTransaction, [
'abort'
]);
function UpgradeDB(db, oldVersion, transaction) {
this._db = db;
this.oldVersion = oldVersion;
this.transaction = new Transaction(transaction);
}
UpgradeDB.prototype.createObjectStore = function() {
return new ObjectStore(this._db.createObjectStore.apply(this._db, arguments));
};
proxyProperties(UpgradeDB, '_db', [
'name',
'version',
'objectStoreNames'
]);
proxyMethods(UpgradeDB, '_db', IDBDatabase, [
'deleteObjectStore',
'close'
]);
function DB(db) {
this._db = db;
}
DB.prototype.transaction = function() {
return new Transaction(this._db.transaction.apply(this._db, arguments));
};
proxyProperties(DB, '_db', [
'name',
'version',
'objectStoreNames'
]);
proxyMethods(DB, '_db', IDBDatabase, [
'close'
]);
// Add cursor iterators
// TODO: remove this once browsers do the right thing with promises
['openCursor', 'openKeyCursor'].forEach(function(funcName) {
[ObjectStore, Index].forEach(function(Constructor) {
Constructor.prototype[funcName.replace('open', 'iterate')] = function() {
var args = toArray(arguments);
var callback = args[args.length - 1];
var nativeObject = this._store || this._index;
var request = nativeObject[funcName].apply(nativeObject, args.slice(0, -1));
request.onsuccess = function() {
callback(request.result);
};
};
});
});
// polyfill getAll
[Index, ObjectStore].forEach(function(Constructor) {
if (Constructor.prototype.getAll) return;
Constructor.prototype.getAll = function(query, count) {
var instance = this;
var items = [];
return new Promise(function(resolve) {
instance.iterateCursor(query, function(cursor) {
if (!cursor) {
resolve(items);
return;
}
items.push(cursor.value);
if (count !== undefined && items.length == count) {
resolve(items);
return;
}
cursor.continue();
});
});
};
});
var exp = {
open: function(name, version, upgradeCallback) {
var p = promisifyRequestCall(indexedDB, 'open', [name, version]);
var request = p.request;
request.onupgradeneeded = function(event) {
if (upgradeCallback) {
upgradeCallback(new UpgradeDB(request.result, event.oldVersion, request.transaction));
}
};
return p.then(function(db) {
return new DB(db);
});
},
delete: function(name) {
return promisifyRequestCall(indexedDB, 'deleteDatabase', [name]);
}
};
if (typeof module !== 'undefined') {
module.exports = exp;
module.exports.default = module.exports;
}
else {
self.idb = exp;
}
}());

8
src/js/immortal-db.min.js vendored Normal file

File diff suppressed because one or more lines are too long

10
src/js/objectId.js Normal file
View File

@@ -0,0 +1,10 @@
function objectId () {
return hex(Date.now() / 1000) +
' '.repeat(16).replace(/./g, () => hex(Math.random() * 16))
}
function hex (value) {
return Math.floor(value).toString(16)
}
export default objectId

116
src/js/storage.js Normal file
View File

@@ -0,0 +1,116 @@
export let idbKeyval = (() => {
let db;
function getDB() {
if (!db) {
// console.log('CREO DB STORAGE JS !')
db = new Promise((resolve, reject) => {
const openreq = indexedDB.open('mydb3', 11);
openreq.onerror = () => {
reject(openreq.error);
};
openreq.onupgradeneeded = () => {
// First time setup: create an empty object store
openreq.result.createObjectStore('todos', { keyPath: '_id' });
openreq.result.createObjectStore('sync_todos', { keyPath: '_id' });
openreq.result.createObjectStore('sync_todos_patch', { keyPath: '_id' });
openreq.result.createObjectStore('delete_todos', { keyPath: '_id' });
openreq.result.createObjectStore('config', { keyPath: '_id' });
openreq.result.createObjectStore('swmsg', { keyPath: '_id' });
};
openreq.onsuccess = () => {
resolve(openreq.result);
};
});
}
return db;
}
async function withStore(type, table, callback, ) {
const db = await getDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction(table, type);
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject(transaction.error);
callback(transaction.objectStore(table));
});
}
return {
async get(key) {
let req;
await withStore('readonly', 'keyval', store => {
req = store.get(key);
});
return req.result;
},
async getdata(table, key) {
let req;
await withStore('readonly', table, store => {
console.log('store', store, 'key', key)
req = store.get(key);
});
// console.log('RISFINALE!', req.result)
return req.result;
},
async getalldata(table) {
let req;
await withStore('readonly', table, store => {
req = store.getAll();
});
return req.result;
},
async count(table) {
let req;
await withStore('readonly', table, store => {
req = store.count();
});
return req.result;
},
async set(key, value) {
let req;
await withStore('readwrite', 'keyval', store => {
req = store.put(value, key);
});
return req.result;
},
async setdata(table, value) {
let req;
console.log('setdata', table, value)
await withStore('readwrite', table, store => {
req = store.put(value);
});
return req.result;
},
async delete(key) {
return await withStore('readwrite', 'keyval', store => {
store.delete(key);
});
},
async deletedata(table, key) {
return await withStore('readwrite', table, store => {
store.delete(key);
});
},
async clearalldata(table) {
return await withStore('readwrite', table, store => {
store.clear();
});
}
};
})();
// iOS add-to-homescreen is missing IDB, or at least it used to.
// I haven't tested this in a while.
if (!self.indexedDB) {
idbKeyval = {
get: key => Promise.resolve(localStorage.getItem(key)),
set: (key, val) => Promise.resolve(localStorage.setItem(key, val)),
delete: key => Promise.resolve(localStorage.removeItem(key))
};
}

28
src/js/utility.js Normal file
View File

@@ -0,0 +1,28 @@
function urlBase64ToUint8Array(base64String) {
var padding = '='.repeat((4 - base64String.length % 4) % 4);
var base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
var rawData = window.atob(base64);
var outputArray = new Uint8Array(rawData.length);
for (var i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ab], { type: mimeString });
return blob;
}
export default urlBase64ToUint8Array

View File

@@ -55,7 +55,7 @@
links links
created() { created() {
console.log('Drawer created...') // console.log('Drawer created...')
let listatodo = [] let listatodo = []

View File

@@ -4,6 +4,7 @@ export interface IPost {
export interface IGlobalState { export interface IGlobalState {
conta: number conta: number
isSubscribed: boolean
isLoginPage: boolean isLoginPage: boolean
layoutNeeded: boolean layoutNeeded: boolean
mobileMode: boolean mobileMode: boolean

View File

@@ -1,5 +1,5 @@
export interface ITodo { export interface ITodo {
id?: number, _id?: any,
userId: string userId: string
category?: string category?: string
descr?: string, descr?: string,
@@ -7,10 +7,11 @@ export interface ITodo {
completed: boolean, completed: boolean,
created_at: any, created_at: any,
modify_at: any, modify_at: any,
completed_at: any,
expiring_at: any, expiring_at: any,
enableExpiring?: boolean, enableExpiring?: boolean,
id_prev?: number, id_prev?: string,
id_next?: number, id_next?: string,
modified?: boolean, modified?: boolean,
pos?: number, pos?: number,
progress?: number progress?: number
@@ -18,4 +19,10 @@ export interface ITodo {
export interface ITodosState { export interface ITodosState {
visuOnlyUncompleted: boolean visuOnlyUncompleted: boolean
networkDataReceived: boolean
todos: ITodo[]
todos_changed: number
reload_fromServer: boolean
testpao: String
insidePending: boolean
} }

View File

@@ -21,10 +21,12 @@ export interface IUserState {
tokens?: IToken[] tokens?: IToken[]
verifiedEmail?: boolean verified_email?: boolean
categorySel?: string categorySel?: string
tokenforgot?: string tokenforgot?: string
servercode?: number servercode?: number
x_auth_token?: string
isLogged?: boolean
} }

View File

@@ -3,7 +3,7 @@ export * from './GlobalStore'
export * from './signin-option' export * from './signin-option'
export * from './signup-option' export * from './signup-option'
export * from './key-value' export * from './key-value'
export * from './payload' // export * from './payload'
export * from './Categories' export * from './Categories'
export * from './Todos' export * from './Todos'

View File

@@ -1,4 +0,0 @@
export { IPayload } from './payload'
export { IPayloadMessage } from './payload-message'
export * from './payload-mapper'

View File

@@ -1,80 +0,0 @@
import { AxiosError, AxiosResponse } from 'axios'
import { PayloadMessageTypes } from 'common'
import { IPayload } from './payload'
export { PayloadMessageTypes } from '../../common/message'
export class PayloadMapper {
private fromError<T>(o: Error): IPayload<T> {
return {
data: null,
message: {
messageTypeId: PayloadMessageTypes.error,
text: o.message,
title: o.name
}
}
}
private fromAxiosError<T>(o: AxiosError): IPayload<T> {
let data: T = null
if (o.response && isAxiosResponse(o.response))
data = this.fromAxiosResponse<T>(o.response).data
return {
data: data,
message: {
messageTypeId: PayloadMessageTypes.error,
text: o.message,
title: 'Code:' + o.code + '. ' + o.name
}
}
}
private fromAxiosResponse<T>(o: AxiosResponse): IPayload<T> {
let value: IPayload<T> = null
if (isPayload<T>(o.data))
value = o.data
else
value = {
data: <any>o.data,
message: {
messageTypeId: PayloadMessageTypes.success,
text: null
}
}
return value
}
public fromObject<T>(o: any): IPayload<T> {
if (isAxiosError(o))
return this.fromAxiosError<T>(o)
if (o instanceof Error)
return this.fromError<T>(o)
if (isAxiosResponse(o))
return this.fromAxiosResponse<T>(o)
return null
}
}
function isAxiosResponse(o: any): o is AxiosResponse {
return o instanceof Object && 'data' in o && 'config' in o && 'status' in o && 'statusText' in o && 'headers' in o
}
function isAxiosError(o: any): o is AxiosError {
return o instanceof Object && o instanceof Error && 'config' in o
}
function isPayload<T>(o: any): o is IPayload<T> {
return o instanceof Object && 'data' in o && 'message' in o
}

View File

@@ -1,6 +0,0 @@
export interface IPayloadMessage {
text: string
title?: string
messageTypeId: string
}

View File

@@ -1,8 +0,0 @@
import { IPayloadMessage } from './payload-message'
export interface IPayload<T> {
data: T
message: IPayloadMessage
}

View File

@@ -0,0 +1,8 @@
import globalroutines from '../globalroutines'
export default ({ app, router, store, Vue }) => {
// something to do
Vue.prototype.$globalroutines = globalroutines
}

View File

@@ -1,6 +1,6 @@
// src/plugins/i18n.js // src/plugins/i18n.js
import VueI18n from 'vue-i18n'; import VueI18n from 'vue-i18n';
import messages from 'src/i18n'; import messages from 'src/statics/i18n';
export default ({ app, store, Vue }) => { export default ({ app, store, Vue }) => {
Vue.use(VueI18n); Vue.use(VueI18n);

View File

@@ -1,5 +0,0 @@
import VueIdb from 'vue-idb'
export default ({ Vue }) => {
Vue.use(VueIdb)
}

View File

@@ -4,17 +4,6 @@ import VueIdb from 'vue-idb'
export default ({ Vue }) => { export default ({ Vue }) => {
Vue.use(VueIdb) Vue.use(VueIdb)
// Insert here the database for IndexDB
new VueIdb({
database: 'test',
schemas: [
{ categories: '++id, sub_categ_id, descr_it, campo2bool, campo3bool' },
{ todos: '++id, userId, category, pos, descr, priority, completed, created_at, modify_at, expiring_at, progress, enableExpiring' }
],
options: {
todos: { type: 'list', primary: 'pos', label: 'label', updated_at: 'updated_at' },
}
})
} }
@@ -25,7 +14,7 @@ export default new VueIdb({
version: 1, version: 1,
database: 'test', database: 'test',
schemas: [ schemas: [
{ categories: '++id, sub_categ_id, descr_it' } { categories: '++_id, sub_categ_id, descr_it' }
] ]
}) })
*/ */

View File

@@ -19,12 +19,14 @@ export default class Home extends Vue {
constructor() { constructor() {
super() super()
console.log('Home constructor...') // console.log('Home constructor...')
this.initprompt() this.initprompt()
} }
created() { created() {
console.log('Home created...') // console.log('Home created...')
GlobalStore.actions.prova()
} }
mystilecard() { mystilecard() {
@@ -37,14 +39,20 @@ export default class Home extends Vue {
get conta() { get conta() {
return GlobalStore.state.conta return GlobalStore.state.conta
} }
set conta(valore) { set conta(valore) {
GlobalStore.actions.setConta(valore) GlobalStore.actions.setConta(valore)
let my = this.$q.i18n.lang let my = this.$q.i18n.lang
this.showNotification(String(my)) this.showNotification(String(my))
} }
showNotification(msg: string) { showNotification(message: string, color = 'primary', icon = '') {
this.$q.notify(msg) this.$q.notify({
color,
icon,
message
})
} }
initprompt() { initprompt() {
@@ -54,8 +62,113 @@ export default class Home extends Vue {
console.log('§§§§§§§§§§§§§§§§§§§§ IMPOSTA DEFERRED PROMPT !!!!!!!!!!!!!!!!! ') console.log('§§§§§§§§§§§§§§§§§§§§ IMPOSTA DEFERRED PROMPT !!!!!!!!!!!!!!!!! ')
return false return false
}) })
} }
getPermission() {
return Notification.permission
}
displayConfirmNotification() {
let options = null
if ('serviceWorker' in navigator) {
options = {
body: 'You successfully subscribed to our Notification service!',
icon: '/statics/icons/app-icon-96x96.png',
image: '/src/images/sf-boat.jpg',
dir: 'ltr',
lang: 'en-US', // BCP 47,
vibrate: [100, 50, 200],
badge: '/statics/icons/app-icon-96x96.png',
tag: 'confirm-notification',
renotify: true, // if it's already sent, will Vibrate anyway
actions: [
{ action: 'confirm', title: 'Okay', icon: '/statics/icons/app-icon-96x96.png' },
{ action: 'cancel', title: 'Cancel', icon: '/statics/icons/app-icon-96x96.png' }
]
}
navigator.serviceWorker.ready
.then(function (swreg) {
swreg.showNotification('Successfully subscribed!', options)
})
}
}
urlBase64ToUint8Array(base64String) {
let padding = '='.repeat((4 - base64String.length % 4) % 4)
let base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/')
let rawData = window.atob(base64)
let outputArray = new Uint8Array(rawData.length)
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i)
}
return outputArray
}
dataURItoBlob(dataURI) {
let byteString = atob(dataURI.split(',')[1])
let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
let ab = new ArrayBuffer(byteString.length)
let ia = new Uint8Array(ab)
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i)
}
let blob = new Blob([ab], { type: mimeString })
return blob
}
showNotificationExample() {
let options = null
let mythis = this
if ('serviceWorker' in navigator) {
options = {
body: mythis.$t('notification.subscribed'),
icon: '/statics/icons/android-chrome-192x192.png',
image: '/statics/images/freeplanet.png',
dir: 'ltr',
lang: 'en-US', // BCP 47,
vibrate: [100, 50, 200],
badge: '/statics/icons/android-chrome-192x192.png',
tag: 'confirm-notification',
renotify: true, // if it's already sent, will Vibrate anyway
actions: [
{ action: 'confirm', title: mythis.$t('dialog.ok'), icon: '/statics/icons/android-chrome-192x192.png', }
// { action: 'cancel', title: 'Cancel', icon: '/statics/icons/android-chrome-192x192.png', }
]
}
navigator.serviceWorker.ready
.then(function (swreg) {
swreg.showNotification('aaa', options)
})
}
}
askfornotification() {
this.showNotification(this.$t('notification.waitingconfirm'), 'positive', 'notifications')
let mythis = this
Notification.requestPermission(function (result) {
console.log('User Choice', result)
if (result === 'granted') {
mythis.showNotification(mythis.$t('notification.confirmed'), 'positive', 'notifications')
} else {
mythis.showNotification(mythis.$t('notification.denied'), 'negative', 'notifications')
// displayConfirmNotification();
}
})
}
test_fetch() { test_fetch() {
fetch('https:/httpbin.org/post', { fetch('https:/httpbin.org/post', {
method: 'POST', method: 'POST',

View File

@@ -2,6 +2,22 @@
<q-page class="flex flex-center"> <q-page class="flex flex-center">
<logo></logo> <logo></logo>
<q-btn v-if="getPermission() !== 'granted'" class="enable-notifications" color="primary" rounded size="lg" icon="notifications" @click="askfornotification" :label="$t('notification.ask')"/>
<q-btn v-if="getPermission() === 'granted'" class="enable-notifications" color="primary" rounded size="lg" icon="notifications" @click="showNotificationExample" label="Send Notification"/>
<!--<q-btn v-if="getPermission() === 'granted'" class="enable-notifications" color="secondary" rounded size="lg" icon="notifications" @click="createPushSubscription" label="Create Push Subscription !"/>-->
<br>
<div>
<q-chip square color="secondary">
Status:
</q-chip>
<q-field
v-if="getPermission() === 'granted'"
icon="notifications"
:label="$t('notification.titlegranted')"
helper="Stato Notifiche">
</q-field>
</div>
</q-page> </q-page>

File diff suppressed because one or more lines are too long

View File

@@ -1,13 +1,14 @@
const messages = { const messages = {
it: { it: {
dialog: { dialog: {
ok: 'Ok',
yes: 'Si', yes: 'Si',
no: 'No', no: 'No',
delete: 'Elimina', delete: 'Elimina',
cancel: 'Annulla', cancel: 'Annulla',
msg: { msg: {
titledeleteTask: 'Cancella Task', titledeleteTask: 'Elimina Task',
deleteTask: 'Vuoi cancellare questo Task?' deleteTask: 'Vuoi Eliminare questo Task?'
} }
}, },
comp:{ comp:{
@@ -47,6 +48,13 @@ const messages = {
} }
} }
}, },
fetch: {
errore_generico: 'Errore Generico',
errore_server: 'Impossibile accedere al Server. Riprovare Grazie',
},
user: {
notregistered: 'Devi registrarti al servizio prima di porter memorizzare i dati'
},
reg: { reg: {
incorso: 'Registrazione in corso...', incorso: 'Registrazione in corso...',
richiesto: 'Campo Richiesto', richiesto: 'Campo Richiesto',
@@ -101,11 +109,147 @@ const messages = {
titleprioritymenu: 'Priorità:', titleprioritymenu: 'Priorità:',
insert: 'Inserisci il Task', insert: 'Inserisci il Task',
edit: 'Descrizione Task:', edit: 'Descrizione Task:',
completed: 'Completati' completed: 'Completati',
usernotdefined: 'Attenzione, occorre essere Loggati per poter aggiungere un Todo'
},
notification : {
ask: 'Attiva le Notifiche',
waitingconfirm: 'Conferma la richiesta di Notifica',
confirmed: 'Notifiche Attivate!',
denied: 'Notifiche Disabilitate! Attenzione così non vedrai arrivarti i messaggi. Riabilitali per vederli.',
titlegranted: 'Permesso Notifiche Abilitato!',
titledenied: 'Permesso Notifiche Disabilitato!',
title_subscribed: 'Sottoscrizione a FreePlanet.app!',
subscribed: 'Ora potrai ricevere i messaggi e le notifiche.'
}
},
es: {
dialog: {
ok: 'Vale',
yes: 'Sí',
no: 'No',
delete: 'Borrar',
cancel: 'Cancelar',
msg: {
titledeleteTask: 'Borrar Tarea',
deleteTask: 'Quieres borrar este tarea?'
}
},
comp:{
Conta: "Conta",
},
msg: {
hello: 'Buenos Días',
myAppName: 'FreePlanet',
myDescriz: 'La primera App Libera'
},
pages: {
home: 'Principal',
SignUp: 'Registrarte',
SignIn: 'Login',
vreg: 'Verifica Reg',
Test: 'Test',
Category: 'Categorías',
Todo: 'Tareas',
personal: 'Personal',
work: 'Trabajo',
shopping: 'Compras',
},
components: {
authentication:{
login: {
facebook: 'Facebook'
},
email_verification: {
title: 'Crea una cuenta',
introduce_email: 'ingrese su dirección de correo electrónico',
email: 'Email',
invalid_email: 'Tu correo electrónico no es válido',
verify_email: 'Revisa tu email',
go_login: 'Vuelve al Login',
incorrect_input: 'Entrada correcta.',
link_sent: 'Para confirmar el registro, lea su buzón y haga clic en "Verificar correo electrónico".\n' + 'Si no lo encuentras, busca en la carpeta Spam.'
}
}
},
fetch: {
errore_generico: 'Error genérico',
errore_server: 'No se puede acceder al Servidor. Inténtalo de nuevo, Gracias',
},
user: {
notregistered: 'Debe registrarse en el servicio antes de poder almacenar los datos'
},
reg: {
incorso: 'Registro en curso...',
richiesto: 'Campo requerido',
email: 'Email',
username : 'Nombre usuario',
password: 'contraseña',
repeatPassword: 'Repetir contraseña',
terms: "Acepto los términos y condiciones",
submit: "Registrarse",
title_verif_reg: "Verifica registro",
verificato: "Verificado",
non_verificato: "No Verificado",
forgetpassword:"¿Olvidaste tu contraseña?",
err: {
required: 'se requiere',
email: 'Debe ser una email válida.',
errore_generico: 'Por favor, rellene los campos correctamente',
atleast: 'debe ser al menos largo',
complexity: 'debe contener al menos 1 minúscula, 1 mayúscula y 1 dígito',
notmore: 'no tiene que ser más largo que',
char: 'caracteres',
terms: 'Debes aceptar las condiciones, para continuar..',
duplicate_email: 'La email ya ha sido registrada',
duplicate_username: 'El nombre de usuario ya ha sido utilizado',
sameaspassword: 'Las contraseñas deben ser idénticas',
}
},
login:{
incorso: 'Login en curso',
enter: 'Login',
errato: "Nombre de usuario o contraseña incorrectos. inténtelo de nuevo",
completato: 'Login realizado!',
},
reset: {
title_reset_pwd: "Restablece tu contraseña",
send_reset_pwd: 'Enviar restablecer contraseña',
incorso: 'Solicitar nueva Email...',
email_sent:'Email enviada',
check_email: 'Revise su correo electrónico, recibirá un mensaje con un enlace para restablecer su contraseña. Este enlace, por razones de seguridad, expirará después de 4 horas.',
title_update_pwd: 'Actualiza tu contraseña',
update_password: 'Actualizar contraseña',
},
logout:{
uscito: 'Estás desconectado',
},
errors: {
graphql: {
undefined: 'no definido'
}
},
todo: {
titleprioritymenu: 'Prioridad:',
insert: 'Ingrese una nueva Tarea',
edit: 'Descripción Tarea:',
completed: 'Completados',
usernotdefined: 'Atención, debes iniciar sesión para agregar una Tarea'
},
notification : {
ask: 'Activar notificaciones',
waitingconfirm: 'Confirmar la solicitud de notificación.',
confirmed: 'Notificaciones activadas!',
denied: 'Notificaciones deshabilitadas! Ten cuidado, así no verás llegar los mensajes. Rehabilítalos para verlos.',
titlegranted: 'Notificaciones permitidas habilitadas!',
titledenied: 'Notificaciones permitidas deshabilitadas!',
title_subscribed: 'Suscripción a FreePlanet.app!',
subscribed: 'Ahora puedes recibir mensajes y notificaciones.'
} }
}, },
enUk: { enUk: {
dialog: { dialog: {
ok: 'Ok',
yes: 'Yes', yes: 'Yes',
no: 'No', no: 'No',
delete: 'Delete', delete: 'Delete',
@@ -152,6 +296,13 @@ const messages = {
} }
} }
}, },
fetch: {
errore_generico: 'Generic Error',
errore_server: 'Unable to access to the Server. Retry. Thank you.',
},
user: {
notregistered: 'You need first to SignUp before storing data'
},
reg: { reg: {
incorso: 'Registration please wait...', incorso: 'Registration please wait...',
richiesto: 'Field Required', richiesto: 'Field Required',
@@ -206,7 +357,18 @@ const messages = {
titleprioritymenu: 'Priority:', titleprioritymenu: 'Priority:',
insert: 'Insert Task', insert: 'Insert Task',
edit: 'Task Description:', edit: 'Task Description:',
completed: 'Completed' completed: 'Completed',
usernotdefined: 'Attention, you need to be Signed In to add a new Task'
},
notification : {
ask: 'Enable Notification',
waitingconfirm: 'Confirm the Request Notification',
confirmed: 'Notifications Enabled!',
denied: 'Notifications Disabled! Attention, you will not see your messages incoming. Reenable it for see it',
titlegranted: 'Notification Permission Granted!',
titledenied: 'Notification Permission Denied!',
title_subscribed: 'Subscribed to FreePlanet.app!',
subscribed: 'You can now receive Notification and Messages.'
} }
}, },
}; };

View File

Before

Width:  |  Height:  |  Size: 190 KiB

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

8
src/statics/js/immortal-db.min.js vendored Normal file

File diff suppressed because one or more lines are too long

109
src/statics/js/storage.js Normal file
View File

@@ -0,0 +1,109 @@
let idbKeyval = (() => {
let db;
function getDB() {
if (!db) {
// console.log('CREO DB STORAGE JS !')
db = new Promise((resolve, reject) => {
const openreq = indexedDB.open('mydb3', 11);
openreq.onerror = () => {
reject(openreq.error);
};
openreq.onupgradeneeded = () => {
// First time setup: create an empty object store
openreq.result.createObjectStore('todos', { keyPath: '_id' });
openreq.result.createObjectStore('sync_todos', { keyPath: '_id' });
openreq.result.createObjectStore('sync_todos_patch', { keyPath: '_id' });
openreq.result.createObjectStore('delete_todos', { keyPath: '_id' });
openreq.result.createObjectStore('config', { keyPath: '_id' });
openreq.result.createObjectStore('swmsg', { keyPath: '_id' });
};
openreq.onsuccess = () => {
resolve(openreq.result);
};
});
}
return db;
}
async function withStore(type, table, callback, ) {
const db = await getDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction(table, type);
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject(transaction.error);
callback(transaction.objectStore(table));
});
}
return {
async get(key) {
let req;
await withStore('readonly', 'keyval', store => {
req = store.get(key);
});
return req.result;
},
async getdata(table, key) {
let req;
await withStore('readonly', table, store => {
console.log('store', store, 'key', key)
req = store.get(key);
});
// console.log('RISFINALE!', req.result)
return req.result;
},
async getalldata(table) {
let req;
await withStore('readonly', table, store => {
req = store.getAll();
});
return req.result;
},
async set(key, value) {
let req;
await withStore('readwrite', 'keyval', store => {
req = store.put(value, key);
});
return req.result;
},
async setdata(table, value) {
let req;
console.log('setdata', table, value)
await withStore('readwrite', table, store => {
req = store.put(value);
});
return req.result;
},
async delete(key) {
return await withStore('readwrite', 'keyval', store => {
store.delete(key);
});
},
async deletedata(table, key) {
return await withStore('readwrite', table, store => {
store.delete(key);
});
},
async clearalldata(table) {
return await withStore('readwrite', table, store => {
store.clear();
});
}
};
})();
// iOS add-to-homescreen is missing IDB, or at least it used to.
// I haven't tested this in a while.
if (!self.indexedDB) {
idbKeyval = {
get: key => Promise.resolve(localStorage.getItem(key)),
set: (key, val) => Promise.resolve(localStorage.setItem(key, val)),
delete: key => Promise.resolve(localStorage.removeItem(key))
};
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

View File

@@ -1,18 +1,36 @@
import axios, { AxiosInstance, AxiosPromise, AxiosResponse, AxiosInterceptorManager } from 'axios' import axios, { AxiosInstance, AxiosPromise, AxiosResponse, AxiosInterceptorManager } from 'axios'
async function sendRequest (url: string, lang: string, mytok: string, method: string, mydata: any) { async function sendRequest(url: string, lang: string, mytok: string, method: string, mydata: any) {
console.log('LANG ' + lang)
// let mytok: string = this.getTok()
const authHeader = new Headers()
authHeader.append('content-type', 'application/json') console.log('sendRequest', method, url, '[', lang, ']')
const authHeader = new Headers()
authHeader.append('content-Type', 'application/json')
authHeader.append('Accept', 'application/json')
authHeader.append('x-auth', mytok) authHeader.append('x-auth', mytok)
authHeader.append('accept-language', lang) // authHeader.append('accept-language', lang)
const configInit: RequestInit = {
method: method, let configInit: RequestInit
cache: 'no-cache',
body: JSON.stringify(mydata), if (method === 'GET') {
headers: authHeader configInit = {
method: method,
cache: 'no-cache',
headers: authHeader
}
} else if (method === 'DELETE') {
configInit = {
method: method,
cache: 'no-cache',
headers: authHeader
}
} else {
configInit = {
method: method,
cache: 'no-cache',
body: JSON.stringify(mydata),
headers: authHeader
}
} }
const request: Promise<Response> = fetch(url, configInit) const request: Promise<Response> = fetch(url, configInit)

View File

@@ -1,10 +1,16 @@
import Request from './Instance' import Request from './Instance'
import sendRequest from './Inst-Pao' import sendRequest from './Inst-Pao'
export * from './ApiTypes' export * from './ApiTypes'
import axios from 'axios' import axios from 'axios'
export {addAuthHeaders, removeAuthHeaders, API_URL} from './Instance'
export { addAuthHeaders, removeAuthHeaders, API_URL } from './Instance'
// import {AlgoliaSearch} from './AlgoliaController' // import {AlgoliaSearch} from './AlgoliaController'
import Paths from '@paths' import Paths from '@paths'
import { rescodes } from '@src/store/Modules/rescodes'
import { UserStore } from '@modules'
import globalroutines from './../../globalroutines/index'
// const algoliaApi = new AlgoliaSearch() // const algoliaApi = new AlgoliaSearch()
@@ -12,19 +18,24 @@ export namespace ApiTool {
export async function post(path: string, payload?: any) { export async function post(path: string, payload?: any) {
return await Request('post', path, payload) return await Request('post', path, payload)
} }
export async function postFormData(path: string, payload?: any) { export async function postFormData(path: string, payload?: any) {
return await Request('postFormData', path, payload) return await Request('postFormData', path, payload)
} }
export async function get(path: string, payload?: any) { export async function get(path: string, payload?: any) {
return await Request('get', path, payload) return await Request('get', path, payload)
} }
export async function put(path: string, payload?: any) { export async function put(path: string, payload?: any) {
return await Request('put', path, payload) return await Request('put', path, payload)
} }
export async function Delete(path: string, payload: any) { export async function Delete(path: string, payload: any) {
return await Request('delete', path, payload) return await Request('delete', path, payload)
} }
export async function checkSession({token, refresh_token}) {
export async function checkSession({ token, refresh_token }) {
return await axios.post(process.env.API_URL + Paths.TOKEN_REFRESH, { return await axios.post(process.env.API_URL + Paths.TOKEN_REFRESH, {
refresh_token refresh_token
}, { }, {
@@ -34,9 +45,139 @@ export namespace ApiTool {
}) })
} }
export async function SendReq(url: string, lang: string, mytok: string, method: string, mydata: any) { export async function SendReq(url: string, lang: string, mytok: string, method: string, mydata: any, noAuth: boolean = false) {
return await sendRequest(url, lang, mytok, method, mydata) UserStore.mutations.setServerCode(rescodes.EMPTY)
UserStore.mutations.setAuth('')
return await new Promise(function (resolve, reject) {
let ricevuto = false
sendRequest(url, lang, mytok, method, mydata)
.then(resreceived => {
ricevuto = true
let res = resreceived.clone()
if (process.env.DEV) {
console.log('SendReq RES [', res.status, ']', res)
}
let x_auth_token = ''
if (res.status === 200) {
try {
if (!noAuth) {
x_auth_token = String(res.headers.get('x-auth'))
if (url === process.env.MONGODB_HOST + '/updatepwd') {
UserStore.mutations.UpdatePwd({ idToken: x_auth_token })
localStorage.setItem(rescodes.localStorage.token, x_auth_token)
}
if (x_auth_token === '') {
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION)
}
}
UserStore.mutations.setServerCode(rescodes.OK)
UserStore.mutations.setAuth(x_auth_token)
} catch (e) {
if (!noAuth) {
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION)
UserStore.mutations.setAuth(x_auth_token)
}
return reject(e)
}
}
return res.json()
.then((body) => {
return resolve({ res, body })
})
.catch(e => {
UserStore.mutations.setServerCode(rescodes.ERR_GENERICO)
return reject(e)
})
})
.catch(error => {
if (process.env.DEV) {
console.log('ERROR using', url, error, 'ricevuto=', ricevuto)
}
if (!ricevuto) {
UserStore.mutations.setServerCode(rescodes.ERR_SERVERFETCH)
} else {
UserStore.mutations.setServerCode(rescodes.ERR_GENERICO)
}
return reject(error)
})
})
} }
export async function syncAlternative(mystrparam) {
console.log('[ALTERNATIVE Background syncing', mystrparam)
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('[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)
console.log('A1) INIZIO.............................................................')
await 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'
if (method !== 'POST')
link += '/' + rec._id
console.log(' [Alternative] ++++++++++++++++++ SYNCING !!!! ', rec.descr, table, 'FETCH: ', method, link, 'data:')
// Insert/Delete/Update table to the server
fetch(link, {
method: method,
headers: headers,
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);
globalroutines(null, 'delete', table, null, rec._id)
console.log('DELETE: ', mystrparam)
// deleteItemFromData('swmsg', mystrparam)
globalroutines(null, 'delete', 'swmsg', null, mystrparam)
})
.catch(function (err) {
console.log(' [Alternative] !!!!!!!!!!!!!!! Error while sending data', err)
})
}
}
})
console.log(' [Alternative] A2) ?????????????????????????? ESCO DAL LOOP !!!!!!!!! err=')
}
}
}
}
} }
export default ApiTool export default ApiTool

View File

@@ -1,9 +1,18 @@
import { IGlobalState } from 'model' import { IGlobalState } from 'model'
import { storeBuilder } from './Store/Store' import { storeBuilder } from './Store/Store'
import Vue from 'vue'
import translate from './../../globalroutines/util'
import urlBase64ToUint8Array from '../../js/utility'
import messages from '../../statics/i18n'
import { UserStore } from "@store"
const state: IGlobalState = { const state: IGlobalState = {
conta: 0, conta: 0,
isSubscribed: false,
isLoginPage: false, isLoginPage: false,
layoutNeeded: true, layoutNeeded: true,
mobileMode: false, mobileMode: false,
@@ -70,8 +79,111 @@ namespace Actions {
Mutations.mutations.setConta(num) Mutations.mutations.setConta(num)
} }
function createPushSubscription(context) {
if (!('serviceWorker' in navigator)) {
return
}
console.log('createPushSubscription')
let reg
const mykey = process.env.PUBLICKEY_PUSH
const mystate = state
navigator.serviceWorker.ready
.then(function (swreg) {
reg = swreg
return swreg.pushManager.getSubscription()
})
.then(function (subscription) {
mystate.isSubscribed = !(subscription === null)
if (mystate.isSubscribed) {
console.log('User is already Subscribed!')
} else {
// Create a new subscription
let convertedVapidPublicKey = urlBase64ToUint8Array(mykey)
return reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: convertedVapidPublicKey
})
}
})
.then(function (newSub) {
if (newSub) {
saveNewSubscriptionToServer(context, newSub)
mystate.isSubscribed = true;
}
return null
})
.catch(function (err) {
console.log(err)
})
}
// Calling the Server to Save in the MongoDB the Subscriber
function saveNewSubscriptionToServer(context, newSub) {
console.log('saveSubscriptionToServer: ', newSub)
console.log('context', context)
const options = {
title: translate('notification.title_subscribed'),
content: translate('notification.subscribed'),
openUrl: '/'
}
let myres = {
options: { ...options },
subs: newSub,
others: {
userId: UserStore.state.userId
}
}
return fetch(process.env.MONGODB_HOST + '/subscribe', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(myres)
})
}
function t(params) {
let msg = params.split('.')
let lang = UserStore.state.lang
let stringa = messages[lang]
let ris = stringa
msg.forEach(param => {
ris = ris[param]
})
return ris
}
function prova(context) {
// console.log('prova')
// let msg = t('notification.title_subscribed')
// console.log('msg', msg)
}
function loadAfterLogin (context) {
}
export const actions = { export const actions = {
setConta: b.dispatch(setConta) setConta: b.dispatch(setConta),
createPushSubscription: b.dispatch(createPushSubscription),
loadAfterLogin: b.dispatch(loadAfterLogin),
prova: b.dispatch(prova)
} }
} }

View File

@@ -1,12 +1,25 @@
import { ITodosState } from 'model' import { IGlobalState, ITodo, ITodosState } from 'model'
import { storeBuilder } from './Store/Store' import { storeBuilder } from './Store/Store'
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"
const state: ITodosState = { const state: ITodosState = {
visuOnlyUncompleted: false visuOnlyUncompleted: false,
networkDataReceived: false,
todos: [],
todos_changed: 1,
reload_fromServer: false,
testpao: 'Test',
insidePending: false
} }
const b = storeBuilder.module<ITodosState>('TodosModule', state) const b = storeBuilder.module<ITodosState>('TodosModule', state)
const stateGetter = b.state()
// Getters // Getters
namespace Getters { namespace Getters {
@@ -22,29 +35,307 @@ namespace Getters {
namespace Mutations { namespace Mutations {
function deleteItem(state: ITodosState, num: number) { function setTestpao(state: ITodosState, testpao: String) {
// state.conta = num state.testpao = testpao
// Cancella Item }
function setTodos_changed(state: ITodosState) {
state.todos_changed++
mutations.setTestpao('Cambiato : ' + String(state.todos_changed))
console.log('******************************* state.todos_changed', state.todos_changed)
} }
export const mutations = { export const mutations = {
deleteItem: b.commit(deleteItem), setTestpao: b.commit(setTestpao),
setTodos_changed: b.commit(setTodos_changed)
} }
} }
function consolelogpao(strlog, strlog2 = '', strlog3 = '') {
globalroutines(null, 'log', strlog + strlog2 + strlog3, null)
}
namespace Actions { namespace Actions {
async function deleteItem(context, num: number) {
Mutations.mutations.deleteItem(num) function json2array(json) {
let result = []
let keys = Object.keys(json)
keys.forEach(function (key) {
result.push(json[key])
})
return result
}
// If something in the call of Service Worker went wrong (Network or Server Down), then retry !
async function sendSwMsgIfAvailable() {
let something = false
if ('serviceWorker' in navigator) {
console.log(' -------- sendSwMsgIfAvailable')
let count = await checkPendingMsg(null)
if (count > 0) {
return navigator.serviceWorker.ready
.then(function (sw) {
globalroutines(null, 'readall', 'swmsg')
.then(function (arr_recmsg) {
// let recclone = [...arr_recmsg]
if (arr_recmsg.length > 0) {
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 {
// #Todo ++ Alternative to SyncManager
Api.syncAlternative(rec._id)
}
}
return something
}
})
})
}
}
return something
}
async function waitAndcheckPendingMsg(context) {
await aspettansec(1000)
// console.log('waitAndcheckPendingMsg')
return await checkPendingMsg(context)
.then(ris => {
if (ris) {
console.log('ris = ', ris)
const result = sendSwMsgIfAvailable()
.then(something => {
if (something) {
// Refresh data
waitAndRefreshData(context)
}
})
}
})
}
async function waitAndRefreshData(context) {
await aspettansec(3000)
console.log('waitAndRefreshData')
return await dbLoadTodo(context, false)
}
async function checkPendingMsg(context) {
// console.log('checkPendingMsg')
return new Promise(function (resolve, reject) {
/*
globalroutines(null, 'readall', 'swmsg')
.then(function (arr_recmsg) {
if (arr_recmsg.length > 0) {
*/
// Check if there is something
globalroutines(null, 'count', 'swmsg')
.then(function (count) {
if (count > 0) {
console.log('count = ', count)
return resolve(true)
} else {
return resolve(false)
}
})
.catch(e => {
return reject()
})
})
}
async function dbLoadTodo(context, checkPending: boolean = false) {
console.log('dbLoadTodo', checkPending)
const token = UserStore.state.idToken
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 }) => {
state.networkDataReceived = true
// console.log('******* UPDATE TODOS.STATE.TODOS !:', resData.todos)
state.todos = [...body.todos]
Todos.mutations.setTodos_changed()
console.log('state.todos', state.todos, 'checkPending', checkPending)
// After Login will store into the indexedDb...
return rescodes.OK
})
.catch((error) => {
UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode
})
console.log('fine della funz...')
if (!Todos.state.networkDataReceived) {
console.log('NETWORK UNREACHABLE ! (Error in fetch)')
consolelogpao('NETWORK UNREACHABLE ! (Error in fetch)')
// Read all data from IndexedDB Store into Memory
await updateArrayInMemory(context)
} else {
if (ris === rescodes.OK && checkPending) {
waitAndcheckPendingMsg(context)
}
}
}
async function updateArrayInMemory(context) {
console.log('Update the array in memory, from todos table from IndexedDb')
await globalroutines(null, 'updateinMemory', 'todos', null)
.then(() => {
// console.log('updateArrayInMemory! ')
return true
})
}
function aspettansec(numsec) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('anything')
}, numsec)
})
}
async function testfunc() {
while (true) {
consolelogpao('testfunc')
Todos.mutations.setTodos_changed()
// console.log('Todos.state.todos_changed:', Todos.state.todos_changed)
await aspettansec(5000)
}
}
async function dbSaveTodo(context, itemtodo: ITodo) {
return await dbInsertSaveTodo(context, itemtodo, 'PATCH')
}
async function dbInsertTodo(context, itemtodo: ITodo) {
return await dbInsertSaveTodo(context, itemtodo, 'POST')
}
function UpdateNewIdFromDB(oldItem, newItem, method) {
console.log('PRIMA state.todos', state.todos)
console.log('ITEM', newItem)
if (method === 'POST') {
state.todos.push(newItem)
Todos.mutations.setTodos_changed()
// } else if (method === 'PATCH') {
// state.todos.map(item => {
// if (item._id === newItem._id) {
// return newItem
// }
// })
}
console.log('DOPO state.todos', state.todos)
}
async function dbInsertSaveTodo(context, itemtodo: ITodo, method) {
console.log('dbInsertSaveTodo', itemtodo, method)
let call = process.env.MONGODB_HOST + '/todos'
if (method !== 'POST')
call += '/' + itemtodo._id
const token = UserStore.state.idToken
let res = await Api.SendReq(call, UserStore.state.lang, token, method, itemtodo)
.then(({ res, newItem }) => {
console.log('dbInsertSaveTodo RIS =', newItem)
if (newItem) {
// Update ID on local
UpdateNewIdFromDB(itemtodo, newItem, method)
}
})
.catch((error) => {
UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode
})
return res
}
async function dbDeleteTodo(context, item: ITodo) {
console.log('dbDeleteTodo', item)
let call = process.env.MONGODB_HOST + '/todos/' + item._id
const token = UserStore.state.idToken
let res = await Api.SendReq(call, UserStore.state.lang, token, 'DELETE', item)
.then(function ({ res, itemris }) {
if (res.status === 200) {
// Delete Item in to Array
state.todos.splice(state.todos.indexOf(item), 1)
Todos.mutations.setTodos_changed()
}
return rescodes.OK
})
.catch((error) => {
UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode
})
return res
}
async function getTodosByCategory(context, category: string) {
let myarr = state.todos.filter((p) => {
return p.category === category
})
return myarr
} }
export const actions = { export const actions = {
setConta: b.dispatch(deleteItem) dbInsertTodo: b.dispatch(dbInsertTodo),
dbSaveTodo: b.dispatch(dbSaveTodo),
dbLoadTodo: b.dispatch(dbLoadTodo),
dbDeleteTodo: b.dispatch(dbDeleteTodo),
updateArrayInMemory: b.dispatch(updateArrayInMemory),
getTodosByCategory: b.dispatch(getTodosByCategory),
checkPendingMsg: b.dispatch(checkPendingMsg),
waitAndcheckPendingMsg: b.dispatch(waitAndcheckPendingMsg)
} }
} }
const stateGetter = b.state()
// Module // Module
const TodosModule = { const TodosModule = {
@@ -56,6 +347,4 @@ const TodosModule = {
actions: Actions.actions actions: Actions.actions
} }
export default TodosModule
export default ITodosState

View File

@@ -6,15 +6,17 @@ import router from '@router'
import { serv_constants } from '../Modules/serv_constants' import { serv_constants } from '../Modules/serv_constants'
import { rescodes } from '../Modules/rescodes' import { rescodes } from '../Modules/rescodes'
import { GlobalStore, UserStore } from '@store' import { GlobalStore, UserStore, Todos } from '@store'
import globalroutines from './../../globalroutines/index'
import translate from './../../globalroutines/util'
const bcrypt = require('bcryptjs') const bcrypt = require('bcryptjs')
// State // State
const state: IUserState = { const state: IUserState = {
userId: '', userId: '',
email: '', email: '',
username: '', username: '',
idapp: process.env.APP_ID, idapp: process.env.APP_ID,
password: '', password: '',
@@ -22,8 +24,10 @@ const state: IUserState = {
repeatPassword: '', repeatPassword: '',
idToken: '', idToken: '',
tokens: [], tokens: [],
verifiedEmail: false, verified_email: false,
categorySel: 'personal' categorySel: 'personal',
servercode: 0,
x_auth_token: ''
} }
@@ -52,15 +56,30 @@ namespace Getters {
} }
}, 'tok') }, 'tok')
const isServerError = b.read(state => {
return (state.servercode === rescodes.ERR_SERVERFETCH)
}, 'isServerError')
const getServerCode = b.read(state => {
return state.servercode
}, 'getServerCode')
export const getters = { export const getters = {
get lang() { get lang() {
return lang() return lang()
}, },
get tok() { get tok() {
return tok() return tok()
},
get isServerError() {
return isServerError()
},
get getServerCode() {
return getServerCode()
} }
} }
} }
@@ -69,7 +88,7 @@ namespace Mutations {
state.userId = data.userId state.userId = data.userId
state.username = data.username state.username = data.username
state.idToken = data.idToken state.idToken = data.idToken
state.verifiedEmail = data.verifiedEmail state.verified_email = data.verified_email
state.category = data.categorySel state.category = data.categorySel
// @ts-ignore // @ts-ignore
state.tokens = [ state.tokens = [
@@ -102,15 +121,46 @@ namespace Mutations {
state.servercode = num state.servercode = num
} }
function setAuth(state: IUserState, x_auth_token: string) {
state.x_auth_token = x_auth_token
}
function clearAuthData(state: IUserState) { function clearAuthData(state: IUserState) {
state.userId = '' state.userId = ''
state.username = '' state.username = ''
state.tokens = [] state.tokens = []
state.idToken = '' state.idToken = ''
state.verifiedEmail = false state.verified_email = false
state.categorySel = 'personal' state.categorySel = 'personal'
} }
function setErrorCatch(state: IUserState, err: number) {
if (state.servercode !== rescodes.ERR_SERVERFETCH) {
state.servercode = err
}
}
function getMsgError(state: IUserState, err: number) {
let msgerrore = ''
if (err !== rescodes.OK) {
msgerrore = 'Error [' + state.servercode + ']: '
if (state.servercode === rescodes.ERR_SERVERFETCH) {
msgerrore = translate('fetch.errore_server')
} else {
msgerrore = translate('fetch.errore_generico')
}
if (process.env.DEV) {
console.log('ERROREEEEEEEEE: ', msgerrore, ' (', err, ')')
}
}
// return { code: state.servercode, msg: msgerrore }
return msgerrore
}
export const mutations = { export const mutations = {
authUser: b.commit(authUser), authUser: b.commit(authUser),
setpassword: b.commit(setpassword), setpassword: b.commit(setpassword),
@@ -118,16 +168,20 @@ namespace Mutations {
setlang: b.commit(setlang), setlang: b.commit(setlang),
UpdatePwd: b.commit(UpdatePwd), UpdatePwd: b.commit(UpdatePwd),
setServerCode: b.commit(setServerCode), setServerCode: b.commit(setServerCode),
clearAuthData: b.commit(clearAuthData) setAuth: b.commit(setAuth),
clearAuthData: b.commit(clearAuthData),
setErrorCatch: b.commit(setErrorCatch),
getMsgError: b.commit(getMsgError)
} }
} }
namespace Actions { namespace Actions {
async function sendUserEdit(context, form: Object) { async function sendUserEdit(context, form: Object) {
try { try {
const {data} = await Api.postFormData('profile/edit', form) const { data } = await Api.postFormData('profile/edit', form)
console.log(data) console.log(data)
// return new ApiSuccess({data}) // return new ApiSuccess({data})
@@ -136,8 +190,7 @@ namespace Actions {
} }
} }
async function resetpwd(context, paramquery: IUserState) {
async function resetpwd (context, paramquery: IUserState) {
let call = process.env.MONGODB_HOST + '/updatepwd' let call = process.env.MONGODB_HOST + '/updatepwd'
console.log('CALL ' + call) console.log('CALL ' + call)
@@ -152,36 +205,18 @@ namespace Actions {
Mutations.mutations.setServerCode(rescodes.CALLING) Mutations.mutations.setServerCode(rescodes.CALLING)
let myres return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend)
.then(({ res, body }) => {
let x_auth_token: string = ''
return Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend)
.then((res) => {
console.log(res)
myres = res
x_auth_token = String(res.headers.get('x-auth'))
if (myres.status === 200) {
return myres.json()
}
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO)
return { code: rescodes.ERR_GENERICO, msg: 'Errore: ' + myres.status, resetpwd: true }
})
.then((body) => {
Mutations.mutations.UpdatePwd({ idToken: x_auth_token })
localStorage.setItem(rescodes.localStorage.token, x_auth_token)
return { code: body.code, msg: body.msg } return { code: body.code, msg: body.msg }
}).catch((err) => { })
console.log('ERROR: ' + err) .catch((error) => {
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO) UserStore.mutations.setErrorCatch(error)
return { code: rescodes.ERR_GENERICO, msg: 'Errore' } return UserStore.getters.getServerCode
}) })
} }
async function requestpwd (context, paramquery: IUserState) { async function requestpwd(context, paramquery: IUserState) {
let call = process.env.MONGODB_HOST + '/requestnewpwd' let call = process.env.MONGODB_HOST + '/requestnewpwd'
console.log('CALL ' + call) console.log('CALL ' + call)
@@ -195,30 +230,17 @@ namespace Actions {
Mutations.mutations.setServerCode(rescodes.CALLING) Mutations.mutations.setServerCode(rescodes.CALLING)
let myres return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend)
.then(({ res, body }) => {
return Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend)
.then((res) => {
console.log(res)
myres = res
if (myres.status === 200) {
return myres.json()
}
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO)
return { code: rescodes.ERR_GENERICO, msg: 'Errore: ' + myres.status, resetpwd: true }
})
.then((body) => {
return { code: body.code, msg: body.msg } return { code: body.code, msg: body.msg }
}).catch((err) => { }).catch((error) => {
console.log('ERROR: ' + err) UserStore.mutations.setErrorCatch(error)
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO) return UserStore.getters.getServerCode
return { code: rescodes.ERR_GENERICO, msg: 'Errore' }
}) })
} }
async function vreg (context, paramquery: ILinkReg) { async function vreg(context, paramquery: ILinkReg) {
let call = process.env.MONGODB_HOST + '/vreg' let call = process.env.MONGODB_HOST + '/vreg'
console.log('CALL ' + call) console.log('CALL ' + call)
@@ -231,20 +253,8 @@ namespace Actions {
Mutations.mutations.setServerCode(rescodes.CALLING) Mutations.mutations.setServerCode(rescodes.CALLING)
let myres
return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend) return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend)
.then((res) => { .then(({ res, body }) => {
console.log(res)
myres = res
if (myres.status === 200) {
return myres.json()
}
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO)
return { code: rescodes.ERR_GENERICO, msg: 'Errore: ' + myres.status }
})
.then((body) => {
// console.log("RITORNO 2 "); // console.log("RITORNO 2 ");
// mutations.setServerCode(myres); // mutations.setServerCode(myres);
if (body.code === serv_constants.RIS_CODE_EMAIL_VERIFIED) { if (body.code === serv_constants.RIS_CODE_EMAIL_VERIFIED) {
@@ -254,14 +264,13 @@ namespace Actions {
console.log('Risultato di vreg: ', body.code) console.log('Risultato di vreg: ', body.code)
} }
return { code: body.code, msg: body.msg } return { code: body.code, msg: body.msg }
}).catch((err) => { }).catch((error) => {
console.log('ERROR: ' + err) UserStore.mutations.setErrorCatch(error)
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO) return UserStore.getters.getServerCode
return { code: rescodes.ERR_GENERICO, msg: 'Errore' }
}) })
} }
async function signup (context, authData: ISignupOptions) { async function signup(context, authData: ISignupOptions) {
let call = process.env.MONGODB_HOST + '/users' let call = process.env.MONGODB_HOST + '/users'
console.log('CALL ' + call) console.log('CALL ' + call)
@@ -290,27 +299,13 @@ namespace Actions {
let x_auth_token: string = '' let x_auth_token: string = ''
return Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend) return Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend)
.then((res) => { .then(({ res, newuser }) => {
myres = res myres = res
x_auth_token = String(res.headers.get('x-auth'))
if (x_auth_token) {
return res.json()
} else {
return { status: 400, code: rescodes.ERR_GENERICO }
}
})
.then((body) => {
if (process.env.DEV) {
console.log('RISULTATO ')
console.log('STATUS ' + myres.status + ' ' + (myres.statusText))
console.log('BODY:')
console.log(body)
}
Mutations.mutations.setServerCode(myres.status) Mutations.mutations.setServerCode(myres.status)
if (myres.status === 200) { if (myres.status === 200) {
let userId = body.userId let userId = newuser.userId
let username = authData.username let username = authData.username
if (process.env.DEV) { if (process.env.DEV) {
console.log('USERNAME = ' + username) console.log('USERNAME = ' + username)
@@ -321,7 +316,7 @@ namespace Actions {
userId: userId, userId: userId,
username: username, username: username,
idToken: x_auth_token, idToken: x_auth_token,
verifiedEmail: false verified_email: false
}) })
const now = new Date() const now = new Date()
@@ -332,34 +327,23 @@ namespace Actions {
localStorage.setItem(rescodes.localStorage.token, x_auth_token) localStorage.setItem(rescodes.localStorage.token, x_auth_token)
localStorage.setItem(rescodes.localStorage.expirationDate, expirationDate.toString()) localStorage.setItem(rescodes.localStorage.expirationDate, expirationDate.toString())
localStorage.setItem(rescodes.localStorage.verifiedEmail, '0') localStorage.setItem(rescodes.localStorage.verifiedEmail, '0')
state.isLogged = true
// dispatch('storeUser', authData); // dispatch('storeUser', authData);
// dispatch('setLogoutTimer', myres.data.expiresIn); // dispatch('setLogoutTimer', myres.data.expiresIn);
return rescodes.OK return rescodes.OK
} else if (myres.status === 404) {
if (process.env.DEV) {
console.log('CODE = ' + body.code)
}
return body.code
} else { } else {
if (process.env.DEV) { return rescodes.ERR_GENERICO
console.log('CODE = ' + body.code)
}
return body.code
} }
}) })
.catch((error) => { .catch((error) => {
if (process.env.DEV) { UserStore.mutations.setErrorCatch(error)
console.log('ERROREEEEEEEEE') return UserStore.getters.getServerCode
console.log(error)
}
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO)
return rescodes.ERR_GENERICO
}) })
}) })
} }
async function signin (context, authData: ISigninOptions) { async function signin(context, authData: ISigninOptions) {
let call = process.env.MONGODB_HOST + '/users/login' let call = process.env.MONGODB_HOST + '/users/login'
console.log('LOGIN ' + call) console.log('LOGIN ' + call)
@@ -379,29 +363,10 @@ namespace Actions {
Mutations.mutations.setServerCode(rescodes.CALLING) Mutations.mutations.setServerCode(rescodes.CALLING)
let x_auth_token: string = '' return await Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend)
.then(({ res, body }) => {
return Api.SendReq(call, state.lang, Getters.getters.tok, 'POST', usertosend)
.then((res) => {
myres = res myres = res
x_auth_token = String(res.headers.get('x-auth')) if (res.code === serv_constants.RIS_CODE_LOGIN_ERR) {
let injson = res.json()
if (x_auth_token || injson) {
return injson
} else {
return { status: 400, code: rescodes.ERR_GENERICO }
}
})
.then((body) => {
if (process.env.DEV) {
console.log('RISULTATO ')
console.log('STATUS ' + myres.status + ' ' + (myres.statusText))
console.log('BODY:')
console.log(body)
}
if (body.code === serv_constants.RIS_CODE_LOGIN_ERR) {
Mutations.mutations.setServerCode(body.code) Mutations.mutations.setServerCode(body.code)
return body.code return body.code
} }
@@ -409,17 +374,18 @@ namespace Actions {
Mutations.mutations.setServerCode(myres.status) Mutations.mutations.setServerCode(myres.status)
if (myres.status === 200) { if (myres.status === 200) {
let userId = body.userId let myuser: IUserState = body.usertosend
let userId = myuser.userId
let username = authData.username let username = authData.username
let verifiedEmail = body.verified_email === 'true' || body.verified_email === true let verifiedEmail = myuser.verified_email === true
if (process.env.DEV) { if (process.env.DEV) {
console.log('USERNAME = ' + username) console.log('USERNAME = ' + username)
console.log('IDUSER= ' + userId) console.log('IDUSER= ' + userId)
Mutations.mutations.authUser({ Mutations.mutations.authUser({
userId: userId, userId: userId,
username: username, username: username,
idToken: x_auth_token, idToken: state.x_auth_token,
verifiedEmail: verifiedEmail verified_email: verifiedEmail
}) })
} }
@@ -428,11 +394,13 @@ namespace Actions {
const expirationDate = new Date(now.getTime() * 1000) const expirationDate = new Date(now.getTime() * 1000)
localStorage.setItem(rescodes.localStorage.userId, userId) localStorage.setItem(rescodes.localStorage.userId, userId)
localStorage.setItem(rescodes.localStorage.username, username) 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.expirationDate, expirationDate.toString())
localStorage.setItem(rescodes.localStorage.isLogged, String(true)) localStorage.setItem(rescodes.localStorage.isLogged, String(true))
localStorage.setItem(rescodes.localStorage.verifiedEmail, Number(verifiedEmail).toString()) localStorage.setItem(rescodes.localStorage.verifiedEmail, Number(verifiedEmail).toString())
setGlobal()
// dispatch('storeUser', authData); // dispatch('storeUser', authData);
// dispatch('setLogoutTimer', myres.data.expiresIn); // dispatch('setLogoutTimer', myres.data.expiresIn);
return rescodes.OK return rescodes.OK
@@ -449,16 +417,12 @@ namespace Actions {
} }
}) })
.catch((error) => { .catch((error) => {
if (process.env.DEV) { UserStore.mutations.setErrorCatch(error)
console.log('ERROREEEEEEEEE') return UserStore.getters.getServerCode
console.log(error)
}
Mutations.mutations.setServerCode(rescodes.ERR_GENERICO)
return rescodes.ERR_GENERICO
}) })
} }
async function logout (context) { async function logout(context) {
let call = process.env.MONGODB_HOST + '/users/me/token' let call = process.env.MONGODB_HOST + '/users/me/token'
console.log('CALL ' + call) console.log('CALL ' + call)
@@ -469,16 +433,15 @@ namespace Actions {
} }
console.log(usertosend) console.log(usertosend)
Api.SendReq(call, state.lang, Getters.getters.tok, 'DELETE', usertosend) return await Api.SendReq(call, state.lang, Getters.getters.tok, 'DELETE', usertosend)
.then( .then(({ res, body }) => {
(res) => { console.log(res)
console.log(res) }).then(() => {
} Mutations.mutations.clearAuthData()
).catch((err) => { }).catch((error) => {
console.log('ERROR: ' + err) UserStore.mutations.setErrorCatch(error)
}).then(() => { return UserStore.getters.getServerCode
Mutations.mutations.clearAuthData() })
})
localStorage.removeItem(rescodes.localStorage.expirationDate) localStorage.removeItem(rescodes.localStorage.expirationDate)
localStorage.removeItem(rescodes.localStorage.token) localStorage.removeItem(rescodes.localStorage.token)
@@ -493,12 +456,21 @@ namespace Actions {
} }
function setGlobal() { function setGlobal() {
state.isLogged = true
GlobalStore.mutations.setleftDrawerOpen(localStorage.getItem(rescodes.localStorage.leftDrawerOpen) === 'true') GlobalStore.mutations.setleftDrawerOpen(localStorage.getItem(rescodes.localStorage.leftDrawerOpen) === 'true')
GlobalStore.mutations.setCategorySel(localStorage.getItem(rescodes.localStorage.categorySel)) GlobalStore.mutations.setCategorySel(localStorage.getItem(rescodes.localStorage.categorySel))
GlobalStore.actions.loadAfterLogin()
Todos.actions.dbLoadTodo(true)
} }
async function autologin (context) {
async function autologin(context) {
try { try {
console.log('*** Autologin ***')
// INIT // INIT
UserStore.mutations.setlang(process.env.LANG_DEFAULT) UserStore.mutations.setlang(process.env.LANG_DEFAULT)
// ++Todo: Estrai la Lang dal Localstorage // ++Todo: Estrai la Lang dal Localstorage
@@ -515,20 +487,26 @@ namespace Actions {
let expirationDate = new Date(String(expirationDateStr)) let expirationDate = new Date(String(expirationDateStr))
const now = new Date() const now = new Date()
if (now >= expirationDate) { if (now >= expirationDate) {
console.log('!!! Login Expired')
return false return false
} }
const userId = String(localStorage.getItem(rescodes.localStorage.userId)) const userId = String(localStorage.getItem(rescodes.localStorage.userId))
const username = String(localStorage.getItem(rescodes.localStorage.username)) const username = String(localStorage.getItem(rescodes.localStorage.username))
const verifiedEmail = localStorage.getItem(rescodes.localStorage.verifiedEmail) === '1' const verifiedEmail = localStorage.getItem(rescodes.localStorage.verifiedEmail) === '1'
setGlobal() console.log('autologin userId', userId)
Mutations.mutations.authUser({ Mutations.mutations.authUser({
userId: userId, userId: userId,
username: username, username: username,
idToken: token, idToken: token,
verifiedEmail: verifiedEmail verified_email: verifiedEmail
}) })
setGlobal()
console.log('autologin userId STATE ', state.userId)
return true return true
} catch (e) { } catch (e) {
console.error('ERR autologin ', e.message) console.error('ERR autologin ', e.message)

View File

@@ -1,3 +1,4 @@
export {storeBuilder} from './Store/Store' export {storeBuilder} from './Store/Store'
export {default as GlobalStore} from './GlobalStore' export {default as GlobalStore} from './GlobalStore'
export {default as UserStore} from './UserStore' export {default as UserStore} from './UserStore'
export {default as Todos} from './Todos'

View File

@@ -1,12 +1,15 @@
export const rescodes = { export const rescodes = {
EMPTY: 0,
CALLING: 10, CALLING: 10,
OK: 20, OK: 20,
ERR_GENERICO: -1, ERR_GENERICO: -1,
ERR_SERVERFETCH: -2,
ERR_AUTHENTICATION: -5,
DUPLICATE_EMAIL_ID: 11000, DUPLICATE_EMAIL_ID: 11000,
DUPLICATE_USERNAME_ID: 11100, DUPLICATE_USERNAME_ID: 11100,
LIST_END: 10000000, LIST_END: '10000000',
LIST_START: 0, LIST_START: '0',
localStorage: { localStorage: {
verifiedEmail: 'vf', verifiedEmail: 'vf',
@@ -25,6 +28,15 @@ export const rescodes = {
PRIORITY_LOW: 0 PRIORITY_LOW: 0
}, },
DB: {
CMD_SYNC_TODOS: 'sync-todos',
CMD_SYNC_NEW_TODOS: 'sync-new-todos',
CMD_DELETE_TODOS: 'sync-delete-todos',
TABLE_SYNC_TODOS : 'sync_todos',
TABLE_SYNC_TODOS_PATCH : 'sync_todos_patch',
TABLE_DELETE_TODOS : 'delete_todos'
},
MenuAction: { MenuAction: {
DELETE: 100, DELETE: 100,
TOGGLE_EXPIRING: 101, TOGGLE_EXPIRING: 101,
@@ -110,7 +122,7 @@ export const rescodes = {
}, },
{ {
id: 50, id: 50,
label: 'Cancella', label: 'Elimina',
value: 100, // DELETE value: 100, // DELETE
icon: 'delete', icon: 'delete',
checked: false checked: false
@@ -153,7 +165,8 @@ export const rescodes = {
checked: false checked: false
} }
] ]
} },
} }

View File

@@ -1,11 +1,14 @@
export const serv_constants = { export const serv_constants = {
RIS_CODE_TODO_CREATING_NOTMYUSER: -1001,
RIS_CODE_ERR: -99, RIS_CODE_ERR: -99,
RIS_CODE_EMAIL_ALREADY_VERIFIED: -5, RIS_CODE_EMAIL_ALREADY_VERIFIED: -5,
RIS_CODE_EMAIL_VERIFIED: 1, RIS_CODE_EMAIL_VERIFIED: 1,
RIS_CODE_OK: 1,
RIS_CODE_LOGIN_ERR_GENERIC: -20, RIS_CODE_LOGIN_ERR_GENERIC: -20,
RIS_CODE_LOGIN_ERR: -10, RIS_CODE_LOGIN_ERR: -10,
RIS_CODE_OK: 1,
RIS_CODE_LOGIN_OK: 1 RIS_CODE_LOGIN_OK: 1

8
src/typings/libs/globalroutines.d.ts vendored Normal file
View File

@@ -0,0 +1,8 @@
import { globalroutines } from '../../globalroutines'
declare module 'vue/types/vue' {
interface Vue {
$globalroutines: globalroutines
}
}

View File

@@ -6,13 +6,17 @@ switch (process.env.NODE_ENV) {
case 'test': case 'test':
path = `${__dirname}/../../.env.test` path = `${__dirname}/../../.env.test`
break break
case 'production': case 'development':
path = `${__dirname}/../../.env.production` path = `${__dirname}/../../.env.development`
break break
default: default:
path = `${__dirname}/../../.env.development` path = `${__dirname}/../../.env.production`
} }
dotenv.config({ path }) dotenv.config({ path })
console.log('path', path)
console.log('process.env.APP_ID', process.env.APP_ID)
export const APP_ID = process.env.APP_ID export const APP_ID = process.env.APP_ID
export const LOG_LEVEL = process.env.LOG_LEVEL export const LOG_LEVEL = process.env.LOG_LEVEL

View File

@@ -1,5 +1,5 @@
import { default as Axios, AxiosResponse } from 'axios' import { default as Axios, AxiosResponse } from 'axios'
import { IPayload } from 'model' // import { IPayload } from 'model'
import { GlobalConfig, PayloadMessageTypes } from '../common' import { GlobalConfig, PayloadMessageTypes } from '../common'
// const SITE_URL = GlobalConfig.uri.site // const SITE_URL = GlobalConfig.uri.site

View File

@@ -1,6 +1,6 @@
import Vue from 'vue' import Vue from 'vue'
import { Component, Prop, Watch } from 'vue-property-decorator' import { Component, Prop, Watch } from 'vue-property-decorator'
import { UserStore } from '@store' import { GlobalStore, UserStore } from '@store'
import { rescodes } from '../../../store/Modules/rescodes' import { rescodes } from '../../../store/Modules/rescodes'
import { serv_constants } from '../../../store/Modules/serv_constants' import { serv_constants } from '../../../store/Modules/serv_constants'
@@ -14,6 +14,8 @@ import { Logo } from '../../../components/logo'
import router from '@router' import router from '@router'
import globalroutines from '../../../globalroutines/index'
// import {Loading, QSpinnerFacebook, QSpinnerGears} from 'quasar' // import {Loading, QSpinnerFacebook, QSpinnerGears} from 'quasar'
@@ -75,6 +77,11 @@ export default class Signin extends Vue {
} else if (riscode === serv_constants.RIS_CODE_LOGIN_ERR) { } else if (riscode === serv_constants.RIS_CODE_LOGIN_ERR) {
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) {
this.showNotif(this.$t('fetch.errore_server'))
} else if (riscode === rescodes.ERR_GENERICO) {
let msg = this.$t('fetch.errore_generico') + UserStore.mutations.getMsgError(riscode)
this.showNotif(msg)
} else { } else {
this.showNotif('Errore num ' + riscode) this.showNotif('Errore num ' + riscode)
} }
@@ -115,13 +122,19 @@ 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)
if (riscode === rescodes.OK) { if (riscode === rescodes.OK) {
router.push('/signin') router.push('/signin')
globalroutines(this, 'loadapp', '')
GlobalStore.actions.createPushSubscription()
} }
this.checkErrors(riscode) this.checkErrors(riscode)
this.$q.loading.hide() this.$q.loading.hide()
}).catch(error => { }).catch(error => {
console.log('ERROR = ' + error) console.log('ERROR = ' + error)
this.checkErrors(error)
this.$q.loading.hide() this.$q.loading.hide()
}) })

View File

@@ -8,52 +8,54 @@
</div> </div>
<!--Prova URL : {{env('PROVA_PAOLO')}}--> <!--Prova URL : {{env('PROVA_PAOLO')}}-->
<form>
<q-field <q-field
:error="$v.signin.username.$error"
:error-label="`${errorMsg('username', $v.signin.username)}`"
>
<q-input
v-model="signin.username"
autocomplete="username"
@change="val => { signin.username = val }"
:before="[{icon: 'person', handler () {}}]"
@blur="$v.signin.username.$touch"
:error="$v.signin.username.$error" :error="$v.signin.username.$error"
:float-label="$t('reg.username')"></q-input> :error-label="`${errorMsg('username', $v.signin.username)}`"
</q-field> >
<q-input
v-model="signin.username"
autocomplete="username"
@change="val => { signin.username = val }"
:before="[{icon: 'person', handler () {}}]"
@blur="$v.signin.username.$touch"
:error="$v.signin.username.$error"
:float-label="$t('reg.username')"></q-input>
</q-field>
<q-field <q-field
:error="$v.signin.password.$error"
:error-label="`${errorMsg('password', $v.signin.password)}`"
>
<q-input
v-model="signin.password"
type="password"
:before="[{icon: 'vpn_key', handler () {}}]"
@blur="$v.signin.password.$touch"
:error="$v.signin.password.$error" :error="$v.signin.password.$error"
:float-label="$t('reg.password')"></q-input> :error-label="`${errorMsg('password', $v.signin.password)}`"
</q-field> >
<q-input
v-model="signin.password"
type="password"
:before="[{icon: 'vpn_key', handler () {}}]"
@blur="$v.signin.password.$touch"
:error="$v.signin.password.$error"
:float-label="$t('reg.password')"></q-input>
</q-field>
<div> <div>
<a :href="getlinkforgetpwd">{{$t('reg.forgetpassword')}}</a> <a :href="getlinkforgetpwd">{{$t('reg.forgetpassword')}}</a>
</div> </div>
<br> <br>
<q-card-main class="flex flex-center"> <q-card-main class="flex flex-center">
<!--<q-btn v-if="$myconfig.socialLogin.facebook" :loading="loading" class="q-mb-md q-mr-md" rounded icon="fab fa-facebook-f" size="sm" color="blue-10" text-color="white" @click="facebook" :label="$t('components.authentication.login.facebook')"/>--> <!--<q-btn v-if="$myconfig.socialLogin.facebook" :loading="loading" class="q-mb-md q-mr-md" rounded icon="fab fa-facebook-f" size="sm" color="blue-10" text-color="white" @click="facebook" :label="$t('components.authentication.login.facebook')"/>-->
<!-- <!--
<q-btn v-if="$myconfig.socialLogin.facebook" class="q-mb-md q-mr-md" rounded icon="fab fa-facebook-f" size="sm" color="blue-10" text-color="white" @click="facebook" :label="$t('components.authentication.login.facebook')"/> <q-btn v-if="$myconfig.socialLogin.facebook" class="q-mb-md q-mr-md" rounded icon="fab fa-facebook-f" size="sm" color="blue-10" text-color="white" @click="facebook" :label="$t('components.authentication.login.facebook')"/>
<q-btn v-if="$myconfig.socialLogin.google" class="q-mb-md q-mr-md" rounded icon="fab fa-google" size="sm" color="deep-orange-14" text-color="white" @click="google" :label="$t('components.authentication.login.google')"/> <q-btn v-if="$myconfig.socialLogin.google" class="q-mb-md q-mr-md" rounded icon="fab fa-google" size="sm" color="deep-orange-14" text-color="white" @click="google" :label="$t('components.authentication.login.google')"/>
--> -->
</q-card-main> </q-card-main>
<div align="center"> <div align="center">
<q-btn rounded size="lg" color="primary" @click="submit" :disable="$v.$error">{{$t('login.enter')}} <q-btn rounded size="lg" color="primary" @click="submit" :disable="$v.$error">{{$t('login.enter')}}
</q-btn> </q-btn>
</div> </div>
</form>
</q-page> </q-page>
</div> </div>
</template> </template>

View File

@@ -124,11 +124,16 @@ export default class Signup extends Vue {
} }
checkErrors(riscode: number) { checkErrors(riscode: number) {
// console.log("RIS = " + riscode); console.log('checkErrors', riscode)
if (riscode === rescodes.DUPLICATE_EMAIL_ID) { if (riscode === rescodes.DUPLICATE_EMAIL_ID) {
this.showNotif(this.$t('reg.err.duplicate_email')) this.showNotif(this.$t('reg.err.duplicate_email'))
} else if (riscode === rescodes.DUPLICATE_USERNAME_ID) { } else if (riscode === rescodes.DUPLICATE_USERNAME_ID) {
this.showNotif(this.$t('reg.err.duplicate_username')) this.showNotif(this.$t('reg.err.duplicate_username'))
} else if (riscode === rescodes.ERR_SERVERFETCH) {
this.showNotif(this.$t('fetch.errore_server'))
} else if (riscode === rescodes.ERR_GENERICO) {
let msg = this.$t('fetch.errore_generico') + UserStore.mutations.getMsgError(riscode)
this.showNotif(msg)
} else if (riscode === rescodes.OK) { } else if (riscode === rescodes.OK) {
this.$router.push('/signin') this.$router.push('/signin')
this.showNotif({type: 'warning', textColor: 'black', message: this.$t('components.authentication.email_verification.link_sent')}) this.showNotif({type: 'warning', textColor: 'black', message: this.$t('components.authentication.email_verification.link_sent')})
@@ -136,6 +141,8 @@ export default class Signup extends Vue {
this.showNotif('Errore num ' + riscode) this.showNotif('Errore num ' + riscode)
} }
} }
public submitOk() { public submitOk() {

View File

@@ -39,7 +39,7 @@ export default class Vreg extends Vue {
} }
load() { load() {
console.log('load') // console.log('load')
let param: ILinkReg let param: ILinkReg
param = { idlink: this.$route.query.idlink.toString() } param = { idlink: this.$route.query.idlink.toString() }
console.log('idlink = ', param) console.log('idlink = ', param)

13
workbox-config.js Normal file
View File

@@ -0,0 +1,13 @@
module.exports = {
"globDirectory": "dist/pwa-mat/",
"globPatterns": [
"**/*.{css,woff2,woff,svg,html,js,json,ico}"
// "src/images/*.{jpg,png}"
],
// "swSrc": "dist/pwa-mat/src-sw.js",
"swDest": "dist/pwa-mat/service-worker.js",
"globIgnores": [
"../workbox-config.js",
"help/**"
],
};