- add: createPushSubscription :

'Subscribed to FreePlanet.app!',
  'You can now receive Notification and Messages.'
This commit is contained in:
Paolo Arena
2019-02-05 18:17:36 +01:00
parent d8e0ff0bc3
commit cb941568e2
11 changed files with 242 additions and 157 deletions

View File

@@ -5,6 +5,8 @@
import { register } from 'register-service-worker'
register(process.env.SERVICE_WORKER_FILE, {
ready() {
console.log('READY::: App is being served from cache by a service worker.')
@@ -12,7 +14,6 @@ register(process.env.SERVICE_WORKER_FILE, {
registered(registration) { // registration -> a ServiceWorkerRegistration instance
console.log('REGISTERED::: !!!', process.env.SERVICE_WORKER_FILE)
},
cached(registration) {
console.log('CACHED::: Content has been cached for offline use.')

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,92 +15,8 @@
</div>
</template>
<script lang="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'
import globalroutines from './globalroutines/index'
@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) {
globalroutines(this, 'loadapp', '')
// this.$router.replace('/')
}
})
}
}
<script lang="ts" src="./App.ts">
</script>
<style>
.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 lang="scss" scoped>
@import './App.scss';
</style>

View File

@@ -1,3 +1,5 @@
import objectId from "./objectId";
console.log('utility.js')
// var dbPromise = idb.open('mydb1', 1, function (db) {
@@ -79,3 +81,5 @@ function dataURItoBlob(dataURI) {
var blob = new Blob([ab], { type: mimeString });
return blob;
}
export default urlBase64ToUint8Array

View File

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

View File

@@ -25,6 +25,8 @@ export default class Home extends Vue {
created() {
// console.log('Home created...')
GlobalStore.actions.prova()
}
mystilecard() {
@@ -37,6 +39,7 @@ export default class Home extends Vue {
get conta() {
return GlobalStore.state.conta
}
set conta(valore) {
GlobalStore.actions.setConta(valore)
let my = this.$q.i18n.lang
@@ -62,7 +65,7 @@ export default class Home extends Vue {
}
getPermission () {
getPermission() {
return Notification.permission
}
@@ -86,37 +89,37 @@ export default class Home extends Vue {
}
navigator.serviceWorker.ready
.then(function(swreg) {
.then(function (swreg) {
swreg.showNotification('Successfully subscribed!', options)
})
}
}
urlBase64ToUint8Array(base64String) {
let padding = '='.repeat((4 - base64String.length % 4) % 4);
let padding = '='.repeat((4 - base64String.length % 4) % 4)
let base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
.replace(/_/g, '/')
let rawData = window.atob(base64);
let outputArray = new Uint8Array(rawData.length);
let rawData = window.atob(base64)
let outputArray = new Uint8Array(rawData.length)
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
outputArray[i] = rawData.charCodeAt(i)
}
return outputArray;
return outputArray
}
dataURItoBlob(dataURI) {
let byteString = atob(dataURI.split(',')[1]);
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);
let ab = new ArrayBuffer(byteString.length)
let ia = new Uint8Array(ab)
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
ia[i] = byteString.charCodeAt(i)
}
let blob = new Blob([ab], { type: mimeString });
return blob;
let blob = new Blob([ab], { type: mimeString })
return blob
}
@@ -141,17 +144,17 @@ export default class Home extends Vue {
}
navigator.serviceWorker.ready
.then(function(swreg) {
swreg.showNotification(mythis.$t('notification.title_subscribed'), options)
.then(function (swreg) {
swreg.showNotification('aaa', options)
})
}
}
askfornotification () {
askfornotification() {
this.showNotification(this.$t('notification.waitingconfirm'), 'positive', 'notifications')
let mythis = this
Notification.requestPermission(function(result) {
Notification.requestPermission(function (result) {
console.log('User Choice', result)
if (result === 'granted') {
mythis.showNotification(mythis.$t('notification.confirmed'), 'positive', 'notifications')
@@ -164,54 +167,6 @@ export default class Home extends Vue {
}
configurePushSub() {
if (!('serviceWorker' in navigator)) {
return
}
console.log('configurePushSub')
let reg
const mythis = this
const mykey = process.env.PUBLICKEY_PUSH
navigator.serviceWorker.ready
.then(function(swreg) {
reg = swreg
return swreg.pushManager.getSubscription()
})
.then(function(sub) {
if (sub === null) {
// Create a new subscription
let convertedVapidPublicKey = mythis.urlBase64ToUint8Array(mykey)
return reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: convertedVapidPublicKey
})
} else {
// We have a subscription
return sub
}
})
.then(function(newSub) {
console.log('Body newSubscription: ', newSub)
return fetch(process.env.MONGODB_HOST + '/subscribe', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(newSub)
})
})
.then(function(res) {
if (res.ok) {
mythis.showNotificationExample()
}
})
.catch(function(err) {
console.log(err)
})
}
test_fetch() {

View File

@@ -4,7 +4,7 @@
<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="configurePushSub" label="Send Push 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">

View File

@@ -1,9 +1,16 @@
import { IGlobalState } from 'model'
import { storeBuilder } from './Store/Store'
import Vue from 'vue'
import urlBase64ToUint8Array from '../../js/utility'
import messages from '../../statics/i18n'
import { UserStore } from "@store"
const state: IGlobalState = {
conta: 0,
isSubscribed: false,
isLoginPage: false,
layoutNeeded: true,
mobileMode: false,
@@ -70,8 +77,109 @@ namespace Actions {
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: t('notification.title_subscribed'),
content: t('notification.subscribed'),
openUrl: '/'
}
let myres = {
options: { ...options },
subs: newSub
}
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 = {
setConta: b.dispatch(setConta)
setConta: b.dispatch(setConta),
createPushSubscription: b.dispatch(createPushSubscription),
loadAfterLogin: b.dispatch(loadAfterLogin),
prova: b.dispatch(prova)
}
}

View File

@@ -496,6 +496,8 @@ namespace Actions {
GlobalStore.mutations.setleftDrawerOpen(localStorage.getItem(rescodes.localStorage.leftDrawerOpen) === 'true')
GlobalStore.mutations.setCategorySel(localStorage.getItem(rescodes.localStorage.categorySel))
GlobalStore.actions.loadAfterLogin()
Todos.actions.dbLoadTodo(true)

View File

@@ -1,6 +1,6 @@
import Vue from 'vue'
import { Component, Prop, Watch } from 'vue-property-decorator'
import { UserStore } from '@store'
import { GlobalStore, UserStore } from '@store'
import { rescodes } from '../../../store/Modules/rescodes'
import { serv_constants } from '../../../store/Modules/serv_constants'
@@ -120,6 +120,8 @@ export default class Signin extends Vue {
if (riscode === rescodes.OK) {
router.push('/signin')
globalroutines(this, 'loadapp', '')
GlobalStore.actions.createPushSubscription()
}
this.checkErrors(riscode)
this.$q.loading.hide()