diff --git a/dbTools/chat.js b/dbTools/chat.js index f603cfe..2061150 100644 --- a/dbTools/chat.js +++ b/dbTools/chat.js @@ -27,6 +27,13 @@ const chatDB = (DB) => { }; }; + DB.getChatParticipants = async () => { + return DB.chatMessagesCol.distinct("senderProfileId").catch((err) => { + console.log(err); + return []; + }); + }; + DB.getRecentChatMessages = async (limit = 100) => { const safeLimit = Math.min(Math.max(parseInt(limit, 10) || 100, 1), 200); const messages = await DB.chatMessagesCol.find({}) diff --git a/notifications.js b/notifications.js index fdbbdd4..e6e6e70 100644 --- a/notifications.js +++ b/notifications.js @@ -489,6 +489,26 @@ const Notifications = { // sendWebNotification(requesterProfile.webSubscription, notifBody); DB.addNotification(requesterProfile, notifBody, null, null, groupProfile._id); }, + async youGotANewChatMessage(senderProfileId, messageText) { + const DB = await DBGetter.getDB; + const participants = await DB.getChatParticipants(); + const senderProfile = await DB.getProfileCache(senderProfileId); + + const tokens = []; + for (const participantProfileId of participants) { + if (participantProfileId.toString() === senderProfileId.toString()) continue; + + const participantProfile = await DB.getProfileCache(participantProfileId); + if (participantProfile && Array.isArray(participantProfile.token)) { + tokens.push(...participantProfile.token); + } + } + + if (tokens.length > 0) { + const notifBody = `${senderProfile.profile.firstName}: ${messageText.substring(0, 100)}${messageText.length > 100 ? '...' : ''}`; + sendPushNotification(tokens, notifBody, { type: 'chat' }); + } + }, } diff --git a/routes/chat.js b/routes/chat.js index a15097b..ee38d4e 100644 --- a/routes/chat.js +++ b/routes/chat.js @@ -2,6 +2,7 @@ var express = require('express'); var router = express.Router(); const DB = require("../mongoDB.js"); +const Notifications = require("../notifications.js"); const { getUserId, getProfileId } = require("../utils/sessionUtils.js"); const { normalizeLanguageCode, translateText } = require("../utils/chatTranslation.js"); @@ -190,6 +191,8 @@ DB.getDB.then((DB) => { return res.status(500).json({ status: "Could not save message" }); } + Notifications.youGotANewChatMessage(profileId, text); + activeUsers.set(profileId + "", { profileId: profileId + "", userId: userId + "",