/pushapi: Auto stash before merge of "theslby/pushapi" and "development"

Push Frontend
This commit is contained in:
Unknown 2018-03-06 15:41:13 +00:00
parent 59cbc920c2
commit ff0fe0202f
16 changed files with 528 additions and 44 deletions

View file

@ -1,6 +1,14 @@
// Push Notifications
import { ServiceWorkerModule } from '@angular/service-worker';
import { ConfigService } from './config.service';
import { PushService } from './push.service';
import { PushComponent } from './push/push.component';
import { HttpModule } from '@angular/http';
import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
@ -45,19 +53,22 @@ import { DashboardModule } from './dashboard/dashboard.module';
@NgModule({
imports: [
BrowserAnimationsModule,
BrowserModule,
HttpClientModule,
HttpModule,
NgxPaginationModule,
BsDropdownModule.forRoot(),
TabsModule.forRoot(),
AuthModule,
DashboardModule,
ServiceWorkerModule.register('/ngsw-worker.js', {enabled: environment.production}),
// Loaded last to allow for 404 catchall
AppRoutingModule,
],
declarations: [
ServiceWorkerModule,
AppComponent,
PushComponent,
FullLayoutComponent,
SimpleLayoutComponent,
NAV_DROPDOWN_DIRECTIVES,
@ -68,6 +79,8 @@ import { DashboardModule } from './dashboard/dashboard.module';
P500Component,
],
providers: [
ConfigService,
PushService,
AuthGuard,
OrgGuard,
CustomerGuard,

16
src/app/config.service.ts Normal file
View file

@ -0,0 +1,16 @@
import { Injectable } from '@angular/core';
import { environment } from './../environments/environment';
@Injectable()
export class ConfigService {
private _config:any = environment.config;
constructor() {
}
get(key: any) {
return this._config[key];
}
}

View file

@ -19,9 +19,8 @@
</div>
</li>
</ul>
<push></push>
<app-push>HELLO</app-push>
</header>
<div class="app-body">
<div class="sidebar">
<nav class="sidebar-nav">
@ -117,7 +116,6 @@
</main>
</div>
<footer class="app-footer">
<a href="http://www.peartrade.org" target="_blank">&copy; 2017 Pear Trading Ltd.</a>
<span class="float-right">Powered by <a href="http://coreui.io">CoreUI</a></span>

73
src/app/push.service.ts Normal file
View file

@ -0,0 +1,73 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
import { ConfigService } from './config.service';
@Injectable()
export class PushService {
private API_URL: string
constructor(private http: HttpClient, private configService: ConfigService) {
this.API_URL = this.configService.get('API_URL')
}
// urlBase64ToUint8Array(base64String) {
// const padding = '='.repeat((4 - base64String.length % 4) % 4);
// const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/');
// const rawData = window.atob(base64);
// const outputArray = new Uint8Array(rawData.length);
// for (let i = 0; i < rawData.length; ++i) {
// outputArray[i] = rawData.charCodeAt(i);
// }
// return outputArray;
// }
addSubscriber(subscription) {
const url = `${this.API_URL}/webpush`;
console.log('[Push Service] Adding subscriber')
let body = {
action: 'subscribe',
subscription: subscription
}
return this.http
.post(url, body)
.catch(this.handleError);
}
deleteSubscriber(subscription) {
const url = `${this.API_URL}/webpush`;
console.log('[Push Service] Deleting subscriber')
let body = {
action: 'unsubscribe',
subscription: subscription
}
return this.http
.post(url, body)
.catch(this.handleError);
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
errMsg = `${error.statusText || 'Network error'}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
return Observable.throw(errMsg);
}
}

View file

View file

@ -1,4 +1,3 @@
<push-notification
title="hello"
body="hi">
</push-notification>
<button (click)="subscribeToPush()">Subscribe To Push</button>
<button (click)="unsubscribeFromPush()">Unsubscribe From Push</button>
{{target}}

View file

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { PushComponent } from './push.component';
describe('PushComponent', () => {
let component: PushComponent;
let fixture: ComponentFixture<PushComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ PushComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PushComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View file

@ -1,19 +1,101 @@
import { Component, OnInit} from '@angular/core'
import { PushNotificationComponent } from 'ng2-notifications/ng2-notifications';
import { Component, OnInit } from '@angular/core';
import { ConfigService } from './../config.service';
import { PushService } from './../push.service';
import { SwPush } from '@angular/service-worker';
import "rxjs/Rx";
@Component({
selector: 'push',
selector: 'app-push',
templateUrl: './push.component.html',
styleUrls: ['./push.component.css']
})
export class PushComponent implements OnInit {
})
private VAPID_PUBLIC_KEY: string;
tweets = []
target = ''
export class PushComponent {
constructor(){}
ngOnInit(){
constructor(private pushService: PushService, private configService: ConfigService, private swPush: SwPush) {
}
ngOnInit() {
this.VAPID_PUBLIC_KEY = this.configService.get('VAPID_PUBLIC_KEY')
}
subscribeToPush() {
// Requesting messaging service to subscribe current client (browser)
this.swPush.requestSubscription({
serverPublicKey: this.VAPID_PUBLIC_KEY
})
.then(pushSubscription => {
// Passing subscription object to our backend
console.log(pushSubscription.endpoint)
this.target = JSON.stringify(pushSubscription);
console.log(pushSubscription.getKey)
this.pushService.addSubscriber(pushSubscription)
.subscribe(
res => {
console.log('[App] Add subscriber request answer', res)
},
err => {
console.log('[App] Add subscriber request failed', err)
}
)
})
.catch(err => {
console.error(err);
})
}
showNotification(){
this.swPush.messages.subscribe(message => {
console.log('[App] Push message received', message)
})
}
unsubscribeFromPush(){
// Get active subscription
this.swPush.subscription
.take(1)
.subscribe(pushSubscription => {
console.log('[App] pushSubscription', pushSubscription)
// Delete the subscription from the backend
this.pushService.deleteSubscriber(pushSubscription)
.subscribe(
res => {
console.log('[App] Delete subscriber request answer', res)
// Unsubscribe current client (browser)
pushSubscription.unsubscribe()
.then(success => {
console.log('[App] Unsubscription successful', success)
})
.catch(err => {
console.log('[App] Unsubscription failed', err)
})
},
err => {
console.log('[App] Delete subscription request failed', err)
}
)
})
}
}

View file

@ -4,7 +4,11 @@
// The list of which env maps to which file can be found in `angular-cli.json`.
export const environment = {
production: false,
production: true,
apiUrl: 'https://dev.peartrade.org/api',
mapApiKey: 'CHANGEME',
mapApiKey: 'AIzaSyBhm0iaIGG0Ko5IsfZx-CpLt01YHkp4Y1w',
config: {
"API_URL": "https://pwa-workshop-api.herokuapp.com",
"VAPID_PUBLIC_KEY": "BMDZ6FANqsYRF9iGo3Ki0LdltGZZksgIFbgxBr_otO0H7jTFgcm3v2bGSgnVGJ5bidvLvuKStirfDNl4khVBiok"
}
};

View file

@ -18,7 +18,6 @@
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>
<body class="app header-fixed sidebar-fixed">
<!-- Enable bootstrap 4 theme -->
<script>window.__theme = 'bs4';</script>

31
src/ngsw-config.json Normal file
View file

@ -0,0 +1,31 @@
{
"index": "/index.html",
"assetGroups": [{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html"
],
"versionedFiles": [
"/*.bundle.css",
"/*.bundle.js",
"/*.chunk.js"
]
}
}, {
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**"
]
}
}],
"push": {
"showNotifications": true,
"backgroundOnly": false
}
}

28
src/test.js Normal file
View file

@ -0,0 +1,28 @@
const webpush = require('web-push');
const options = {
vapidDetails: {
subject: 'http://127.0.0.1:8080',
publicKey: 'BMDZ6FANqsYRF9iGo3Ki0LdltGZZksgIFbgxBr_otO0H7jTFgcm3v2bGSgnVGJ5bidvLvuKStirfDNl4khVBiok',
privateKey: 'tZacTzAIA5W-B19SsaQ-4KGWrKPAAqth5HQfJsjyHYs'
},
TTL: 5000
}
// NgPushRegistration-Object from the browser
const pushSubscription = {"endpoint":"https://fcm.googleapis.com/fcm/send/dQn-7TOL3dM:APA91bHLuAR3G-XLxsSsjvo_P5UIEwrPS85Ho-fUZOFMpuuubEFgU6_dfgMZJvgvIOLCpSbRjPc_iWCdjgFz9snS3Rtg5H3H14RDeKt051CQp441PqqXrKHwR5ICpEyLV3x3jcEmGF8Q","expirationTime":null,"keys":{"p256dh":"BBq-RpOiUXSucWCUj8RrFy5jwKRZ6Rv9y7AHYqbE-0vIestbyRt8oxAC2yrbkwuKgPRYAElC32Sbs_Wo2mXNpJU=","auth":"sbIdhYisA6_Kc3_hDYJdog=="}};
const payload = JSON.stringify({
notification: {
title: 'Info',
body: 'Hallo Welt!',
icon: './assets/angular.png',
data: 'additional data'
}
});
webpush.sendNotification(
pushSubscription,
payload,
options
);