feat: implement Firebase Admin SDK push notification logic in server.js with fallback support
This commit is contained in:
@@ -15,6 +15,7 @@
|
|||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"express": "^4.18.2",
|
"express": "^4.18.2",
|
||||||
|
"firebase-admin": "^11.11.1",
|
||||||
"puppeteer": "^21.0.0",
|
"puppeteer": "^21.0.0",
|
||||||
"qrcode": "^1.5.3",
|
"qrcode": "^1.5.3",
|
||||||
"whatsapp-web.js": "^1.26.0",
|
"whatsapp-web.js": "^1.26.0",
|
||||||
|
|||||||
@@ -16,6 +16,72 @@ const app = express();
|
|||||||
const server = http.createServer(app);
|
const server = http.createServer(app);
|
||||||
const wss = new WebSocketServer({ server });
|
const wss = new WebSocketServer({ server });
|
||||||
|
|
||||||
|
// ─── Firebase Admin SDK Configuration (Optional Background Pushes) ─────────
|
||||||
|
const admin = require('firebase-admin');
|
||||||
|
const path = require('path');
|
||||||
|
const fs = require('fs');
|
||||||
|
|
||||||
|
let firebaseApp = null;
|
||||||
|
const serviceAccountPath = path.join(__dirname, 'serviceAccountKey.json');
|
||||||
|
|
||||||
|
if (fs.existsSync(serviceAccountPath)) {
|
||||||
|
try {
|
||||||
|
const serviceAccount = require(serviceAccountPath);
|
||||||
|
firebaseApp = admin.initializeApp({
|
||||||
|
credential: admin.credential.cert(serviceAccount)
|
||||||
|
});
|
||||||
|
console.log('[FCM] Firebase Admin SDK initialized successfully using serviceAccountKey.json');
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[FCM ERROR] Failed to initialize Firebase Admin SDK:', err.message);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.warn('[FCM WARNING] serviceAccountKey.json not found in server directory. Background push notifications will be disabled.');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendPushNotification(chatId, senderName, body) {
|
||||||
|
if (!firebaseApp) {
|
||||||
|
console.log('[FCM] Push skipped: Firebase Admin SDK not initialized.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenPath = path.join(__dirname, 'fcm_token.json');
|
||||||
|
if (!fs.existsSync(tokenPath)) {
|
||||||
|
console.log('[FCM] Push skipped: No registered FCM device token found.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const tokenData = JSON.parse(fs.readFileSync(tokenPath));
|
||||||
|
const token = tokenData.token;
|
||||||
|
if (!token) return;
|
||||||
|
|
||||||
|
const message = {
|
||||||
|
token: token,
|
||||||
|
notification: {
|
||||||
|
title: senderName || 'WhatsApp Message',
|
||||||
|
body: body || 'New Message'
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
chatId: chatId,
|
||||||
|
name: senderName || 'WhatsApp'
|
||||||
|
},
|
||||||
|
apns: {
|
||||||
|
payload: {
|
||||||
|
aps: {
|
||||||
|
sound: 'default',
|
||||||
|
badge: 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await admin.messaging().send(message);
|
||||||
|
console.log('[FCM] Push notification sent successfully, messageId:', response);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[FCM SEND ERROR] Failed to send push notification:', err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ─── State ─────────────────────────────────────────────────────────────────
|
// ─── State ─────────────────────────────────────────────────────────────────
|
||||||
let waClient = null;
|
let waClient = null;
|
||||||
let clientReady = false;
|
let clientReady = false;
|
||||||
@@ -216,6 +282,21 @@ function initWhatsApp() {
|
|||||||
try {
|
try {
|
||||||
const formatted = formatMessage(msg);
|
const formatted = formatMessage(msg);
|
||||||
broadcast({ type: 'new_message', chatId: msg.from, data: formatted });
|
broadcast({ type: 'new_message', chatId: msg.from, data: formatted });
|
||||||
|
|
||||||
|
// Trigger background push notification if not sent by me
|
||||||
|
if (!msg.fromMe) {
|
||||||
|
try {
|
||||||
|
const contact = await msg.getContact();
|
||||||
|
const senderName = contact.name || contact.pushname || msg.from.split('@')[0];
|
||||||
|
let body = msg.body || '';
|
||||||
|
if (!body && msg.hasMedia) {
|
||||||
|
body = '📷 Media/Attachment';
|
||||||
|
}
|
||||||
|
await sendPushNotification(msg.from, senderName, body);
|
||||||
|
} catch (fcmErr) {
|
||||||
|
console.error('[FCM PUSH ERROR] Failed to send background push:', fcmErr.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[WA] Error formatting new message event:', err.message);
|
console.error('[WA] Error formatting new message event:', err.message);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user