delete all if no id sent. proper managment and handling of subs

This commit is contained in:
Dobromir Popov
2024-05-07 12:14:54 +03:00
parent d95898005c
commit 885f98e83e
2 changed files with 58 additions and 20 deletions

View File

@ -2,6 +2,7 @@ import React, { useEffect, useState } from 'react';
import common from '../src/helpers/common'; // Ensure this path is correct import common from '../src/helpers/common'; // Ensure this path is correct
//use session to get user role //use session to get user role
import { useSession } from "next-auth/react" import { useSession } from "next-auth/react"
import e from 'express';
function PwaManager() { function PwaManager() {
const [deferredPrompt, setDeferredPrompt] = useState(null); const [deferredPrompt, setDeferredPrompt] = useState(null);
@ -240,6 +241,32 @@ function PwaManager() {
}); });
} }
async function deleteAllSubscriptions(event: MouseEvent<HTMLButtonElement, MouseEvent>): Promise<void> {
event.preventDefault();
await fetch(`/api/notify`,
{
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
//send the current subscription to be removed
body: JSON.stringify({ id: session.user.id })
}
).then(async response => {
if (!response.ok) {
throw new Error('Failed to delete subscription data on server.');
}
else {
console.log('ALL subscriptions data deleted on server.');
if (subscription) {
await subscription.unsubscribe();
}
setSubscription(null);
setIsSubscribed(false);
}
});
}
return ( return (
<> <>
<div> <div>
@ -260,6 +287,12 @@ function PwaManager() {
className={`text-xs py-1 px-2 rounded-full focus:outline-none transition duration-150 ease-in-out ${isSubscribed ? 'bg-red-500 hover:bg-red-700 text-white' : 'bg-green-500 hover:bg-green-700 text-white'}`} > className={`text-xs py-1 px-2 rounded-full focus:outline-none transition duration-150 ease-in-out ${isSubscribed ? 'bg-red-500 hover:bg-red-700 text-white' : 'bg-green-500 hover:bg-green-700 text-white'}`} >
{isSubscribed ? 'Unsubscribe from Notifications' : 'Subscribe to Notifications'} {isSubscribed ? 'Unsubscribe from Notifications' : 'Subscribe to Notifications'}
</button> </button>
<button
onClick={deleteAllSubscriptions}
className="text-xs py-1 px-2 rounded-full focus:outline-none bg-red-500 hover:bg-red-700 text-white"
>
Delete All Subscriptions
</button>
</div > </div >
<div> <div>
<button <button
@ -276,7 +309,7 @@ function PwaManager() {
className={`text-xs py-1 px-2 rounded-full focus:outline-none transition duration-150 ease-in-out ${!isSubscribed ? 'cursor-not-allowed bg-gray-300 text-gray-500' : 'bg-yellow-500 hover:bg-yellow-600 text-white' className={`text-xs py-1 px-2 rounded-full focus:outline-none transition duration-150 ease-in-out ${!isSubscribed ? 'cursor-not-allowed bg-gray-300 text-gray-500' : 'bg-yellow-500 hover:bg-yellow-600 text-white'
}`} }`}
> >
Send Reminder Broadcast Reminder
</button> </button>
<button <button
onClick={sendTestCoverMe} onClick={sendTestCoverMe}
@ -284,7 +317,7 @@ function PwaManager() {
className={`text-xs py-1 px-2 rounded-full focus:outline-none transition duration-150 ease-in-out ${!isSubscribed ? 'cursor-not-allowed bg-gray-300 text-gray-500' : 'bg-yellow-500 hover:bg-yellow-600 text-white' className={`text-xs py-1 px-2 rounded-full focus:outline-none transition duration-150 ease-in-out ${!isSubscribed ? 'cursor-not-allowed bg-gray-300 text-gray-500' : 'bg-yellow-500 hover:bg-yellow-600 text-white'
}`} }`}
> >
Send CoverMe Broadcast CoverMe
</button> </button>
{notificationPermission !== "granted" && ( {notificationPermission !== "granted" && (

View File

@ -71,8 +71,7 @@ const Notification = async (req, res) => {
let subscriptions = Array.isArray(publisher.pushSubscription) ? publisher.pushSubscription : (publisher.pushSubscription ? [publisher.pushSubscription] : []); let subscriptions = Array.isArray(publisher.pushSubscription) ? publisher.pushSubscription : (publisher.pushSubscription ? [publisher.pushSubscription] : []);
try { try {
subscriptions = subscriptions.filter(sub => sub.endpoint !== subscriptionId); subscriptions = subscriptionId ? subscriptions.filter(sub => sub.endpoint !== subscriptionId) : [];
await prisma.publisher.update({ await prisma.publisher.update({
where: { id }, where: { id },
data: { pushSubscription: subscriptions } data: { pushSubscription: subscriptions }
@ -95,13 +94,13 @@ const Notification = async (req, res) => {
if (req.method == 'POST') {//title = "ССС", message = "Ще получите уведомление по този начин.") if (req.method == 'POST') {//title = "ССС", message = "Ще получите уведомление по този начин.")
const { subscription, id, broadcast, title = 'ССОМ', message = 'Ще получавате уведомления така.', actions } = req.body const { subscription, id, broadcast, title = 'ССОМ', message = 'Ще получавате уведомления така.', actions } = req.body
if (broadcast) { if (broadcast) {
await broadcastPush(title, message) await broadcastPush(title, message, actions)
res.statusCode = 200 res.statusCode = 200
res.end() res.end()
return return
} }
else if (id) { else if (id) {
await sendPush(id, title, message) await sendPush(id, title, message.actions)
res.statusCode = 200 res.statusCode = 200
res.end() res.end()
return return
@ -133,7 +132,7 @@ const Notification = async (req, res) => {
export default Notification export default Notification
//export pushNotification(userId or email) for use in other files //export pushNotification(userId or email) for use in other files
export const sendPush = async (id, title, message) => { export const sendPush = async (id, title, message, actions) => {
const prisma = common.getPrismaClient(); const prisma = common.getPrismaClient();
const publisher = await prisma.publisher.findUnique({ const publisher = await prisma.publisher.findUnique({
where: { id } where: { id }
@ -146,7 +145,7 @@ export const sendPush = async (id, title, message) => {
await webPush await webPush
.sendNotification( .sendNotification(
publisher.pushSubscription, publisher.pushSubscription,
JSON.stringify({ title, message }) JSON.stringify({ title, message, actions })
) )
.then(response => { .then(response => {
console.log('Push notification sent to publisher', id) console.log('Push notification sent to publisher', id)
@ -156,23 +155,29 @@ export const sendPush = async (id, title, message) => {
}) })
} }
//export breoadcastNotification for use in other files //export breoadcastNotification for use in other files
export const broadcastPush = async (title, message) => { export const broadcastPush = async (title, message, actions) => {
const prisma = common.getPrismaClient(); const prisma = common.getPrismaClient();
const publishers = await prisma.publisher.findMany({ const publishers = await prisma.publisher.findMany({
where: { pushSubscription: { not: null } } where: { pushSubscription: { not: null } }
}) })
for (const publisher of publishers) { for (const publisher of publishers) {
await webPush if (Array.isArray(publisher.pushSubscription) && publisher.pushSubscription.length) {
.sendNotification( for (const subscription of publisher.pushSubscription) {
publisher.pushSubscription, await webPush.sendNotification(
JSON.stringify({ title, message }) subscription, // Here subscription is each individual subscription object
) JSON.stringify({ title, message, actions })
.then(response => { )
console.log('Push notification sent to publisher', publisher.id) .then(response => {
}) console.log('Push notification sent to device', subscription.endpoint, 'of publisher', publisher.id);
.catch(err => { })
console.error('Error sending push notification to publisher', publisher.id, ':', err) .catch(err => {
}) console.error('Error sending push notification to device', subscription.endpoint, 'of publisher', publisher.id, ':', err);
// Optionally handle failed subscriptions, e.g., remove outdated or invalid subscriptions
});
}
} else {
console.log('No valid subscriptions found for publisher', publisher.id);
}
} }
} }