import {Injectable, signal} from '@angular/core'; @Injectable({providedIn: 'root'}) export class NotificationService { private readonly notificationSound = new Audio('/public/sounds/notification.mp3'); private readonly notificationStorageKey = 'chat-notifications-enabled'; private readonly _notificationEnabled = signal>( this.getStoredNotificationSettings() ); public notify(server: string) { if (!this.isNotificationEnabled(server)) { return; } this.playSound(); } private enableSound() { this.notificationSound.muted = true; this.notificationSound.play() .then(() => { this.notificationSound.pause(); this.notificationSound.currentTime = 0; this.notificationSound.muted = false; }) .catch((error) => { console.log('Could not unlock notification sound:', error); this.notificationSound.muted = false; }); } private playSound() { this.notificationSound.currentTime = 0; this.notificationSound.play().catch((error) => { console.log('Could not play notification sound:', error); }); } public isNotificationEnabled(server: string): boolean { return this._notificationEnabled()[server]; } public enableNotifications(server: string) { this.setNotificationEnabled(server, true); this.enableSound() } public disableNotifications(server: string) { this.setNotificationEnabled(server, false); } private setNotificationEnabled(server: string, enabled: boolean) { const notificationSettings = { ...this._notificationEnabled(), [server]: enabled }; this._notificationEnabled.set(notificationSettings); localStorage.setItem(this.notificationStorageKey, JSON.stringify(notificationSettings)); } private getStoredNotificationSettings(): Record { const storedSettings = localStorage.getItem(this.notificationStorageKey); if (storedSettings === null) { return {}; } if (storedSettings === 'true' || storedSettings === 'false') { return {}; } try { return JSON.parse(storedSettings) as Record; } catch { return {}; } } }