| | const webpush = require('web-push'); |
| | const User = require('../models/User'); |
| |
|
| | |
| | webpush.setVapidDetails( |
| | process.env.VAPID_EMAIL, |
| | process.env.VAPID_PUBLIC_KEY, |
| | process.env.VAPID_PRIVATE_KEY |
| | ); |
| |
|
| | |
| | const sendToUser = async (userId, title, message, url = '/') => { |
| | try { |
| | const user = await User.findById(userId); |
| | if (user && user.pushSubscription) { |
| | await webpush.sendNotification( |
| | user.pushSubscription, |
| | JSON.stringify({ title, body: message, url }) |
| | ); |
| | } |
| | } catch (err) { |
| | |
| | if (err.statusCode === 410) { |
| | await User.findByIdAndUpdate(userId, { $unset: { pushSubscription: "" } }); |
| | } |
| | console.error("Push Error (Single):", err.statusCode); |
| | } |
| | }; |
| |
|
| | |
| | const sendGlobal = async (title, message, url = '/') => { |
| | try { |
| | |
| | const users = await User.find({ pushSubscription: { $exists: true } }); |
| | const payload = JSON.stringify({ title, body: message, url }); |
| |
|
| | console.log(`📢 Sending Global Push to ${users.length} devices...`); |
| |
|
| | const promises = users.map(user => |
| | webpush.sendNotification(user.pushSubscription, payload).catch(err => { |
| | if (err.statusCode === 410) { |
| | User.findByIdAndUpdate(user._id, { $unset: { pushSubscription: "" } }); |
| | } |
| | }) |
| | ); |
| |
|
| | await Promise.all(promises); |
| | } catch (err) { |
| | console.error("Push Error (Global):", err); |
| | } |
| | }; |
| |
|
| | module.exports = { sendToUser, sendGlobal }; |
| |
|