From e35296c0a3b96e2a59db9bc0fcf3a2c53e02dda5 Mon Sep 17 00:00:00 2001 From: Bhaskar Date: Mon, 13 Jan 2025 08:19:23 +0530 Subject: [PATCH] multiple fcmIds added --- src/controllers/tanksController.js | 72 +++++++++++++++++++++--------- src/index.js | 21 ++++++--- src/models/User.js | 4 +- 3 files changed, 71 insertions(+), 26 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index aec3e273..0daace6c 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -1569,7 +1569,7 @@ eventEmitter.on('motorStart', async (fcmTokens, timestamp, motorId, waterLevel, // await sendNotification(fcmTokens, 'Motor Started', message); try { // Retrieve the user information - const users = await User.find({ fcmId: { $in: fcmTokens } }); + const users = await User.find({ fcmIds: { $in: fcmTokens } }); console.log("users",users) const userNames = users.map(user => user.username).join(', '); console.log("userNames",userNames) @@ -1592,7 +1592,7 @@ eventEmitter.on('motorStart', async (fcmTokens, timestamp, motorId, waterLevel, eventEmitter.on('motorStop', async (fcmTokens, tankName,stopTime, motorOnType) => { try { // Retrieve the user information - const users = await User.find({ fcmId: { $in: fcmTokens } }); + const users = await User.find({ fcmIds: { $in: fcmTokens } }); console.log("users",users) const userNames = users.map(user => user.username).join(', '); console.log("userNames",userNames) @@ -1687,35 +1687,67 @@ const emitWithTimestamp = (eventName, fcmTokens, motorId, waterLevel) => { }; +// const sendNotification = async (fcmTokens, title, body) => { +// if (!Array.isArray(fcmTokens) || fcmTokens.length === 0) { +// console.error('No FCM tokens provided.'); +// return; +// } + +// for (const token of fcmTokens) { +// const message = { +// token: token, +// notification: { +// title: title, +// body: body, +// }, +// data: { +// target: 'tank_levels', +// }, +// }; + +// try { +// const response = await admin.messaging().send(message); // Send each message individually +// console.log('Notification sent successfully:', response); +// } catch (error) { +// console.error(`Failed to send notification to token ${token}:`, error); +// } +// } +// }; + const sendNotification = async (fcmTokens, title, body) => { if (!Array.isArray(fcmTokens) || fcmTokens.length === 0) { console.error('No FCM tokens provided.'); return; } - for (const token of fcmTokens) { - const message = { - token: token, - notification: { - title: title, - body: body, - }, - data: { - target: 'tank_levels', - }, - }; + const message = { + tokens: fcmTokens, // Send to multiple tokens + notification: { + title: title, + body: body, + }, + data: { + target: 'tank_levels', // Any additional data you want to send + }, + }; - try { - const response = await admin.messaging().send(message); // Send each message individually - console.log('Notification sent successfully:', response); - } catch (error) { - console.error(`Failed to send notification to token ${token}:`, error); + try { + const response = await admin.messaging().sendMulticast(message); // Send all messages at once + console.log('Notification sent successfully:', response); + // Check for failures + if (response.failureCount > 0) { + response.responses.forEach((resp, idx) => { + if (!resp.success) { + console.error(`Failed to send notification to token ${fcmTokens[idx]}:`, resp.error); + } + }); } + } catch (error) { + console.error('Error sending notifications:', error); } }; - // const sendPushNotification = async (registrationToken, title, body) => { // const message = { // notification: { @@ -2062,7 +2094,7 @@ exports.motorAction = async (req, reply) => { // Get user FCM tokens const users = await User.find({ customerId }); - const fcmToken = users.map(user => user.fcmId).filter(fcmId => fcmId); + const fcmToken = users.map(user => user.fcmIds).filter(fcmIds => fcmIds); const receiverTank = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() }); console.log(receiverTank) diff --git a/src/index.js b/src/index.js index f29461b6..8456bc61 100644 --- a/src/index.js +++ b/src/index.js @@ -166,16 +166,21 @@ fastify.post("/api/login", { properties: { phone: { type: "string" }, password: { type: "string" }, - fcmId: { type: "string" }, // Add this line + // fcmId: { type: "string" }, // Add this line + fcmIds: { + type: "array", // Change this to allow an array + items: { type: "string" }, // Each item in the array is a string + default: [], // Default value if not provided + }, deviceId: { type: "string" } // Add this line }, }, }, async handler(req, reply) { // Pass fcmId and deviceId to the loginUser function - const { phone, password, fcmId, deviceId } = req.body; + const { phone, password, fcmIds, deviceId } = req.body; console.log(password,phone) - const loginObject = await userController.loginUser(req, fcmId, deviceId); + const loginObject = await userController.loginUser(req, fcmIds, deviceId); if (loginObject.same) { console.log("entered 1st loop") @@ -187,6 +192,12 @@ fastify.post("/api/login", { typeof oneTimePasswordSetFlag, typeof phoneVerified ); + if (fcmIds && fcmIds.length > 0) { + await User.updateOne( + { customerId: loginObject.user.customerId }, + { $addToSet: { fcmIds: { $each: fcmIds } } } // Add multiple FCM IDs, avoiding duplicates + ); + } if (!phoneVerified) { reply.send({ simplydata: { @@ -366,7 +377,7 @@ console.log(user) phoneVerified: user.phoneVerified, oneTimePasswordSetFlag: user.oneTimePasswordSetFlag, type: user.profile.role, - fcmId: user.fcmId, + fcmIds: user.fcmIds, team: user.team, city: user.city, manager: user.manager, @@ -899,7 +910,7 @@ fastify.post("/api/insatllLogin", { phoneVerified: install.phoneVerified, oneTimePasswordSetFlag: install.oneTimePasswordSetFlag, type: install.profile.role, - fcmId: install.fcmId, + fcmIds: install.fcmIds, team: install.team, city: install.city, manager: install.manager, diff --git a/src/models/User.js b/src/models/User.js index eab08b7a..d8d9c7cc 100644 --- a/src/models/User.js +++ b/src/models/User.js @@ -118,7 +118,9 @@ const userSchema = new mongoose.Schema( latitude: {type: Number,default: 0.0}, isActive: Boolean, tenantId: ObjectId, - fcmId: { type: String, default: null }, + // fcmId: { type: String, default: null }, + fcmIds: [{ type: String }], // Changed to an array of strings + deviceId: { type: String, default: null }, createdAt: { type: Date,