Push notifications with capacitor runing great

This commit is contained in:
Eudes Inácio
2021-11-05 07:49:01 +01:00
parent 84f2c1cc36
commit 1d58ef0615
12 changed files with 200 additions and 131 deletions
+5
View File
@@ -2162,6 +2162,11 @@
"resolved": "https://registry.npmjs.org/@capacitor/keyboard/-/keyboard-1.1.2.tgz",
"integrity": "sha512-EUduhQzrHma4PlGfdSxVeGIwxR2+/xLRDbjQH5Q4cXqrlYssIX2UyQrL4wNpDaAOg1Z4VD8EzzVolC81LG6Q+A=="
},
"@capacitor/push-notifications": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/@capacitor/push-notifications/-/push-notifications-1.0.7.tgz",
"integrity": "sha512-vbvAptFq5cI6xKYYWMb7tsWvA88/PTG4v6ptxN0Ygtc1fQ4l/AzONQiYqdtFpbBhF2fML2kXQ/5eSAfn8HY9aw=="
},
"@capacitor/status-bar": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@capacitor/status-bar/-/status-bar-1.0.5.tgz",
+1
View File
@@ -36,6 +36,7 @@
"@capacitor/core": "^3.3.0",
"@capacitor/haptics": "^1.1.2",
"@capacitor/keyboard": "^1.1.2",
"@capacitor/push-notifications": "^1.0.7",
"@capacitor/status-bar": "^1.0.5",
"@fortawesome/angular-fontawesome": "^0.9.0",
"@fortawesome/fontawesome-free": "^5.15.3",
+14 -13
View File
@@ -2,8 +2,8 @@
/* tslint:disable */
import { Component, OnInit, NgZone } from '@angular/core';
import { Event } from '../models/event.model';
/* import { NotificationsService } from '../services/notifications.service';
import { WebNotificationsService } from '../services/webnotifications.service'; */
import { NotificationsService } from '../services/notifications.service';
/*import { WebNotificationsService } from '../services/webnotifications.service'; */
import { AlertController, Platform } from '@ionic/angular';
import { Router, ActivatedRoute } from '@angular/router';
import { ToDayEventStorage } from '../store/to-day-event-storage.service';
@@ -14,7 +14,7 @@ import { InativityService } from '../services/inativity.service';
import { SessionStore } from '../store/session.service';
import { StorageService } from '../services/storage.service';
import { File } from '@ionic-native/file/ngx';
import { WebNotificationPopupService } from '../services/notification/web-notification-popup.service';
/* import { WebNotificationPopupService } from '../services/notification/web-notification-popup.service'; */
import { DocumentCounterService } from '../services/worker/document-counter.service';
import { PermissionService } from '../services/worker/permission.service';
import { Network } from '@ionic-native/network/ngx';
@@ -24,7 +24,6 @@ import { Storage } from '@ionic/storage';
import { EventsService } from 'src/app/services/events.service';
import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';
@Component({
selector: 'app-home',
templateUrl: './home.page.html',
@@ -70,7 +69,7 @@ export class HomePage implements OnInit {
private zone: NgZone,
private router: Router,
public modalCtrl: AlertController,
/* private notificationsService: NotificationsService, */
private notificationsService: NotificationsService,
private platform: Platform,
private activeroute: ActivatedRoute,
/* private webnotification: WebNotificationsService, */
@@ -79,14 +78,14 @@ export class HomePage implements OnInit {
private despachoRule: DespachoService,
private inativityService: InativityService,
private storageService: StorageService,
private webNotificationPopupService: WebNotificationPopupService,
/* private webNotificationPopupService: WebNotificationPopupService, */
private backgroundservice: BackgroundService,
private offlinemanager: OfflineManagerService,
private storage: Storage,
private eventservice: EventsService,
private screenOrientation: ScreenOrientation,) {
this.webNotificationPopupService.askNotificationPermission()
/* this.webNotificationPopupService.askNotificationPermission() */
this.router.events.subscribe((val) => {
document.querySelectorAll('ion-modal').forEach((e: any) => e.remove())
@@ -114,6 +113,8 @@ export class HomePage implements OnInit {
ngOnInit() {
this.notificationsService.onReciveForeground();
this.notificationsService.onReciveBackground();
window.addEventListener('online', () => {
console.log('Became online')
@@ -143,12 +144,12 @@ export class HomePage implements OnInit {
updateList() {
/* this.notificationsService.registerCallback(
'despachos',
() => {
this.despachoRule.getList({ updateStore: true })
}
) */
/* this.notificationsService.registerCallback(
'despachos',
() => {
this.despachoRule.getList({ updateStore: true })
}
) */
document.addEventListener('pause', function () {
// console.log('App going to background');
+2 -2
View File
@@ -56,8 +56,8 @@
</div>
<div class="approve-event-detail">
<p *ngIf = "item.Service == 'agenda'">{{item.Location}}</p>
<h3 id="profile-title">{{item.alert}}</h3>
<p *ngIf = "item.Service != 'agenda'">{{item.desc}}</p>
<h3 id="profile-title">{{item.title}}</h3>
<p *ngIf = "item.Service != 'agenda'">{{item.body}}</p>
</div>
<!-- <div class="notification-label-MD-official" *ngIf = "item.Service == 'agenda' && item.TypeAgenda == 'official' && item.Role == '100000011'" ></div>
<div class="notification-label-MD-pessoal" *ngIf = "item.Service == 'agenda' && item.TypeAgenda == 'pessoal' && item.Role == '100000011'" ></div>
+13 -21
View File
@@ -83,31 +83,23 @@ export class ProfilePage implements OnInit {
this.storageservice.get("Notifications").then((value) => {
console.log("Init get store", value)
/* var data = JSON.parse(value); */
console.log("Init store parse", value)
if(typeof(value) == 'string') {
value = JSON.parse(value)
console.log("CSDfdvdf",value)
}
this.DataArray = []
value.forEach((element,i) => {
console.log("ARaaAA", element)
let notificationObject;
notificationObject = {
let notificationObject = {
index: i,
//alert: element.alert,
Service: element.Service,
Object: element.Object,
IdObject: element.IdObject,
FolderId: 1,
//desc: payload.desc,
//dateInit: this.getFormatedTime(payload.dateInit),
//dateEnd: this.getFormatedTime(payload.dateEnd),
//Location: payload.Location,
//TypeAgenda: payload.TypeAgenda,
//Role: payload.Role,
//Status: payload.Status
title: element.title,
Service: element.data.Service,
Object: element.data.Object,
IdObject: element.data.IdObject,
FolderId: element.data.FolderId,
body: element.body,
dateInit: this.getFormatedTime(element.data.dateInit),
dateEnd: this.getFormatedTime(element.data.dateEnd),
Location: element.data.Location,
TypeAgenda: element.data.TypeAgenda,
Role: element.data.Role,
Status: element.data.Status
}
/* if(element.payload){
var payload = JSON.parse(element.payload)
+1 -1
View File
@@ -1,4 +1,4 @@
export class Token {
export class Tokenn {
UserId: number;
TokenId: string;
Status: number;
-6
View File
@@ -121,12 +121,6 @@ export class EventsPage implements OnInit {
ngOnInit() {
try {
this.sqliteservice.databaseConn();
} catch (error) {
console.log("Error creating local database: ", error)
}
this.segment = "Combinada";
this.profile = "mdgpr";
+5 -3
View File
@@ -5,7 +5,7 @@ import { UserForm } from 'src/app/models/user.model';
import { ToastService } from 'src/app/services/toast.service';
import { environment } from 'src/environments/environment';
import { AlertController } from '@ionic/angular';
//import { NotificationsService } from 'src/app/services/notifications.service';
import { NotificationsService } from 'src/app/services/notifications.service';
import { SessionStore } from 'src/app/store/session.service';
@@ -25,7 +25,7 @@ export class InactivityPage implements OnInit {
enterWithPassword = false
constructor(
//private notificatinsservice: NotificationsService,
private notificatinsservice: NotificationsService,
private router: Router,
private authService: AuthService,
private toastService: ToastService,
@@ -141,7 +141,9 @@ export class InactivityPage implements OnInit {
}
getToken() {
//this.notificatinsservice.getAndpostToken(this.username);
this.notificatinsservice.requestPermissions();
this.notificatinsservice.registrationError();
this.notificatinsservice.getAndpostToken(this.username);
}
setCode(code: string) {
+5 -3
View File
@@ -5,7 +5,7 @@ import { UserForm } from 'src/app/models/user.model';
import { ToastService } from 'src/app/services/toast.service';
import { environment } from 'src/environments/environment';
import { AlertController } from '@ionic/angular';
//import { NotificationsService } from 'src/app/services/notifications.service';
import { NotificationsService } from 'src/app/services/notifications.service';
import { SessionStore } from 'src/app/store/session.service';
import { ClearStoreService } from 'src/app/services/clear-store.service';
import { ChangeProfileService } from 'src/app/services/change-profile.service';
@@ -31,7 +31,7 @@ export class LoginPage implements OnInit {
sessionStore = SessionStore
constructor(
//private notificatinsservice: NotificationsService,
private notificatinsservice: NotificationsService,
private router: Router,
private authService: AuthService,
private toastService: ToastService,
@@ -74,7 +74,9 @@ export class LoginPage implements OnInit {
}
getToken() {
//this.notificatinsservice.getAndpostToken(this.username);
this.notificatinsservice.requestPermissions();
this.notificatinsservice.registrationError();
this.notificatinsservice.getAndpostToken(this.username);
}
async Login() {
+129 -81
View File
@@ -6,7 +6,7 @@ import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { StorageService } from 'src/app/services/storage.service';
import { AuthConnstants } from 'src/app/config/auth-constants';
import { Token } from '../models/token.model';
import { Tokenn } from '../models/token.model';
import { ModalController, AlertController, AnimationController, Platform } from '@ionic/angular';
import { NavigationExtras, Router } from '@angular/router';
import { ToastService } from '../services/toast.service';
@@ -14,9 +14,7 @@ import { BackgroundService } from './background.service';
import { v4 as uuidv4 } from 'uuid';
import { EventTrigger } from '../services/eventTrigger.service';
import { SessionStore } from '../store/session.service';
//import { FCM } from '@ionic-native/fcm/ngx';
//import { FCM } from 'cordova-plugin-fcm-with-dependecy-updated/ionic/ngx';
import { ActionPerformed, PushNotificationSchema, PushNotifications, Token, } from '@capacitor/push-notifications';
@Injectable({
providedIn: 'root'
@@ -82,80 +80,130 @@ export class NotificationsService {
getTokenByUserIdAndId(user, userID) {
const geturl = environment.apiURL + 'notifications/user/' + userID;
return this.http.get<Token[]>(`${geturl}`);
return this.http.get<Tokenn[]>(`${geturl}`);
}
/* getAndpostToken(username) {
requestPermissions() {
PushNotifications.requestPermissions().then(result => {
if (result.receive === 'granted') {
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
} else {
// Show some error
}
});
}
getAndpostToken(username) {
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
console.log('Notifications not supported')
} else {
const geturl = environment.apiURL + 'notifications/token';
PushNotifications.addListener('registration',
(token: Token) => {
console.log('token: ', token.value)
this.storageService.store(username, token.value);
this.storageService.get(username).then(value => {
console.log('STORAGE TOKEN', value)
this.storageService.get(AuthConnstants.USER).then(res => {
console.log('USERID', res);
const headers = { 'Authorization': SessionStore.user.BasicAuthKey };
const body = {
UserId: res.UserId,
TokenId: token.value,
Status: 1,
Service: 1
};
return this.fcm.getToken().then(token => {
console.log('token: ', token)
this.storageService.store(username, token);
this.storageService.get(username).then(value => {
console.log('STORAGE TOKEN', value)
this.storageService.get(AuthConnstants.USER).then(res => {
console.log('USERID', res);
const headers = { 'Authorization': SessionStore.user.BasicAuthKey };
const body = {
UserId: res.UserId,
TokenId: token,
Status: 1,
Service: 1
};
this.http.post<Tokenn>(`${geturl}`, body, { headers }).subscribe(data => {
console.log('TOKEN USER MIDLE', data);
}, (error) => {
console.log('Post token to backend', error)
})
});
this.http.post<Token>(`${geturl}`, body, { headers }).subscribe(data => {
console.log('TOKEN USER MIDLE', data);
})
});
});
});
}
);
}
}
async onReceviNotification() {
this.fcm.onNotification().subscribe(data => {
if (data.click_action) {
console.log("Received in background: ", data);
registrationError() {
PushNotifications.addListener('registrationError',
(error: any) => {
console.log('Error on registration: ' + JSON.stringify(error));
}
);
}
this.notificatinsRoutes(data)
} else {
console.log("Received in foreground: ", data);
console.log(data.Service)
console.log(data.Object)
console.log(data.IdObject)
this.DataArray.push(data)
onReciveForeground() {
PushNotifications.addListener('pushNotificationReceived',
(notification: PushNotificationSchema) => {
console.log('Push received: ' + JSON.stringify(notification));
this.DataArray.push(notification)
console.log("On ReceiveNotification", this.DataArray)
this.storageService.store("Notifications", this.DataArray)
this.eventtrigger.publishSomeData({
notification: "recive"
})
}
);
}
onReciveBackground() {
PushNotifications.addListener('pushNotificationActionPerformed',
(notification: ActionPerformed) => {
console.log('Push action performed: ' + JSON.stringify(notification));
this.notificatinsRoutes(notification)
}
);
}
};
});
} */
/*
async onReceviNotification() {
this.fcm.onNotification().subscribe(data => {
if (data.click_action) {
console.log("Received in background: ", data);
this.notificatinsRoutes(data)
} else {
console.log("Received in foreground: ", data);
console.log(data.Service)
console.log(data.Object)
console.log(data.IdObject)
this.DataArray.push(data)
console.log("On ReceiveNotification", this.DataArray)
this.storageService.store("Notifications", this.DataArray)
};
});
} */
/////////////////////////////////////////////////////
/* getTokenByUserIdAndId(user, userID) {
const geturl = environment.apiURL + 'notifications/user/' + userID;
return this.http.get<Token[]>(`${geturl}`);
}
*/
*/
/* getAndpostToken(username) {
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
//console.log('Notifications not supported')
} else {
const geturl = environment.apiURL + 'notifications/token';
if(window['WLAuthorizationManager']) {
if(window['WLAuthorizationManager'].obtainAccessToken) {
@@ -207,17 +255,17 @@ export class NotificationsService {
);
}
}
}
} */
tempClearArray() {
this.DataArray = [];
this.DataArray = new Array;
}
/* async onReceviNotification() {
if(window['WLAuthorizationManager']) {
if(window['WLAuthorizationManager'].obtainAccessToken) {
window['WLAuthorizationManager'].obtainAccessToken("push.mobileclient").then(
@@ -244,7 +292,7 @@ export class NotificationsService {
notification: "recive"
})
var data = JSON.parse(message.payload);
//synchro.$send(data)
console.log('data.Service', data.Service); // module
@@ -264,7 +312,7 @@ export class NotificationsService {
e.funx()
}
})
}
}, (error) => {
console.log('Push notification recived: failure ' + error.responseText);
@@ -273,54 +321,54 @@ export class NotificationsService {
);
}
}
} */
notificatinsRoutes = (data) => {
if (data.Service === "agenda") {
this.zone.run(() => this.router.navigate(['/home/agenda', data.IdObject, 'agenda']));
notificatinsRoutes = (notification) => {
if (notification.data.Service === "agenda") {
this.zone.run(() => this.router.navigate(['/home/agenda', notification.data.IdObject, 'agenda']));
}
else if (data.Service === "gabinete-digital" && data.Object === "expediente") {
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/expediente', data.IdObject, 'gabinete-digital']));
else if (notification.data.Service === "gabinete-digital" && notification.data.Object === "expediente") {
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/expediente', notification.data.IdObject, 'gabinete-digital']));
}
else if (data.Service === "agenda" && data.Object === "event-list") {
this.zone.run(() => this.router.navigate(['/home/agenda/event-list/approve-event', data.IdObject, 'agenda']));
} else if (data.Service === "gabinete-digital" && data.Object === "despachos") {
else if (notification.data.Service === "agenda" && notification.data.Object === "event-list") {
this.zone.run(() => this.router.navigate(['/home/agenda/event-list/approve-event', notification.data.IdObject, 'agenda']));
} else if (notification.data.Service === "gabinete-digital" && notification.data.Object === "despachos") {
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/despachos', data.IdObject, 'gabinete-digital'], { replaceUrl: true }));
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/despachos', notification.data.IdObject, 'gabinete-digital'], { replaceUrl: true }));
}
else if (data.Service === "gabinete-digital" && data.Object === "parecer") {
else if (notification.data.Service === "gabinete-digital" && notification.data.Object === "parecer") {
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/pedidos', data.IdObject, 'gabinete-digital']));
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/pedidos', notification.data.IdObject, 'gabinete-digital']));
}
else if (data.Service === "gabinete-digital" && data.Object === "deferimento") {
else if (notification.data.Service === "gabinete-digital" && notification.data.Object === "deferimento") {
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/pedidos', data.IdObject, 'gabinete-digital']));
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/pedidos', notification.data.IdObject, 'gabinete-digital']));
}
else if (data.Service === "gabinete-digital" && data.Object === "despachos-pr") {
else if (notification.data.Service === "gabinete-digital" && notification.data.Object === "despachos-pr") {
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/despachos-pr', data.IdObject, 'gabinete-digital']));
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/despachos-pr', notification.data.IdObject, 'gabinete-digital']));
}
else if (data.Service === "accoes" && data.Object === "accao") {
this.zone.run(() => this.router.navigate(['/home/publications', data.IdObject]));
else if (notification.data.Service === "accoes" && notification.data.Object === "accao") {
this.zone.run(() => this.router.navigate(['/home/publications', notification.data.IdObject]));
}
else if (data.Service === "accoes" && data.Object === "publicacao") {
this.zone.run(() => this.router.navigate(['/home/publications/view-publications', data.FolderId, data.IdObject]));
else if (notification.data.Service === "accoes" && notification.data.Object === "publicacao") {
this.zone.run(() => this.router.navigate(['/home/publications/view-publications', notification.data.FolderId, notification.data.IdObject]));
}
else if (data.Service === "gabinete-digital" && data.Object === "diplomas") {
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/diplomas', data.IdObject, 'gabinete-digital']));
else if (notification.data.Service === "gabinete-digital" && notification.data.Object === "diplomas") {
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/diplomas', notification.data.IdObject, 'gabinete-digital']));
}
else if (data.Service === "gabinete-digital" && data.Object === "diplomas-assinar") {
else if (notification.data.Service === "gabinete-digital" && notification.data.Object === "diplomas-assinar") {
let navigationExtras: NavigationExtras = {
queryParams: {
"serialNumber": data.IdObject,
"serialNumber": notification.data.IdObject,
}
};
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/diplomas-assinar/diploma-assinar'], navigationExtras));
}
else if (data.Service === "gabinete-digital" && data.Object === "expedientes-pr") {
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/expedientes-pr', data.IdObject, 'gabinete-digital']));
else if (notification.data.Service === "gabinete-digital" && notification.data.Object === "expedientes-pr") {
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/expedientes-pr', notification.data.IdObject, 'gabinete-digital']));
}
}
+1 -1
View File
@@ -3,7 +3,7 @@ import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { StorageService } from 'src/app/services/storage.service';
import { AuthConnstants } from 'src/app/config/auth-constants';
import { Token } from '../models/token.model';
import { Tokenn } from '../models/token.model';
import { ModalController, AlertController, AnimationController, Platform } from '@ionic/angular';
import { NavigationExtras, Router } from '@angular/router';
import { ToastService } from './toast.service';
+24
View File
@@ -69,6 +69,30 @@
<body class='gov'>
<app-root></app-root>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.2.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.2.0/firebase-analytics.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyAAdHmTFznCMerdT99nrewJgISRvtxPqoY",
authDomain: "gabinete-digital-2020.firebaseapp.com",
databaseURL: "https://gabinete-digital-2020.firebaseio.com",
projectId: "gabinete-digital-2020",
storageBucket: "gabinete-digital-2020.appspot.com",
messagingSenderId: "800733765231",
appId: "1:800733765231:web:28e7792ab150006513779a",
measurementId: "G-8QN4BLZ8XK"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
</script>
</body>
</html>