|
|
|
@ -1,8 +1,8 @@
|
|
|
|
|
import { HttpClient } from '@angular/common/http';
|
|
|
|
|
import { HttpClient, HttpHeaders } 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';
|
|
|
|
|
import { CookiesService } from '../cookies/cookies.service';
|
|
|
|
|
|
|
|
|
|
@Injectable({
|
|
|
|
|
providedIn: 'root'
|
|
|
|
@ -12,14 +12,12 @@ export class PushService {
|
|
|
|
|
|
|
|
|
|
private apiURL = environment.apiURL;
|
|
|
|
|
|
|
|
|
|
constructor(private swPush: SwPush, private http: HttpClient, private authService: AuthService) { }
|
|
|
|
|
constructor(private swPush: SwPush, private http: HttpClient, private cookiesService: CookiesService) { }
|
|
|
|
|
|
|
|
|
|
enableNotifications() {
|
|
|
|
|
Notification.requestPermission().then(permission => {
|
|
|
|
|
if (permission === 'granted') {
|
|
|
|
|
this.subscribeToNotifications();
|
|
|
|
|
} else {
|
|
|
|
|
alert("Notifications refusées ou ignorées.");
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
@ -28,20 +26,23 @@ export class PushService {
|
|
|
|
|
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);
|
|
|
|
|
});
|
|
|
|
|
this.sendSubscriptionToServer(subscription).subscribe();
|
|
|
|
|
}).catch(error => {
|
|
|
|
|
console.error('Subscription failed:', error);
|
|
|
|
|
console.error('Subscription to notifications failed:', error);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
sendSubscriptionToServer(subscription: PushSubscription) {
|
|
|
|
|
const url = `${this.apiURL}/push/subscribe`;
|
|
|
|
|
const headers = this.authService.getAuthHeaders();
|
|
|
|
|
// Obligé de récupérer le token ici car injecter le service dans le constructeur de AuthService provoque une boucle infinie
|
|
|
|
|
const token = this.cookiesService.getToken();
|
|
|
|
|
const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
|
|
|
|
|
headers.set('Content-Type', 'application/json');
|
|
|
|
|
|
|
|
|
|
return this.http.post<any>(url, subscription, { headers });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
unsubscribe(): Promise<void> {
|
|
|
|
|
return this.swPush.unsubscribe();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|