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
//use session to get user role
import { useSession } from "next-auth/react"
import e from 'express';
function PwaManager() {
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 (
<>
<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'}`} >
{isSubscribed ? 'Unsubscribe from Notifications' : 'Subscribe to Notifications'}
</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>
<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'
}`}
>
Send Reminder
Broadcast Reminder
</button>
<button
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'
}`}
>
Send CoverMe
Broadcast CoverMe
</button>
{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] : []);
try {
subscriptions = subscriptions.filter(sub => sub.endpoint !== subscriptionId);
subscriptions = subscriptionId ? subscriptions.filter(sub => sub.endpoint !== subscriptionId) : [];
await prisma.publisher.update({
where: { id },
data: { pushSubscription: subscriptions }
@ -95,13 +94,13 @@ const Notification = async (req, res) => {
if (req.method == 'POST') {//title = "ССС", message = "Ще получите уведомление по този начин.")
const { subscription, id, broadcast, title = 'ССОМ', message = 'Ще получавате уведомления така.', actions } = req.body
if (broadcast) {
await broadcastPush(title, message)
await broadcastPush(title, message, actions)
res.statusCode = 200
res.end()
return
}
else if (id) {
await sendPush(id, title, message)
await sendPush(id, title, message.actions)
res.statusCode = 200
res.end()
return
@ -133,7 +132,7 @@ const Notification = async (req, res) => {
export default Notification
//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 publisher = await prisma.publisher.findUnique({
where: { id }
@ -146,7 +145,7 @@ export const sendPush = async (id, title, message) => {
await webPush
.sendNotification(
publisher.pushSubscription,
JSON.stringify({ title, message })
JSON.stringify({ title, message, actions })
)
.then(response => {
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 const broadcastPush = async (title, message) => {
export const broadcastPush = async (title, message, actions) => {
const prisma = common.getPrismaClient();
const publishers = await prisma.publisher.findMany({
where: { pushSubscription: { not: null } }
})
for (const publisher of publishers) {
await webPush
.sendNotification(
publisher.pushSubscription,
JSON.stringify({ title, message })
if (Array.isArray(publisher.pushSubscription) && publisher.pushSubscription.length) {
for (const subscription of publisher.pushSubscription) {
await webPush.sendNotification(
subscription, // Here subscription is each individual subscription object
JSON.stringify({ title, message, actions })
)
.then(response => {
console.log('Push notification sent to publisher', publisher.id)
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)
})
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);
}
}
}