Website : rimsha.abasa.com
backdoor
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
var
/
www
/
mudeer-web
/
src
/
hooks
/
Filename :
useFCM.ts
back
Copy
import { useState, useEffect } from 'react'; import { setupFCMListener } from '@/lib/firebase'; import { useAuth } from '@/app/Providers/AuthContext'; import Swal from 'sweetalert2'; interface NotificationPayload { notification?: { title: string; body: string; }; data?: { type: string; employeeName: string; employeeRole: string; department: string; loginTime: string; timestamp: string; }; } export const useFCM = () => { const [notification, setNotification] = useState<NotificationPayload | null>(null); const { fcmToken, isFCMRegistered, isAuthenticated } = useAuth(); const shouldListenForNotifications = isAuthenticated && isFCMRegistered; // Listen for foreground messages useEffect(() => { if (!shouldListenForNotifications || !fcmToken) { return; } const handleMessage = (payload: NotificationPayload) => { setNotification(payload); // Play notification sound const audio = new Audio('/notification-sound.mp3'); audio.play().catch(err => console.log('Audio play failed:', err)); // Extract notification title and body from either notification or data payload let title = ''; let body = ''; if (payload.notification) { title = payload.notification.title; body = payload.notification.body; } else if (payload.data) { // Construct notification from data payload title = 'New Login Activity'; body = `${payload.data.employeeName} (${payload.data.employeeRole}) logged in to ${payload.data.department}`; } // Show SweetAlert popup for foreground notification if (title && body) { Swal.fire({ title: title, text: body, icon: 'info', toast: true, position: 'top-end', showConfirmButton: false, timer: 5000, timerProgressBar: true, customClass: { popup: 'colored-toast' } }); // Also show browser notification if permission granted if ('Notification' in window && Notification.permission === 'granted') { new Notification(title, { body: body, icon: '/icon-192x192.png' }); } } }; // ✅ Use the new continuous listener const unsubscribe = setupFCMListener(handleMessage); return () => { if (unsubscribe) unsubscribe(); }; }, [shouldListenForNotifications, fcmToken]); return { fcmToken, notification, clearNotification: () => setNotification(null), isRegistered: isFCMRegistered, }; };