diff --git a/src/app/app.component.ts b/src/app/app.component.ts index ac56d3f..f522125 100644 --- a/src/app/app.component.ts +++ b/src/app/app.component.ts @@ -13,16 +13,14 @@ export class AppComponent { constructor(private messagingService: MessagingService) { } - ngOnInit() { - this.userType = localStorage.getItem('usertype'); - if (this.userType === 'customer') { + /** + * Checks for push notification permissions and subscribes to messages. + */ + ngOnInit(): void { + if (localStorage.getItem('usertype') === 'customer') { this.messagingService.requestPermission(); this.messagingService.receiveMessage(); this.message = this.messagingService.currentMessage; - console.log(this.message); - if (this.message.notification) { - console.log('Notification waiting'); - } } } } diff --git a/src/app/dashboard/send-push-notification.component.ts b/src/app/dashboard/send-push-notification.component.ts index f92c2a1..a100710 100644 --- a/src/app/dashboard/send-push-notification.component.ts +++ b/src/app/dashboard/send-push-notification.component.ts @@ -66,19 +66,19 @@ export class SendPushNotificationComponent implements OnInit { .subscribe( result => { if ( result.success === true ) { - console.log('Successful Upload'); + console.debug('Message successfully sent.'); this.sendMessageFormStatus = 'success'; this.sendMessageForm.patchValue({ messagetext: '', }); } else { - console.error('Upload Error'); + console.error('Message send failed (1).'); this.sendMessageFormStatusError = JSON.stringify(result.status) + 'Error, ' + JSON.stringify(result.message); this.sendMessageFormStatus = 'send_failed'; } }, error => { - console.error('Upload Error'); + console.error('Message send failed (0).'); try { this.sendMessageFormStatusError = '"' + error.error.error + '" Error, ' + error.error.message; } catch (e) { diff --git a/src/app/service/messaging.service.ts b/src/app/service/messaging.service.ts index 8b534d7..2f381bd 100644 --- a/src/app/service/messaging.service.ts +++ b/src/app/service/messaging.service.ts @@ -4,7 +4,6 @@ import { AngularFireMessaging } from '@angular/fire/messaging'; import { BehaviorSubject } from 'rxjs'; @Injectable() - export class MessagingService { currentMessage = new BehaviorSubject(null); @@ -13,37 +12,53 @@ export class MessagingService { private api: ApiService ) { } - requestPermission() { + /** + * Requests user consent to send push notifications if this has not been + * granted and has not been previously denied (i.e., it won't spam people). + */ + requestPermission(): void { if (!('Notification' in window)) { - alert('This browser does not support notifications.'); + console.warn('This browser does not support the Notifications API.'); 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(); - } - }); + } + + switch (Notification.permission) { + case 'granted': + console.debug('Push notification permission granted'); + this.registerDeviceToken(); + break; + case 'denied': + console.debug('Push notification permission refused'); + break; + default: + console.debug('Push notification permission not granted'); + Notification.requestPermission().then(function(permission: string) { + if (permission === 'granted') { + console.debug('Push notification permission granted'); + this.registerDeviceToken(); + } + }); } } - registerDeviceToken() { - this.angularFireMessaging.requestToken.subscribe((token) => { + /** + * Request a unique token for a given device and send it to the server to store + * in the database (if it doesn't already exist). + */ + registerDeviceToken(): void { + this.angularFireMessaging.requestToken.subscribe((token: string) => { this.api.checkDeviceToken({'token': token}).subscribe( result => { - if (result.exists) { console.log('Device already registered!'); } else { + if (result.exists) { + console.debug('Device already registered.'); + } else { this.api.addDeviceToken({'token': token, 'email': localStorage.getItem('email')}).subscribe( result => { - console.log('Device registered successfully!'); + console.debug('Device registered successfully.'); localStorage.setItem('devicetoken', token); }, error => { - console.error('Device could not be registered!', error._body); + console.error('Device could not be registered.', error._body); } ); } @@ -53,15 +68,38 @@ export class MessagingService { } ); }, (err) => { - console.error('Unable to get permission to notify.', err); + console.error('Unable to get token.', err); }); } - receiveMessage() { + /** + * Display a newly-received message as a Notification. + */ + receiveMessage(): void { this.angularFireMessaging.messages.subscribe((message) => { - console.log('show message!', message); - const notification = new Notification(message.notification.title, { body: message.notification.body }); + console.debug('Message received:', message); + this.displayNotification(message['notification']); this.currentMessage.next(message); }); } + + /** + * Display a message as a notification (if the Notifications API) is supported, + * or an alert (if not). + * + * @param notification The notification object to display. + */ + displayNotification(notification): void { + if (!('Notification' in window)) { + console.warn('This browser does not support the Notifications API.'); + window.alert(`${notification.title}\n${notification.body}`); + } else { + console.log(window.location.origin); + var options = { + body: notification.body, + icon: window.location.origin + "/assets/img/logo-128.png", + } + const noti = new Notification(notification.title, options); + } + } } diff --git a/src/environments/environment.ts b/src/environments/environment.ts index 14f55a5..fb20ba5 100644 --- a/src/environments/environment.ts +++ b/src/environments/environment.ts @@ -10,13 +10,13 @@ export const environment = { enableAnalytics: false, analyticsKey: 'CHANGEME', firebase: { - apiKey: 'CHANGEME', - authDomain: 'CHANGEME.firebaseapp.com', - databaseURL: 'CHANGEME.firebaseio.com', - projectId: 'CHANGEME', - storageBucket: 'CHANGEME.appspot.com', - messagingSenderId: 'CHANGEME', - appId: 'CHANGEME', - measurementId: 'G-CHANGEME' + apiKey: "AIzaSyB-iIcMH_eyfFT043_8pSGX3YYugpjm3Fg", + authDomain: "localspend-47012.firebaseapp.com", + databaseURL: "https://localspend-47012.firebaseio.com", + projectId: "localspend-47012", + storageBucket: "localspend-47012.appspot.com", + messagingSenderId: "469562689216", + appId: "1:469562689216:web:567a20c57c123f17354f25", + measurementId: "G-KL7BGT2EW0" } }; diff --git a/src/firebase-messaging-sw.js b/src/firebase-messaging-sw.js index 2df74e5..ab70a32 100644 --- a/src/firebase-messaging-sw.js +++ b/src/firebase-messaging-sw.js @@ -1,3 +1,8 @@ +/** + * A Web Worker for sending and receiving messages using the Firebase Cloud + * Messaging (FCM) service. + */ + importScripts('https://www.gstatic.com/firebasejs/8.0.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/8.0.0/firebase-messaging.js');