-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsocketManager.js
More file actions
310 lines (283 loc) · 11.8 KB
/
Copy pathsocketManager.js
File metadata and controls
310 lines (283 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
const { DisconnectReason, fetchLatestBaileysVersion } = require('@whiskeysockets/baileys');
const makeWASocket = require('@whiskeysockets/baileys').default;
const useMongoDBAuthState = require('./mongoAuthState');
const qrcode = require('qrcode-terminal');
const { connectToDB } = require('./db');
const { wireSocketLogging, appLogger } = require('./logger');
const MediaHandler = require('./mediaHandler');
const socketLog = appLogger('socket');
class SocketManager {
constructor() {
this.sockets = new Map(); // accountId -> { socket, status, qr, collection, etc. }
this.db = null;
this.mediaHandler = null;
// Browser configurations for user agent rotation
this.browserConfigs = [
['Chrome', '107.0.5304.87', 'Windows 10'],
['Chrome', '107.0.5304.87', 'Windows 11'],
['Chrome', '119.0.6045.105', 'Mac OS'],
['Chrome', '119.0.6045.105', 'Linux'],
['Firefox', '119.0', 'Windows 10'],
['Firefox', '119.0', 'Mac OS'],
['Safari', '17.0', 'Mac OS'],
['Edge', '119.0.2151.44', 'Windows 11'],
['Safari', '14.4.1', 'Mac OS'],
['Safari', '14.4.1', 'iOS'],
];
}
_getRandomBrowser() {
return this.browserConfigs[Math.floor(Math.random() * this.browserConfigs.length)];
}
async init() {
this.db = await connectToDB();
this.mediaHandler = new MediaHandler(this.db);
}
async createSocket(accountId, collectionName) {
const collName = collectionName || `auth_${accountId}`;
const existing = this.sockets.get(accountId);
if (existing && existing.status !== 'reconnecting' && existing.status !== 'logged_out') {
return existing;
}
// Remove old socket if reconnecting or logged out
if (existing) {
try { await existing.socket.logout(); } catch {}
this.sockets.delete(accountId);
}
const collection = this.db.collection(collName);
const { state, saveCreds } = await useMongoDBAuthState(collection);
// Use WhatsApp Web version that resolves "Connection Failure" (issue #2370)
// This version is confirmed to work with WhatsApp's current servers
const { version, isLatest } = await fetchLatestBaileysVersion().catch(() => ({ version: [2, 3000, 1033893291], isLatest: false }));
const browser = this._getRandomBrowser();
socketLog.info('socket_creating', { accountId, browser, waVersion: version.join('.'), isLatest });
const sock = makeWASocket({
version,
auth: state,
syncFullHistory: true,
browser,
});
wireSocketLogging(sock);
const socketInfo = {
socket: sock,
status: 'connecting',
qr: null,
lastDisconnect: null,
collection: collName,
};
this.sockets.set(accountId, socketInfo);
// Connection lifecycle
sock.ev.on('connection.update', async (update = {}) => {
const { connection, lastDisconnect, qr } = update;
if (connection) socketInfo.status = connection;
socketInfo.lastDisconnect = lastDisconnect;
socketInfo.qr = qr;
const accountsCol = this.db.collection('accounts');
if (qr) {
// Keep terminal friendly QR while also structured log
console.log(`\n=== QR Code for account: ${accountId} ===`);
qrcode.generate(qr, { small: true });
console.log('=== Scan with WhatsApp to connect ===\n');
socketLog.info('qr_generated', { accountId });
}
if (connection === 'close') {
const loggedOut = lastDisconnect?.error?.output?.statusCode === DisconnectReason.loggedOut;
if (!loggedOut) {
socketInfo.status = 'reconnecting';
socketLog.info('reconnecting_account', { accountId, delaySeconds: 5 });
try {
const res1 = await accountsCol.updateOne({ _id: { $eq: accountId } }, { $set: { status: 'reconnecting', updatedAt: new Date() } });
socketLog.info('account_status_updated', { accountId, status: 'reconnecting', modifiedCount: res1.modifiedCount });
} catch (err) {
socketLog.error('account_status_update_failed', { accountId, status: 'reconnecting', error: err && err.message });
}
setTimeout(() => this.createSocket(accountId, collName), 5000);
} else {
socketInfo.status = 'logged_out';
socketLog.info('account_logged_out', { accountId });
try {
const res2 = await accountsCol.updateOne({ _id: { $eq: accountId } }, { $set: { status: 'logged_out', updatedAt: new Date() } });
socketLog.info('account_status_updated', { accountId, status: 'logged_out', modifiedCount: res2.modifiedCount });
} catch (err) {
socketLog.error('account_status_update_failed', { accountId, status: 'logged_out', error: err && err.message });
}
}
} else if (connection === 'open') {
socketInfo.status = 'connected';
socketLog.info('account_connected', { accountId });
try {
const res3 = await accountsCol.updateOne({ _id: { $eq: accountId } }, { $set: { status: 'connected', updatedAt: new Date() } });
socketLog.info('account_status_updated', { accountId, status: 'connected', modifiedCount: res3.modifiedCount });
} catch (err) {
socketLog.error('account_status_update_failed', { accountId, status: 'connected', error: err && err.message });
}
if (process.env.ADMIN_NUMBER) {
try {
await sock.sendMessage(process.env.ADMIN_NUMBER, { text: `\u2705 Account ${accountId} connected successfully!` });
} catch (notifyErr) {
socketLog.error('admin_notify_failed', { accountId, error: notifyErr.message });
}
}
} else if (connection === 'connecting') {
try {
const res4 = await accountsCol.updateOne({ _id: { $eq: accountId } }, { $set: { status: 'connecting', updatedAt: new Date() } });
socketLog.info('account_status_updated', { accountId, status: 'connecting', modifiedCount: res4.modifiedCount });
} catch (err) {
socketLog.error('account_status_update_failed', { accountId, status: 'connecting', error: err && err.message });
}
}
});
sock.ev.on('creds.update', saveCreds);
// Per-account message handling
sock.ev.on('messages.upsert', async (messageInfoUpsert) => {
if (messageInfoUpsert.type !== 'notify') return;
const messages = messageInfoUpsert.messages || [];
const messagesCollection = this.db.collection('messages');
for (const msg of messages) {
try {
const textContent = this._extractTextContent(msg);
const hasMedia = this.mediaHandler.hasMedia(msg);
let mediaInfo = null;
if (hasMedia) {
try {
mediaInfo = await this.mediaHandler.downloadAndStoreMedia(
msg,
accountId,
sock.updateMediaMessage,
);
socketLog.info('media_stored', { accountId, messageId: msg.key.id, mediaType: mediaInfo.mediaType });
} catch (err) {
socketLog.error('media_download_failed', { accountId, messageId: msg.key.id, error: err.message });
}
}
const quotedMessage = this.mediaHandler.extractQuotedMessage(msg);
const mentions = this.mediaHandler.extractMentions(msg);
const messageDoc = {
accountId,
messageId: msg.key.id,
chatId: msg.key.remoteJid,
from: msg.key.remoteJid,
fromMe: msg.key.fromMe,
timestamp: msg.messageTimestamp,
type: mediaInfo ? mediaInfo.mediaType : 'text',
text: textContent,
hasMedia,
...(mediaInfo && {
mediaType: mediaInfo.mediaType,
mediaGridFsId: mediaInfo.gridFsId.toString(),
mediaUrl: this.mediaHandler.getMediaUrl(accountId, msg.key.id),
mediaSize: mediaInfo.size,
mediaMimetype: mediaInfo.mimetype,
mediaFileName: mediaInfo.fileName,
caption: mediaInfo.caption,
mediaWidth: mediaInfo.width,
mediaHeight: mediaInfo.height,
}),
quotedMessage,
mentions,
isForwarded: msg.message?.extendedTextMessage?.contextInfo?.isForwarded || false,
rawMessage: msg,
createdAt: new Date(),
updatedAt: new Date(),
};
await messagesCollection.insertOne(messageDoc);
// Webhooks
const { sendToWebhook } = require('./webhookHandler');
const webhooksCollection = this.db.collection('webhooks');
const webhooks = await webhooksCollection.find({}).toArray();
const webhookPayload = {
accountId,
messageId: msg.key.id,
chatId: msg.key.remoteJid,
from: msg.key.remoteJid,
fromMe: msg.key.fromMe,
timestamp: msg.messageTimestamp,
type: messageDoc.type,
text: textContent,
hasMedia,
mediaUrl: mediaInfo ? messageDoc.mediaUrl : null,
mediaType: mediaInfo ? mediaInfo.mediaType : null,
quotedMessage,
mentions,
createdAt: messageDoc.createdAt,
};
for (const webhook of webhooks) {
const result = await sendToWebhook(webhook.url, webhookPayload);
if (!result.ok) {
let redactedUrl = '<redacted>';
try {
const parsed = new URL(webhook.url);
redactedUrl = `${parsed.protocol}//${parsed.hostname}${parsed.port ? ':' + parsed.port : ''}${parsed.pathname}`;
} catch {}
socketLog.error('webhook_send_failed', { accountId, webhook: redactedUrl, error: result.error });
}
}
} catch (err) {
socketLog.error('message_processing_error', { accountId, messageId: msg.key?.id, error: err.message });
}
}
});
return socketInfo;
}
getSocket(accountId) {
return this.sockets.get(accountId);
}
getAllSockets() {
return Array.from(this.sockets.entries()).map(([id, info]) => ({
id,
status: info.status,
qr: info.qr,
collection: info.collection,
}));
}
async removeSocket(accountId) {
const info = this.sockets.get(accountId);
if (info) {
try {
await info.socket.logout();
} catch (e) {
socketLog.error('logout_error', { accountId, error: e.message });
}
this.sockets.delete(accountId);
}
}
async deleteAccountData(accountId) {
const info = this.sockets.get(accountId);
if (info) {
await this.db.collection(info.collection).drop();
}
}
async requestPairingCode(accountId, phoneNumber) {
const socketInfo = this.sockets.get(accountId);
if (!socketInfo) {
const err = new Error('Account not found');
err.code = 'account_not_found';
throw err;
}
if (socketInfo.status !== 'connecting') {
const err = new Error('Socket not ready for pairing');
err.code = 'socket_not_ready';
err.status = socketInfo.status;
throw err;
}
if (!/^\d{10,15}$/.test(phoneNumber)) {
const err = new Error('Invalid phone number format');
err.code = 'invalid_phone_number';
throw err;
}
const code = await socketInfo.socket.requestPairingCode(phoneNumber);
socketLog.info('pairing_code_requested', { accountId });
return code;
}
// Extract text content from Baileys message
_extractTextContent(message) {
const msg = message.message;
if (!msg) return null;
if (msg.conversation) return msg.conversation;
if (msg.extendedTextMessage?.text) return msg.extendedTextMessage.text;
if (msg.imageMessage?.caption) return msg.imageMessage.caption;
if (msg.videoMessage?.caption) return msg.videoMessage.caption;
if (msg.documentMessage?.caption) return msg.documentMessage.caption;
return null;
}
}
module.exports = SocketManager;