@ryuhan/baileys 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -110,9 +110,12 @@ exports.MIN_PREKEY_COUNT = 5;
110
110
  exports.INITIAL_PREKEY_COUNT = 812;
111
111
  exports.UPLOAD_TIMEOUT = 30000;
112
112
  exports.MIN_UPLOAD_INTERVAL = 5000;
113
+ exports.DEFAULT_MAX_MSG_RETRY_COUNT = 5;
114
+ exports.DEFAULT_PHONE_REQUEST_DELAY_MS = 3000;
113
115
  exports.DEFAULT_CACHE_TTLS = {
114
116
  SIGNAL_STORE: 5 * 60,
115
117
  MSG_RETRY: 60 * 60,
116
118
  CALL_OFFER: 5 * 60,
117
- USER_DEVICES: 5 * 60
119
+ USER_DEVICES: 5 * 60,
120
+ IDENTITY_ASSERT: 5 // 5 seconds for debouncing
118
121
  };
@@ -33,6 +33,9 @@ const makeChatsSocket = (config) => {
33
33
  let pendingAppStateSync = false;
34
34
  let awaitingSyncTimeout;
35
35
  const processingMutex = (0, make_mutex_1.makeMutex)();
36
+ const messageMutex = (0, make_mutex_1.makeMutex)();
37
+ const notificationMutex = (0, make_mutex_1.makeMutex)();
38
+ const receiptMutex = (0, make_mutex_1.makeMutex)();
36
39
  const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
37
40
  stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
38
41
  useClones: false
@@ -40,6 +43,15 @@ const makeChatsSocket = (config) => {
40
43
  if (!config.placeholderResendCache) {
41
44
  config.placeholderResendCache = placeholderResendCache;
42
45
  }
46
+ // Initialize message retry manager
47
+ const messageRetryManager = config.messageRetryManager || (0, Utils_1.createMessageRetryManager)({
48
+ maxRetries: config.maxMsgRetryCount || Defaults_1.DEFAULT_MAX_MSG_RETRY_COUNT,
49
+ phoneRequestDelayMs: config.phoneRequestDelayMs || Defaults_1.DEFAULT_PHONE_REQUEST_DELAY_MS,
50
+ logger
51
+ });
52
+ if (!config.messageRetryManager) {
53
+ config.messageRetryManager = messageRetryManager;
54
+ }
43
55
  const getAppStateSyncKey = async (keyId) => {
44
56
  const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
45
57
  return key;
@@ -873,6 +885,10 @@ const makeChatsSocket = (config) => {
873
885
  createCallLink,
874
886
  getBotListV2,
875
887
  processingMutex,
888
+ messageMutex,
889
+ notificationMutex,
890
+ receiptMutex,
891
+ messageRetryManager,
876
892
  fetchPrivacySettings,
877
893
  upsertMessage,
878
894
  appPatch,
@@ -16,9 +16,9 @@ const WABinary_1 = require("../WABinary");
16
16
  const groups_1 = require("./groups");
17
17
  const messages_send_1 = require("./messages-send");
18
18
  const makeMessagesRecvSocket = (config) => {
19
- const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid } = config;
19
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
20
20
  const sock = (0, messages_send_1.makeMessagesSocket)(config);
21
- const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, groupMetadata, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, createParticipantNodes, getUSyncDevices, sendPeerDataOperationMessage, } = sock;
21
+ const { ev, authState, ws, processingMutex, messageMutex, notificationMutex, receiptMutex, signalRepository, query, upsertMessage, resyncAppState, groupMetadata, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, createParticipantNodes, getUSyncDevices, sendPeerDataOperationMessage, messageRetryManager } = sock;
22
22
  /** this mutex ensures that each retryRequest will wait for the previous one to finish */
23
23
  const retryMutex = (0, make_mutex_1.makeMutex)();
24
24
  const msgRetryCache = config.msgRetryCounterCache || new node_cache_1.default({
@@ -33,6 +33,8 @@ const makeMessagesRecvSocket = (config) => {
33
33
  stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
34
34
  useClones: false
35
35
  });
36
+ // Debounce identity-change session refreshes per JID to avoid bursts
37
+ const identityAssertDebounce = config.identityAssertDebounceCache || new node_cache_1.default({ stdTTL: 5, useClones: false });
36
38
  let sendActiveReceipts = false;
37
39
  const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
38
40
  const stanza = {
@@ -142,21 +144,83 @@ const makeMessagesRecvSocket = (config) => {
142
144
  const { fullMessage } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '');
143
145
  const { key: msgKey } = fullMessage;
144
146
  const msgId = msgKey.id;
145
- const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
146
- let retryCount = msgRetryCache.get(key) || 0;
147
- if (retryCount >= maxMsgRetryCount) {
148
- logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
149
- msgRetryCache.del(key);
150
- return;
147
+
148
+ // Use new message retry manager if available
149
+ if (messageRetryManager) {
150
+ // Check if we've exceeded max retries using the new system
151
+ if (messageRetryManager.hasExceededMaxRetries(msgId)) {
152
+ logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing');
153
+ messageRetryManager.markRetryFailed(msgId);
154
+ return;
155
+ }
156
+ // Increment retry count using new system
157
+ const retryCount = messageRetryManager.incrementRetryCount(msgId);
158
+ // Use the new retry count for the rest of the logic
159
+ const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
160
+ await msgRetryCache.set(key, retryCount);
161
+ }
162
+ else {
163
+ // Fallback to old system
164
+ const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
165
+ let retryCount = msgRetryCache.get(key) || 0;
166
+ if (retryCount >= maxMsgRetryCount) {
167
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
168
+ msgRetryCache.del(key);
169
+ return;
170
+ }
171
+ retryCount += 1;
172
+ msgRetryCache.set(key, retryCount);
151
173
  }
152
- retryCount += 1;
153
- msgRetryCache.set(key, retryCount);
174
+
175
+ const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
176
+ const retryCount = (await msgRetryCache.get(key)) || 1;
154
177
  const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
155
- if (retryCount === 1) {
156
- //request a resend via phone
157
- const msgId = await requestPlaceholderResend(msgKey);
158
- logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
178
+ const fromJid = node.attrs.from;
179
+
180
+ // Check if we should recreate session
181
+ let shouldRecreateSession = false;
182
+ let recreateReason = '';
183
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
184
+ try {
185
+ // Check if we have a session with this JID
186
+ const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
187
+ const hasSession = await signalRepository.validateSession(fromJid);
188
+ const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists);
189
+ shouldRecreateSession = result.recreate;
190
+ recreateReason = result.reason;
191
+ if (shouldRecreateSession) {
192
+ logger.debug({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry');
193
+ // Delete existing session to force recreation
194
+ await authState.keys.set({ session: { [sessionId]: null } });
195
+ forceIncludeKeys = true;
196
+ }
197
+ }
198
+ catch (error) {
199
+ logger.warn({ error, fromJid }, 'failed to check session recreation');
200
+ }
159
201
  }
202
+
203
+ // Request phone resend on first retry
204
+ if (retryCount <= 2) {
205
+ if (messageRetryManager) {
206
+ // Schedule phone request with delay (like whatsmeow)
207
+ messageRetryManager.schedulePhoneRequest(msgId, async () => {
208
+ try {
209
+ const requestId = await requestPlaceholderResend(msgKey);
210
+ logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`);
211
+ }
212
+ catch (error) {
213
+ logger.warn({ error, msgId }, 'failed to send scheduled phone request');
214
+ }
215
+ });
216
+ }
217
+ else {
218
+ // Fallback to immediate request
219
+ const msgId = await requestPlaceholderResend(msgKey);
220
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
221
+ }
222
+ }
223
+
160
224
  const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
161
225
  await authState.keys.transaction(async () => {
162
226
  const receipt = {
@@ -173,7 +237,8 @@ const makeMessagesRecvSocket = (config) => {
173
237
  count: retryCount.toString(),
174
238
  id: node.attrs.id,
175
239
  t: node.attrs.t,
176
- v: '1'
240
+ v: '1',
241
+ error: '0' // Add error field like blckrose
177
242
  }
178
243
  },
179
244
  {
@@ -189,7 +254,7 @@ const makeMessagesRecvSocket = (config) => {
189
254
  if (node.attrs.participant) {
190
255
  receipt.attrs.participant = node.attrs.participant;
191
256
  }
192
- if (retryCount > 1 || forceIncludeKeys) {
257
+ if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
193
258
  const { update, preKeys } = await (0, Utils_1.getNextPreKeys)(authState, 1);
194
259
  const [keyId] = Object.keys(preKeys);
195
260
  const key = preKeys[+keyId];
@@ -223,35 +288,46 @@ const makeMessagesRecvSocket = (config) => {
223
288
  }
224
289
  }
225
290
  else {
226
- const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, 'identity');
227
- if (identityNode) {
228
- logger.info({ jid: from }, 'identity changed');
229
- // not handling right now
230
- // signal will override new identity anyway
231
- }
232
- else {
291
+ // Use improved identity change handler with debouncing
292
+ const result = await (0, Utils_1.handleIdentityChange)(node, {
293
+ meId: authState.creds.me === null || authState.creds.me === void 0 ? void 0 : authState.creds.me.id,
294
+ meLid: authState.creds.me === null || authState.creds.me === void 0 ? void 0 : authState.creds.me.lid,
295
+ validateSession: signalRepository.validateSession,
296
+ assertSessions,
297
+ debounceCache: identityAssertDebounce,
298
+ logger
299
+ });
300
+ if (result.action === 'no_identity_node') {
233
301
  logger.info({ node }, 'unknown encrypt notification');
234
302
  }
235
303
  }
236
304
  };
237
- const handleGroupNotification = (participant, child, msg) => {
238
- var _a, _b, _c, _d;
239
- const participantJid = ((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(child, 'participant')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.jid) || participant;
305
+ const handleGroupNotification = (fullNode, child, msg) => {
306
+ // TODO: Support PN/LID (Here is only LID now)
307
+ const actingParticipantLid = fullNode.attrs.participant;
308
+ const actingParticipantPn = fullNode.attrs.participant_pn;
309
+ const affectedParticipantLid = (0, WABinary_1.getBinaryNodeChild)(child, 'participant') === null || (0, WABinary_1.getBinaryNodeChild)(child, 'participant') === void 0 ? void 0 : (0, WABinary_1.getBinaryNodeChild)(child, 'participant').attrs.jid || actingParticipantLid;
310
+ const affectedParticipantPn = (0, WABinary_1.getBinaryNodeChild)(child, 'participant') === null || (0, WABinary_1.getBinaryNodeChild)(child, 'participant') === void 0 ? void 0 : (0, WABinary_1.getBinaryNodeChild)(child, 'participant').attrs.phone_number || actingParticipantPn;
240
311
  switch (child === null || child === void 0 ? void 0 : child.tag) {
241
312
  case 'create':
242
313
  const metadata = (0, groups_1.extractGroupMetadata)(child);
243
314
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
244
315
  msg.messageStubParameters = [metadata.subject];
245
- msg.key = { participant: metadata.owner };
246
- ev.emit('chats.upsert', [{
316
+ msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn };
317
+ ev.emit('chats.upsert', [
318
+ {
247
319
  id: metadata.id,
248
320
  name: metadata.subject,
249
- conversationTimestamp: metadata.creation,
250
- }]);
251
- ev.emit('groups.upsert', [{
321
+ conversationTimestamp: metadata.creation
322
+ }
323
+ ]);
324
+ ev.emit('groups.upsert', [
325
+ {
252
326
  ...metadata,
253
- author: participant
254
- }]);
327
+ author: actingParticipantLid,
328
+ authorPn: actingParticipantPn
329
+ }
330
+ ]);
255
331
  break;
256
332
  case 'ephemeral':
257
333
  case 'not_ephemeral':
@@ -274,22 +350,31 @@ const makeMessagesRecvSocket = (config) => {
274
350
  case 'leave':
275
351
  const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
276
352
  msg.messageStubType = Types_1.WAMessageStubType[stubType];
277
- const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
353
+ const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(({ attrs }) => {
354
+ // TODO: Store LID MAPPINGS
355
+ return {
356
+ id: attrs.jid,
357
+ phoneNumber: (0, WABinary_1.isLidUser)(attrs.jid) && (0, WABinary_1.isPnUser)(attrs.phone_number) ? attrs.phone_number : undefined,
358
+ lid: (0, WABinary_1.isPnUser)(attrs.jid) && (0, WABinary_1.isLidUser)(attrs.lid) ? attrs.lid : undefined,
359
+ admin: (attrs.type || null)
360
+ };
361
+ });
278
362
  if (participants.length === 1 &&
279
363
  // if recv. "remove" message and sender removed themselves
280
364
  // mark as left
281
- (0, WABinary_1.areJidsSameUser)(participants[0], participant) &&
365
+ ((0, WABinary_1.areJidsSameUser)(participants[0].id, actingParticipantLid) ||
366
+ (0, WABinary_1.areJidsSameUser)(participants[0].id, actingParticipantPn)) &&
282
367
  child.tag === 'remove') {
283
368
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
284
369
  }
285
- msg.messageStubParameters = participants;
370
+ msg.messageStubParameters = participants.map(a => JSON.stringify(a));
286
371
  break;
287
372
  case 'subject':
288
373
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
289
374
  msg.messageStubParameters = [child.attrs.subject];
290
375
  break;
291
376
  case 'description':
292
- const description = (_d = (_c = (0, WABinary_1.getBinaryNodeChild)(child, 'body')) === null || _c === void 0 ? void 0 : _c.content) === null || _d === void 0 ? void 0 : _d.toString();
377
+ const description = (0, WABinary_1.getBinaryNodeChild)(child, 'body') === null || (0, WABinary_1.getBinaryNodeChild)(child, 'body') === void 0 ? void 0 : (0, WABinary_1.getBinaryNodeChild)(child, 'body').content.toString();
293
378
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
294
379
  msg.messageStubParameters = description ? [description] : undefined;
295
380
  break;
@@ -323,13 +408,12 @@ const makeMessagesRecvSocket = (config) => {
323
408
  break;
324
409
  case 'created_membership_requests':
325
410
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
326
- msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method];
411
+ msg.messageStubParameters = [affectedParticipantLid, 'created', child.attrs.request_method];
327
412
  break;
328
413
  case 'revoked_membership_requests':
329
- const isDenied = (0, WABinary_1.areJidsSameUser)(participantJid, participant);
414
+ const isDenied = (0, WABinary_1.areJidsSameUser)(affectedParticipantLid, actingParticipantLid);
330
415
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
331
- msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected'];
332
- break;
416
+ msg.messageStubParameters = [affectedParticipantLid, isDenied ? 'revoked' : 'rejected'];
333
417
  break;
334
418
  default:
335
419
  // console.log("RYUHAN-DEBUG:", JSON.stringify({ ...child, content: Buffer.isBuffer(child.content) ? child.content.toString() : child.content, participant }, null, 2))
@@ -406,7 +490,7 @@ const makeMessagesRecvSocket = (config) => {
406
490
  handleMexNewsletterNotification(node.attrs.from, child);
407
491
  break;
408
492
  case 'w:gp2':
409
- handleGroupNotification(node.attrs.participant, child, result);
493
+ handleGroupNotification(node, child, result);
410
494
  break;
411
495
  case 'mediaretry':
412
496
  const event = (0, Utils_1.decodeMediaRetryNode)(node);
@@ -381,17 +381,30 @@ const makeSocket = (config) => {
381
381
  }
382
382
  end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
383
383
  };
384
- const requestPairingCode = async (phoneNumber, pairKey = "RYHANDEV") => {
385
- if (pairKey) {
386
- authState.creds.pairingCode = pairKey.toUpperCase();
384
+ const requestPairingCode = async (phoneNumber, customPairingCode) => {
385
+ // Default pairing code: RYHANDEV (8 characters)
386
+ const _defaultCode = 'RYHANDEV';
387
+ // Validate and set pairing code
388
+ if (customPairingCode) {
389
+ if (customPairingCode.length !== 8) {
390
+ throw new Error('Custom pairing code must be exactly 8 characters');
391
+ }
392
+ authState.creds.pairingCode = customPairingCode.toUpperCase();
393
+ }
394
+ else if (authState.creds.pairingCode && authState.creds.pairingCode.length === 8) {
395
+ // Use existing code if already set and valid
396
+ authState.creds.pairingCode = authState.creds.pairingCode.toUpperCase();
387
397
  }
388
398
  else {
389
- authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
399
+ // Generate random code if no custom code provided
400
+ authState.creds.pairingCode = _defaultCode;
390
401
  }
402
+ // Set me credentials BEFORE emitting creds.update
391
403
  authState.creds.me = {
392
404
  id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
393
405
  name: '~'
394
406
  };
407
+ // Emit creds update so listeners can react
395
408
  ev.emit('creds.update', authState.creds);
396
409
  await sendNode({
397
410
  tag: 'iq',
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.handleIdentityChange = handleIdentityChange;
4
+
5
+ const WABinary_1 = require("../WABinary");
6
+ const generics_1 = require("./generics");
7
+
8
+ async function handleIdentityChange(node, ctx) {
9
+ const from = node.attrs.from;
10
+ if (!from) {
11
+ return { action: 'invalid_notification' };
12
+ }
13
+ const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, 'identity');
14
+ if (!identityNode) {
15
+ return { action: 'no_identity_node' };
16
+ }
17
+ ctx.logger.info({ jid: from }, 'identity changed');
18
+ const decoded = (0, WABinary_1.jidDecode)(from);
19
+ if ((decoded === null || decoded === void 0 ? void 0 : decoded.device) && decoded.device !== 0) {
20
+ ctx.logger.debug({ jid: from, device: decoded.device }, 'ignoring identity change from companion device');
21
+ return { action: 'skipped_companion_device', device: decoded.device };
22
+ }
23
+ const isSelfPrimary = ctx.meId && ((0, WABinary_1.areJidsSameUser)(from, ctx.meId) || (ctx.meLid && (0, WABinary_1.areJidsSameUser)(from, ctx.meLid)));
24
+ if (isSelfPrimary) {
25
+ ctx.logger.info({ jid: from }, 'self primary identity changed');
26
+ return { action: 'skipped_self_primary' };
27
+ }
28
+ if (ctx.debounceCache.get(from)) {
29
+ ctx.logger.debug({ jid: from }, 'skipping identity assert (debounced)');
30
+ return { action: 'debounced' };
31
+ }
32
+ ctx.debounceCache.set(from, true);
33
+ const isOfflineNotification = !(0, generics_1.isStringNullOrEmpty)(node.attrs.offline);
34
+ const hasExistingSession = await ctx.validateSession(from);
35
+ if (!hasExistingSession.exists) {
36
+ ctx.logger.debug({ jid: from }, 'no old session, skipping session refresh');
37
+ return { action: 'skipped_no_session' };
38
+ }
39
+ ctx.logger.debug({ jid: from }, 'old session exists, will refresh session');
40
+ if (isOfflineNotification) {
41
+ ctx.logger.debug({ jid: from }, 'skipping session refresh during offline processing');
42
+ return { action: 'skipped_offline' };
43
+ }
44
+ try {
45
+ await ctx.assertSessions([from], true);
46
+ return { action: 'session_refreshed' };
47
+ }
48
+ catch (error) {
49
+ ctx.logger.warn({ error, jid: from }, 'failed to assert sessions after identity change');
50
+ return { action: 'session_refresh_failed', error };
51
+ }
52
+ }
@@ -32,4 +32,5 @@ __exportStar(require("./link-preview"), exports);
32
32
  __exportStar(require("./event-buffer"), exports);
33
33
  __exportStar(require("./process-message"), exports);
34
34
  __exportStar(require("./message-retry-manager"), exports);
35
+ __exportStar(require("./identity-change-handler"), exports);
35
36
  __exportStar(require("./browser-utils"), exports);
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MessageRetryManager = void 0;
4
+ exports.createMessageRetryManager = createMessageRetryManager;
4
5
 
5
6
  const lru_cache_1 = require("lru-cache");
6
7
 
@@ -10,10 +11,16 @@ const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000;
10
11
 
11
12
  const PHONE_REQUEST_DELAY = 3000;
12
13
 
14
+ function createMessageRetryManager(options) {
15
+ const { logger, maxRetries, phoneRequestDelayMs } = options;
16
+ return new MessageRetryManager(logger, maxRetries, phoneRequestDelayMs);
17
+ }
18
+
13
19
  class MessageRetryManager {
14
- constructor(logger, maxMsgRetryCount) {
20
+ constructor(logger, maxMsgRetryCount, phoneRequestDelayMs = PHONE_REQUEST_DELAY) {
15
21
  this.logger = logger;
16
22
  this.maxMsgRetryCount = maxMsgRetryCount;
23
+ this.phoneRequestDelayMs = phoneRequestDelayMs;
17
24
  this._recentMessagesMap = new lru_cache_1.LRUCache({
18
25
  max: RECENT_MESSAGES_SIZE
19
26
  });
@@ -35,7 +42,6 @@ class MessageRetryManager {
35
42
  sessionRecreations: 0,
36
43
  phoneRequests: 0
37
44
  };
38
- this.maxMsgRetryCount = maxMsgRetryCount;
39
45
  }
40
46
  addRecentMessage(to, id, message) {
41
47
  const key = { to, id };
@@ -51,7 +57,7 @@ class MessageRetryManager {
51
57
  const keyStr = this._keyToString(key);
52
58
  return this._recentMessagesMap.get(keyStr);
53
59
  }
54
- shouldRecreateSession(jid, retryCount, hasSession) {
60
+ shouldRecreateSession(jid, hasSession) {
55
61
  if (!hasSession) {
56
62
  this._sessionRecreateHistory.set(jid, Date.now());
57
63
  this.statistics.sessionRecreations++;
@@ -60,6 +66,7 @@ class MessageRetryManager {
60
66
  recreate: true
61
67
  };
62
68
  }
69
+ const retryCount = this._retryCounters.get(jid) || 0;
63
70
  if (retryCount < 2) {
64
71
  return { reason: '', recreate: false };
65
72
  }
@@ -19,16 +19,24 @@ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
19
19
  Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD
20
20
  ]);
21
21
  /** Cleans a received message to further processing */
22
- const cleanMessage = (message, meId) => {
22
+ const cleanMessage = (message, meId, meLid) => {
23
23
  // ensure remoteJid and participant doesn't have device or agent in it
24
24
  // normalize JIDs but catch errors to avoid throwing on invalid LIDs/JIDs
25
- try {
26
- message.key.remoteJid = (0, WABinary_1.jidNormalizedUser)(message.key.remoteJid);
25
+ if ((0, WABinary_1.isHostedLidUser)(message.key.remoteJid) || (0, WABinary_1.isHostedPnUser)(message.key.remoteJid)) {
26
+ message.key.remoteJid = (0, WABinary_1.jidEncode)((0, WABinary_1.jidDecode)(message.key === null || message.key === void 0 ? void 0 : message.key.remoteJid) === null || (0, WABinary_1.jidDecode)(message.key === null || message.key === void 0 ? void 0 : message.key.remoteJid) === void 0 ? void 0 : (0, WABinary_1.jidDecode)(message.key === null || message.key === void 0 ? void 0 : message.key.remoteJid).user, (0, WABinary_1.isHostedPnUser)(message.key.remoteJid) ? 's.whatsapp.net' : 'lid');
27
27
  }
28
- catch (_e) {
29
- // if normalization fails, retain original remoteJid
28
+ else {
29
+ try {
30
+ message.key.remoteJid = (0, WABinary_1.jidNormalizedUser)(message.key.remoteJid);
31
+ }
32
+ catch (_e) {
33
+ // if normalization fails, retain original remoteJid
34
+ }
35
+ }
36
+ if ((0, WABinary_1.isHostedLidUser)(message.key.participant) || (0, WABinary_1.isHostedPnUser)(message.key.participant)) {
37
+ message.key.participant = (0, WABinary_1.jidEncode)((0, WABinary_1.jidDecode)(message.key.participant) === null || (0, WABinary_1.jidDecode)(message.key.participant) === void 0 ? void 0 : (0, WABinary_1.jidDecode)(message.key.participant).user, (0, WABinary_1.isHostedPnUser)(message.key.participant) ? 's.whatsapp.net' : 'lid');
30
38
  }
31
- if (message.key.participant) {
39
+ else if (message.key.participant) {
32
40
  try {
33
41
  message.key.participant = (0, WABinary_1.jidNormalizedUser)(message.key.participant);
34
42
  }
@@ -51,11 +59,13 @@ const cleanMessage = (message, meId) => {
51
59
  // if the sender believed the message being reacted to is not from them
52
60
  // we've to correct the key to be from them, or some other participant
53
61
  msgKey.fromMe = !msgKey.fromMe
54
- ? (0, WABinary_1.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meId)
62
+ ? (0, WABinary_1.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meId) ||
63
+ (0, WABinary_1.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meLid)
55
64
  // if the message being reacted to, was from them
56
65
  // fromMe automatically becomes false
57
66
  : false;
58
67
  // set the remoteJid to being the same as the chat the message came from
68
+ // TODO: investigate inconsistencies
59
69
  msgKey.remoteJid = message.key.remoteJid;
60
70
  // set participant of the message
61
71
  msgKey.participant = msgKey.participant || message.key.participant;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ryuhan/baileys",
3
- "version": "1.0.3",
4
- "description": "Rimuru Baileys",
3
+ "version": "1.0.4",
4
+ "description": "Rimuru Baileys - Fixed & Enhanced Version",
5
5
  "keywords": [
6
6
  "baileys",
7
7
  "whatsapp",