diff --git a/src/app/services/push/push.service.spec.ts b/src/app/services/push/push.service.spec.ts new file mode 100644 index 0000000..1de8371 --- /dev/null +++ b/src/app/services/push/push.service.spec.ts @@ -0,0 +1,16 @@ +import { TestBed } from '@angular/core/testing'; + +import { PushService } from './services/push/push.service'; + +describe('PushService', () => { + let service: PushService; + + beforeEach(() => { + TestBed.configureTestingModule({}); + service = TestBed.inject(PushService); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); +}); diff --git a/src/app/services/push/push.service.ts b/src/app/services/push/push.service.ts new file mode 100644 index 0000000..e56ea11 --- /dev/null +++ b/src/app/services/push/push.service.ts @@ -0,0 +1,47 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { SwPush } from '@angular/service-worker'; +import { environment } from '../../../environment'; +import { AuthService } from '../auth/auth.service'; + +@Injectable({ + providedIn: 'root' +}) +export class PushService { + readonly VAPID_PUBLIC_KEY = 'BMbmo9BUsveiD6z8_WPVQBCSA3uTbA40t9wgDaYXL9zzobV_GO3yLUux18GOvL1DcIEGpxMlgA-uDr3zOFABLGw'; + + private apiURL = environment.apiURL; + + constructor(private swPush: SwPush, private http: HttpClient, private authService: AuthService) { } + + enableNotifications() { + Notification.requestPermission().then(permission => { + if (permission === 'granted') { + this.subscribeToNotifications(); + } else { + alert("Notifications refusées ou ignorées."); + } + }); + } + + subscribeToNotifications() { + this.swPush.requestSubscription({ + serverPublicKey: this.VAPID_PUBLIC_KEY + }).then(subscription => { + console.log('Subscription successful:', subscription); + this.sendSubscriptionToServer(subscription).subscribe(response => { + console.log('Subscription sent to server:', response); + }); + }).catch(error => { + console.error('Subscription failed:', error); + }); + } + + sendSubscriptionToServer(subscription: PushSubscription) { + const url = `${this.apiURL}/push/subscribe`; + const headers = this.authService.getAuthHeaders(); + headers.set('Content-Type', 'application/json'); + + return this.http.post(url, subscription, { headers }); + } +}