squash all commits and fix service worker (file has to be at this specific path by convention):
Added pwa subscription storage for publishers
This commit is contained in:
@ -1,5 +1,7 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import common from '../src/helpers/common'; // Ensure this path is correct
|
||||
//use session to get user role
|
||||
import { useSession } from "next-auth/react"
|
||||
|
||||
function PwaManager() {
|
||||
const [deferredPrompt, setDeferredPrompt] = useState(null);
|
||||
@ -10,6 +12,8 @@ function PwaManager() {
|
||||
const [registration, setRegistration] = useState(null);
|
||||
const [notificationPermission, setNotificationPermission] = useState(Notification.permission);
|
||||
|
||||
const { data: session } = useSession();
|
||||
|
||||
// Handle PWA installation
|
||||
useEffect(() => {
|
||||
|
||||
@ -54,7 +58,7 @@ function PwaManager() {
|
||||
}, []);
|
||||
|
||||
const installPWA = async (e) => {
|
||||
|
||||
console.log('installing PWA');
|
||||
e.preventDefault();
|
||||
if (deferredPrompt) {
|
||||
deferredPrompt.prompt();
|
||||
@ -66,35 +70,54 @@ function PwaManager() {
|
||||
}
|
||||
};
|
||||
|
||||
// Utility function for converting base64 string to Uint8Array
|
||||
const base64ToUint8Array = base64 => {
|
||||
const padding = '='.repeat((4 - (base64.length % 4)) % 4);
|
||||
const b64 = (base64 + padding).replace(/-/g, '+').replace(/_/g, '/');
|
||||
const rawData = window.atob(b64);
|
||||
const outputArray = new Uint8Array(rawData.length);
|
||||
for (let i = 0; i < rawData.length; ++i) {
|
||||
outputArray[i] = rawData.charCodeAt(i);
|
||||
}
|
||||
return outputArray;
|
||||
};
|
||||
|
||||
const subscribeToNotifications = async (e) => {
|
||||
|
||||
try {
|
||||
e.preventDefault();
|
||||
if (!navigator.serviceWorker) {
|
||||
console.error('Service worker is not supported by this browser.');
|
||||
return;
|
||||
}
|
||||
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
if (!registration) {
|
||||
console.error('Service worker registration not found.');
|
||||
registration
|
||||
return;
|
||||
}
|
||||
|
||||
let vapidPublicKey = process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY;
|
||||
if (!vapidPublicKey) {
|
||||
// Fetch the public key from the server if not present in env variables
|
||||
const response = await fetch('/api/notify', { method: 'GET' });
|
||||
vapidPublicKey = await response.text();
|
||||
if (!vapidPublicKey) {
|
||||
throw new Error("Failed to fetch VAPID public key from server.");
|
||||
}
|
||||
}
|
||||
const sub = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: base64ToUint8Array(process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY)
|
||||
applicationServerKey: common.base64ToUint8Array(vapidPublicKey)
|
||||
});
|
||||
// Call your API to save subscription data on server
|
||||
setSubscription(sub);
|
||||
setIsSubscribed(true);
|
||||
console.log('Web push subscribed!');
|
||||
if (session.user?.id != null) {
|
||||
await fetch(`/api/notify`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ subscription: sub, id: session.user.id })
|
||||
}).then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to save subscription data on server.');
|
||||
}
|
||||
else {
|
||||
console.log('Subscription data saved on server.');
|
||||
setSubscription(sub);
|
||||
setIsSubscribed(true);
|
||||
console.log('Web push subscribed!');
|
||||
}
|
||||
});
|
||||
}
|
||||
console.log(sub);
|
||||
} catch (error) {
|
||||
console.error('Error subscribing to notifications:', error);
|
||||
@ -109,6 +132,24 @@ function PwaManager() {
|
||||
// Call your API to delete or invalidate subscription data on server
|
||||
setSubscription(null);
|
||||
setIsSubscribed(false);
|
||||
if (session?.user?.id != null) {
|
||||
await fetch(`/api/notify`,
|
||||
{
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ id: session?.user.id }),
|
||||
}
|
||||
).then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to delete subscription data on server.');
|
||||
}
|
||||
else {
|
||||
console.log('Subscription data deleted on server.');
|
||||
}
|
||||
});
|
||||
}
|
||||
console.log('Web push unsubscribed!');
|
||||
} catch (error) {
|
||||
console.error('Error unsubscribing from notifications:', error);
|
||||
|
Reference in New Issue
Block a user