diff --git a/public/firebase-messaging-sw.js b/public/firebase-messaging-sw.js index 0b5d82416..6d0bd55e6 100644 --- a/public/firebase-messaging-sw.js +++ b/public/firebase-messaging-sw.js @@ -7,41 +7,76 @@ importScripts( "https://www.gstatic.com/firebasejs/10.7.1/firebase-messaging-compat.js", ); -let firebaseConfig = { - apiKey: "AIzaSyDbTFuksgOkIVWDiFe_HG7-BE8X6Dwsg-0", - authDomain: "common-dev-34b09.firebaseapp.com", - databaseURL: "https://common-dev-34b09.firebaseio.com", - projectId: "common-dev-34b09", - storageBucket: "common-dev-34b09.appspot.com", - messagingSenderId: "870639147922", - appId: "1:870639147922:web:9ee954bb1dd52e25cb7f4b", +const ENV = { + LOCAL: "http://localhost:3000", + DEV: "https://web-dev.common.io", + STAGE: "https://web-staging.common.io", + PRODUCTION: "https://common.io", }; -// self.addEventListener("message", (event) => { -// console.log("--INIT_ENV", event); -// if (event.data && event.data.type === "INIT_ENV") { -// firebaseConfig = event.data.env; -// initializeFirebase(); -// } -// }); - -// function initializeFirebase() { -if (firebaseConfig.apiKey) { - console.log("--firebaseConfig", firebaseConfig); - firebase.initializeApp(firebaseConfig); - - const messaging = firebase.messaging(); - - messaging.onBackgroundMessage((payload) => { - console.log("--notif-back", payload); - const notificationTitle = payload.notification.title; - const notificationOptions = { - body: payload.notification.body, - data: payload.data, - icon: "/logo.png", - }; - - self.registration.showNotification(notificationTitle, notificationOptions); - }); +const FIREBASE_CONFIG_ENV = { + DEV: { + apiKey: "AIzaSyDbTFuksgOkIVWDiFe_HG7-BE8X6Dwsg-0", + authDomain: "common-dev-34b09.firebaseapp.com", + databaseURL: "https://common-dev-34b09.firebaseio.com", + projectId: "common-dev-34b09", + storageBucket: "common-dev-34b09.appspot.com", + messagingSenderId: "870639147922", + appId: "1:870639147922:web:9ee954bb1dd52e25cb7f4b", + }, + STAGE: { + apiKey: "AIzaSyBASCWJMV64mZJObeFEitLmdUC1HqmtjJk", + authDomain: "common-staging-1d426.firebaseapp.com", + databaseURL: "https://common-staging-1d426.firebaseio.com", + projectId: "common-staging-1d426", + storageBucket: "common-staging-1d426.appspot.com", + messagingSenderId: "701579202562", + appId: "1:701579202562:web:5729d8a875f98f6709571b", + }, + PRODUCTION: { + apiKey: "AIzaSyAlYrKLd6KNKVkhmNEMKfb0cWHSWicCBOY", + authDomain: "common-production-67641.firebaseapp.com", + databaseURL: "https://common-production-67641.firebaseio.com", + projectId: "common-production-67641", + storageBucket: "common-production-67641.appspot.com", + messagingSenderId: "461029494046", + appId: "1:461029494046:web:4e2e4afbbeb7b487b48d0f", + }, +}; + +let firebaseConfig = {}; + +switch (location.origin) { + case ENV.LOCAL: + case ENV.DEV: { + firebaseConfig = FIREBASE_CONFIG_ENV.DEV; + break; + } + case ENV.STAGE: { + firebaseConfig = FIREBASE_CONFIG_ENV.STAGE; + break; + } + case ENV.PRODUCTION: { + firebaseConfig = FIREBASE_CONFIG_ENV.PRODUCTION; + break; + } + default: { + firebaseConfig = FIREBASE_CONFIG_ENV.DEV; + break; + } } -// } + +firebase.initializeApp(firebaseConfig); + +const messaging = firebase.messaging(); + +messaging.onBackgroundMessage((payload) => { + const notificationTitle = payload.notification.title; + const notificationOptions = { + body: payload.notification.body, + data: payload.data, + icon: "/logo.png", + }; + + self.registration.showNotification(notificationTitle, notificationOptions); +}); diff --git a/src/pages/App/handlers/NotificationsHandler/NotificationsHandler.tsx b/src/pages/App/handlers/NotificationsHandler/NotificationsHandler.tsx index db19bce43..885102c75 100644 --- a/src/pages/App/handlers/NotificationsHandler/NotificationsHandler.tsx +++ b/src/pages/App/handlers/NotificationsHandler/NotificationsHandler.tsx @@ -1,99 +1,46 @@ -import { FC, useEffect } from "react"; +import { FC, useEffect, useState } from "react"; import { useSelector } from "react-redux"; -import firebaseConfig from "@/config"; import { selectUser } from "@/pages/Auth/store/selectors"; import { NotificationService } from "@/services"; const NotificationsHandler: FC = () => { const user = useSelector(selectUser()); const userId = user?.uid; + const [isRegistered, setIsRegistered] = useState(false); - // useEffect(() => { - // NotificationService.requestPermissions(); - // }, []); + useEffect(() => { + if ("serviceWorker" in navigator) { + navigator.serviceWorker + .register("/firebase-messaging-sw-dev.js") + .then((registration) => { + setIsRegistered(true); + return registration; + }) + .catch((err) => { + console.log("ServiceWorker registration failed: ", err); + }); + } + }, []); useEffect(() => { - if (!userId) { + if (!userId && !isRegistered) { return; } let unsubscribeOnMessage; - let unsubscribeLoad; (async () => { const hasPermissions = await NotificationService.requestPermissions(); - console.log("-hasPermissions", hasPermissions); if (hasPermissions) { await NotificationService.saveFCMToken(); unsubscribeOnMessage = NotificationService.onForegroundMessage(); - - if ("serviceWorker" in navigator) { - console.log("--here"); - navigator.serviceWorker - .register("/firebase-messaging-sw.js") - .then((registration) => { - console.log( - "ServiceWorker registration successful with scope: ", - registration.scope, - ); - // registration.active?.postMessage({ - // type: "INIT_ENV", - // env: firebaseConfig.firebase, - // }); - - console.log("---registration", registration); - if (registration.active) { - registration.active.postMessage({ - type: "INIT_ENV", - env: firebaseConfig.firebase, - }); - } else if (registration?.installing) { - registration.installing.addEventListener("statechange", () => { - if (registration?.installing?.state === "activated") { - registration.installing.postMessage({ - type: "INIT_ENV", - env: firebaseConfig.firebase, - }); - } - }); - } else if (registration?.waiting) { - registration.waiting.addEventListener("statechange", () => { - if (registration?.waiting?.state === "activated") { - registration.waiting.postMessage({ - type: "INIT_ENV", - env: firebaseConfig.firebase, - }); - } - }); - } - return registration; - }) - .catch((err) => { - console.log("ServiceWorker registration failed: ", err); - }); - unsubscribeLoad = window.addEventListener("load", () => {}); - } } })(); - // return () => { - // unsubscribeLoad && unsubscribeLoad(); - // unsubscribeOnMessage && unsubscribeOnMessage(); - // }; - }, [userId]); - - // useEffect(() => { - // console.log("--userId", userId, "--isRegistered", isRegistered); - // if (!userId || !isRegistered) { - // return; - // } - - // NotificationService.saveFCMToken(); - - // const unsubscribe = NotificationService.onForegroundMessage(); - - // return unsubscribe; - // }, [userId, isRegistered]); + return () => { + unsubscribeOnMessage && unsubscribeOnMessage(); + }; + }, [userId, isRegistered]); return null; }; diff --git a/src/services/Notification.ts b/src/services/Notification.ts index ad86ad403..25e7597b3 100644 --- a/src/services/Notification.ts +++ b/src/services/Notification.ts @@ -1,7 +1,6 @@ import firebase from "@/shared/utils/firebase"; import firebaseConfig from "@/config"; import Api from "./Api"; -import { NODATA } from "dns"; enum NOTIFICATIONS_PERMISSIONS { DEFAULT = "default", @@ -28,7 +27,6 @@ class NotificationService { } const permission = await Notification.requestPermission(); if (permission === NOTIFICATIONS_PERMISSIONS.GRANTED) { - console.log('Notification permission granted.'); return true; } else { return false; @@ -40,23 +38,15 @@ class NotificationService { public saveFCMToken = async (): Promise => { try { - console.log('-hastPermissions', firebaseConfig.vapidKey); const token = await firebase.messaging().getToken({ vapidKey: firebaseConfig.vapidKey }); if (token) { - try { - console.log("FCM Token:", token); - await Api.post( - this.endpoints.setFCMToken, - { - token, - } - ); - } catch (error) { - console.error("An error occurred while retrieving token. ", error); - } - } else { - console.log("No registration token available. Request permission to generate one."); + await Api.post( + this.endpoints.setFCMToken, + { + token, + } + ); } } catch (error) { console.error("An error occurred while retrieving token. ", error); @@ -64,16 +54,14 @@ class NotificationService { } public onForegroundMessage = () => { - console.log('-subscribe', firebase.messaging().onMessage); const unsubscribe = firebase.messaging().onMessage((payload) => { - console.log('Message received. ', payload); const { title, body } = payload.notification; if (Notification.permission === 'granted') { new Notification(title, { body, data: payload?.data, - icon: '/logo.png', // Replace with your icon + icon: "/logo.png", }); } });