From 885f98e83ecf817e40e5f3cc67afc52949443e4e Mon Sep 17 00:00:00 2001 From: Dobromir Popov Date: Tue, 7 May 2024 12:14:54 +0300 Subject: [PATCH] delete all if no id sent. proper managment and handling of subs --- components/PwaManager.tsx | 37 +++++++++++++++++++++++++++++++++-- pages/api/notify.ts | 41 ++++++++++++++++++++++----------------- 2 files changed, 58 insertions(+), 20 deletions(-) diff --git a/components/PwaManager.tsx b/components/PwaManager.tsx index 6da931b..549b2e9 100644 --- a/components/PwaManager.tsx +++ b/components/PwaManager.tsx @@ -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): Promise { + 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 ( <>
@@ -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'} +
{notificationPermission !== "granted" && ( diff --git a/pages/api/notify.ts b/pages/api/notify.ts index 44aafce..7f316e3 100644 --- a/pages/api/notify.ts +++ b/pages/api/notify.ts @@ -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 }) - ) - .then(response => { - console.log('Push notification sent to publisher', publisher.id) - }) - .catch(err => { - console.error('Error sending push notification to publisher', publisher.id, ':', err) - }) + 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 device', subscription.endpoint, 'of publisher', publisher.id); + }) + .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); + } } }