You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.6 KiB
49 lines
1.6 KiB
import { HttpClient, HttpHeaders } from '@angular/common/http';
|
|
import { Injectable } from '@angular/core';
|
|
import { SwPush } from '@angular/service-worker';
|
|
import { environment } from '../../../environment';
|
|
import { CookiesService } from '../cookies/cookies.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 cookiesService: CookiesService) { }
|
|
|
|
enableNotifications() {
|
|
Notification.requestPermission().then(permission => {
|
|
if (permission === 'granted') {
|
|
this.subscribeToNotifications();
|
|
}
|
|
});
|
|
}
|
|
|
|
subscribeToNotifications() {
|
|
this.swPush.requestSubscription({
|
|
serverPublicKey: this.VAPID_PUBLIC_KEY
|
|
}).then(subscription => {
|
|
this.sendSubscriptionToServer(subscription).subscribe();
|
|
}).catch(error => {
|
|
console.error('Subscription to notifications failed:', error);
|
|
});
|
|
}
|
|
|
|
sendSubscriptionToServer(subscription: PushSubscription) {
|
|
const url = `${this.apiURL}/push/subscribe`;
|
|
// 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();
|
|
}
|
|
}
|