Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/notification handling issue #527

Merged
merged 4 commits into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/components/sidebar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -363,4 +363,4 @@ const getIconComponent = (iconName: string) => {
}
};

export default Sidebar;
export default Sidebar;
36 changes: 27 additions & 9 deletions src/config/firebase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,25 @@ const firebaseConfig = {
measurementId: String(process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID),
};

let app;
let app: any;
let messaging: any;

export const initializeFirebase = () => {
if (typeof window !== 'undefined' && !getApps().length) {
app = initializeApp(firebaseConfig);
messaging = typeof window !== 'undefined' ? getMessaging(app) : null;
messaging = getMessaging(app);
console.log('Firebase initialized');
} else {
console.log('Firebase already initialized or running on the server');
}
};

export const requestForToken = async () => {
if (!messaging) {
console.error('Firebase is not initialized. Please initialize Firebase first.');
return null;
}

if (typeof window !== 'undefined' && 'serviceWorker' in navigator) {
try {
const currentToken = await getToken(messaging, {
Expand All @@ -31,21 +39,31 @@ export const requestForToken = async () => {
return currentToken;
} else {
console.log('No registration token available. Request permission to generate one.');
return null;
}
} catch (err) {
console.log('An error occurred while retrieving token:', err);
console.error('An error occurred while retrieving token:', err);
return null;
}
} else {
console.error('Service Worker is not supported in this browser.');
return null;
}
return null;
};

export const onMessageListener = () => {
if (typeof window !== 'undefined') {
return new Promise((resolve) => {
if (!messaging) {
console.error('Firebase is not initialized. Please initialize Firebase first.');
return Promise.reject('Firebase not initialized');
}

return new Promise((resolve) => {
if (typeof window !== 'undefined') {
onMessage(messaging, (payload) => {
resolve(payload);
});
});
}
return Promise.resolve(null);
} else {
resolve(null);
}
});
};
58 changes: 32 additions & 26 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,41 +47,47 @@ const App = ({ Component, pageProps }: AppProps) => {
};

useEffect(() => {
if (!sessionStorage.getItem('sessionId')) {
sessionStorage.setItem('sessionId', uuidv4());
}
const firebaseConfig = encodeURIComponent(
JSON.stringify({
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
})
);
if (isAuthenticated) {

if (!sessionStorage.getItem('sessionId')) {
sessionStorage.setItem('sessionId', uuidv4());
}

initializeFirebase();
getToken();

if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register(`/firebase-messaging-sw.js?firebaseConfig=${firebaseConfig}`)
.then((registration) => {
console.log('Service Worker registered with scope:', registration.scope);
const firebaseConfig = encodeURIComponent(
JSON.stringify({
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
})
.catch((err) => {
console.error('Service Worker registration failed:', err);
});
);

if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register(`/firebase-messaging-sw.js?firebaseConfig=${firebaseConfig}`)
.then((registration) => {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch((err) => {
console.error('Service Worker registration failed:', err);
});
}
}
initializeFirebase();
getToken();
}, []);
}, [isAuthenticated]);

if (typeof window !== 'undefined') {
if (typeof window !== 'undefined') {
window.updateFCMToken = (param: string) => {
console.log('updateFCMToken called');
return 'updateFCMToken called' + param;
// TODO: save this token for this user
};

window.updateNotificationPayload = (stringifiedPayload: string) => {
console.log('updateNotificationPayload called with param', stringifiedPayload);
const payload = JSON.parse(stringifiedPayload);
Expand Down