Add push notification and device token management.

This commit is contained in:
Ben Goldsworthy 2020-11-30 17:32:56 +00:00
parent 2daf02af2d
commit 7bed14e238
6 changed files with 74 additions and 30 deletions

View file

@ -1 +1,4 @@
{{ message | async | json }}
<router-outlet></router-outlet>
<div *ngIf="userType === 'customer' && message.value" style="position: fixed; padding:1em; right: 2em; bottom: 2em; background-color: grey;">
{{ message | async | json }}
</div>

View file

@ -1,21 +1,25 @@
import { Component } from '@angular/core';
import { MessagingService } from './service/messaging.service';
import { Observable } from 'rxjs';
@Component({
selector: 'app-root',
template: '<router-outlet></router-outlet>'
templateUrl: './app.component.html',
})
export class AppComponent {
title = 'push-notification';
message;
userType;
constructor(private messagingService: MessagingService) { }
ngOnInit() {
if (localStorage.getItem('usertype') === 'customer') {
this.userType = localStorage.getItem('usertype');
if (this.userType === 'customer') {
this.messagingService.requestPermission();
this.messagingService.receiveMessage();
this.message = this.messagingService.currentMessage;
}
console.log(this.message);
}
}

View file

@ -10,9 +10,9 @@
<div class="card-block">
<div class="form-group row">
<label class="col-md-3 form-control-label" for="select-input"><strong>Select Recipients</strong></label>
<select required class="form-control" type="text" formControlName="devicetokens" multiple>
<option *ngFor="let deviceToken of deviceTokenIdList" [ngValue]="deviceTokenList[deviceToken].token">
{{ deviceTokenList[deviceToken].user }} <{{deviceTokenList[deviceToken].token}}>
<select required class="form-control" type="text" formControlName="topic">
<option *ngFor="let topic of topicIdList" [ngValue]="topicList[topic].name">
{{ topicList[topic].name }} <strong>({{topicList[topic].numberOfSubscribers}} subscribers)</strong>
</option>
</select>
</div>

View file

@ -13,24 +13,23 @@ export class SendPushNotificationComponent implements OnInit {
noEmail = false;
sendMessageFormStatus: any;
sendMessageFormStatusError = 'Error received, please try again.';
deviceTokenList: any;
deviceTokenIdList: any;
topicList: any;
topicIdList: any;
constructor(private api: ApiService) {
this.api.getDeviceTokens().subscribe(
this.api.getTopics().subscribe(
result => {
console.log(result);
this.deviceTokenList = result.tokens;
this.deviceTokenIdList = Object.keys(this.deviceTokenList);
this.topicList = result.topics;
this.topicIdList = Object.keys(this.topicList);
},
error => {
console.log("Couldn't get device token");
console.log("Couldn't get topics");
console.log(error._body);
}
);
this.sendMessageForm = new FormGroup({
messagetext: new FormControl('', Validators.required),
devicetokens: new FormControl('', Validators.required),
topic: new FormControl('', Validators.required),
});
}
@ -58,7 +57,6 @@ export class SendPushNotificationComponent implements OnInit {
}
onSubmit(): void {
console.log(this.sendMessageForm.value);
this.api
.sendMessage(this.sendMessageForm.value)
.subscribe(

View file

@ -108,6 +108,14 @@ export class ApiService {
// Push notifications
public checkDeviceToken(data) {
data.session_key = this.sessionKey;
return this.http.post<any>(
this.apiUrl + '/check-device-token',
data
);
}
public addDeviceToken(data) {
data.session_key = this.sessionKey;
return this.http.post<any>(
@ -124,8 +132,15 @@ export class ApiService {
);
}
public getTopics() {
const key = this.sessionKey;
return this.http.post<any>(
this.apiUrl + '/get-topics',
{ session_key : key }
);
}
public sendMessage(data) {
data.devicetoken = localStorage.getItem('devicetoken');
data.sender = localStorage.getItem('displayname');
return this.http.post<any>(
this.apiUrl + '/send-message',

View file

@ -9,24 +9,48 @@ export class MessagingService {
currentMessage = new BehaviorSubject(null);
constructor(
private angularFireMessaging: AngularFireMessaging,
private readonly angularFireMessaging: AngularFireMessaging,
private api: ApiService
) {
this.angularFireMessaging.messages.subscribe((_messaging: AngularFireMessaging) => {
_messaging.onMessage = _messaging.onMessage.bind(_messaging);
_messaging.onTokenRefresh = _messaging.onTokenRefresh.bind(_messaging);
})
}
) { }
requestPermission() {
if (!('Notification' in window)) {
alert("This browser does not support notifications.");
return;
} else if (Notification.permission === 'granted') {
console.log("Push notification permission granted");
this.registerDeviceToken();
} else if (Notification.permission === 'denied' ||
Notification.permission === 'default') {
console.log("Push notification permission not granted");
Notification.requestPermission().then(function(permission) {
if (permission === 'granted') {
console.log("Push notification permission granted");
this.registerDeviceToken();
}
});
}
}
registerDeviceToken() {
this.angularFireMessaging.requestToken.subscribe((token) => {
this.api.addDeviceToken({'token': token, 'email': localStorage.getItem('email')}).subscribe(
this.api.checkDeviceToken({'token': token}).subscribe(
result => {
console.log("Device registered successfully!");
localStorage.setItem('devicetoken', token);
if (result.exists) console.log("Device already registered!");
else {
this.api.addDeviceToken({'token': token, 'email': localStorage.getItem('email')}).subscribe(
result => {
console.log("Device registered successfully!");
localStorage.setItem('devicetoken', token);
},
error => {
console.error("Device could not be registered!", error._body);
}
);
}
},
error => {
console.error("Device could not be registered!", error._body);
console.error(error._body);
}
);
}, (err) => {
@ -35,9 +59,9 @@ export class MessagingService {
}
receiveMessage() {
this.angularFireMessaging.messages.subscribe((payload) => {
console.log("new message received. ", payload);
this.currentMessage.next(payload);
this.angularFireMessaging.messages.subscribe((message) => {
console.log("show message!", message);
this.currentMessage.next(message);
});
}
}