@jkt48connect-corp/baileys 7.3.0 → 7.3.2

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.
Files changed (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1119 -1407
  3. package/lib/Defaults/baileys-version.json +1 -1
  4. package/lib/Defaults/index.d.ts +7 -9
  5. package/lib/Defaults/index.js +4 -6
  6. package/lib/Socket/Client/index.d.ts +3 -2
  7. package/lib/Socket/Client/index.js +3 -2
  8. package/lib/Socket/Client/{websocket.d.ts → web-socket-client.d.ts} +1 -1
  9. package/lib/Socket/Client/{websocket.js → web-socket-client.js} +2 -2
  10. package/lib/Socket/business.d.ts +3 -8
  11. package/lib/Socket/chats.d.ts +19 -21
  12. package/lib/Socket/chats.js +48 -51
  13. package/lib/Socket/groups.d.ts +26 -28
  14. package/lib/Socket/groups.js +1 -2
  15. package/lib/Socket/index.d.ts +3 -6
  16. package/lib/Socket/messages-recv.d.ts +3 -8
  17. package/lib/Socket/messages-recv.js +149 -308
  18. package/lib/Socket/messages-send.d.ts +26 -23
  19. package/lib/Socket/messages-send.js +166 -193
  20. package/lib/Socket/newsletter.d.ts +2 -2
  21. package/lib/Socket/newsletter.js +3 -3
  22. package/lib/Socket/registration.d.ts +3 -8
  23. package/lib/Socket/socket.d.ts +6 -8
  24. package/lib/Socket/socket.js +14 -19
  25. package/lib/Store/make-cache-manager-store.d.ts +2 -2
  26. package/lib/Store/make-ordered-dictionary.d.ts +1 -1
  27. package/lib/Types/Call.d.ts +1 -1
  28. package/lib/Types/Chat.d.ts +7 -12
  29. package/lib/Types/Events.d.ts +2 -17
  30. package/lib/Types/GroupMetadata.d.ts +1 -3
  31. package/lib/Types/Label.d.ts +0 -11
  32. package/lib/Types/Message.d.ts +328 -324
  33. package/lib/Types/Socket.d.ts +0 -7
  34. package/lib/Types/index.d.ts +0 -9
  35. package/lib/Utils/chat-utils.d.ts +4 -4
  36. package/lib/Utils/chat-utils.js +20 -41
  37. package/lib/Utils/crypto.d.ts +1 -1
  38. package/lib/Utils/crypto.js +2 -4
  39. package/lib/Utils/decode-wa-message.d.ts +0 -17
  40. package/lib/Utils/decode-wa-message.js +14 -42
  41. package/lib/Utils/generics.d.ts +10 -4
  42. package/lib/Utils/generics.js +14 -30
  43. package/lib/Utils/history.d.ts +2 -6
  44. package/lib/Utils/history.js +0 -3
  45. package/lib/Utils/messages.d.ts +1 -0
  46. package/lib/Utils/messages.js +41 -249
  47. package/lib/Utils/signal.d.ts +1 -2
  48. package/lib/Utils/signal.js +19 -11
  49. package/lib/Utils/use-multi-file-auth-state.js +3 -11
  50. package/lib/Utils/validate-connection.d.ts +2 -2
  51. package/lib/Utils/validate-connection.js +1 -1
  52. package/lib/WABinary/encode.d.ts +1 -1
  53. package/lib/WABinary/encode.js +10 -16
  54. package/lib/index.d.ts +11 -0
  55. package/lib/index.js +0 -1
  56. package/lib/index.ts +13 -0
  57. package/package.json +15 -27
  58. package/lib/Socket/Client/types.d.ts +0 -17
  59. package/lib/Socket/Client/types.js +0 -13
  60. package/lib/Socket/usync.d.ts +0 -37
  61. package/lib/Socket/usync.js +0 -70
  62. package/lib/Types/USync.d.ts +0 -25
  63. package/lib/Types/USync.js +0 -2
  64. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  65. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -32
  66. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  67. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -57
  68. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  69. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -30
  70. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  71. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -42
  72. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  73. package/lib/WAUSync/Protocols/index.js +0 -20
  74. package/lib/WAUSync/USyncQuery.d.ts +0 -26
  75. package/lib/WAUSync/USyncQuery.js +0 -79
  76. package/lib/WAUSync/USyncUser.d.ts +0 -10
  77. package/lib/WAUSync/USyncUser.js +0 -22
  78. package/lib/WAUSync/index.d.ts +0 -3
  79. package/lib/WAUSync/index.js +0 -19
@@ -19,7 +19,7 @@ const messages_send_1 = require("./messages-send");
19
19
  const makeMessagesRecvSocket = (config) => {
20
20
  const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid } = config;
21
21
  const sock = (0, messages_send_1.makeMessagesSocket)(config);
22
- const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, getUSyncDevices, sendPeerDataOperationMessage, createParticipantNodes } = sock;
22
+ const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, getUSyncDevices, createParticipantNodes } = sock;
23
23
  /** this mutex ensures that each retryRequest will wait for the previous one to finish */
24
24
  const retryMutex = (0, make_mutex_1.makeMutex)();
25
25
  const msgRetryCache = config.msgRetryCounterCache || new node_cache_1.default({
@@ -30,30 +30,23 @@ const makeMessagesRecvSocket = (config) => {
30
30
  stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
31
31
  useClones: false
32
32
  });
33
- const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
34
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
35
- useClones: false
36
- });
37
33
  let sendActiveReceipts = false;
38
- const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
34
+ const sendMessageAck = async ({ tag, attrs, content }) => {
39
35
  const stanza = {
40
36
  tag: 'ack',
41
37
  attrs: {
42
38
  id: attrs.id,
43
39
  to: attrs.from,
44
- class: tag
40
+ class: tag,
45
41
  }
46
42
  };
47
- if (!!errorCode) {
48
- stanza.attrs.error = errorCode.toString();
49
- }
50
43
  if (!!attrs.participant) {
51
44
  stanza.attrs.participant = attrs.participant;
52
45
  }
53
46
  if (!!attrs.recipient) {
54
47
  stanza.attrs.recipient = attrs.recipient;
55
48
  }
56
- if (!!attrs.type && (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
49
+ if (!!attrs.type && (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable'))) {
57
50
  stanza.attrs.type = attrs.type;
58
51
  }
59
52
  if (tag === 'message' && (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable')) {
@@ -134,24 +127,16 @@ const makeMessagesRecvSocket = (config) => {
134
127
  await query(stanza);
135
128
  };
136
129
  const sendRetryRequest = async (node, forceIncludeKeys = false) => {
137
- const { fullMessage } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '');
138
- const { key: msgKey } = fullMessage;
139
- const msgId = msgKey.id;
140
- const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
141
- let retryCount = msgRetryCache.get(key) || 0;
130
+ const msgId = node.attrs.id;
131
+ let retryCount = msgRetryCache.get(msgId) || 0;
142
132
  if (retryCount >= maxMsgRetryCount) {
143
133
  logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
144
- msgRetryCache.del(key);
134
+ msgRetryCache.del(msgId);
145
135
  return;
146
136
  }
147
137
  retryCount += 1;
148
- msgRetryCache.set(key, retryCount);
138
+ msgRetryCache.set(msgId, retryCount);
149
139
  const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
150
- if (retryCount === 1) {
151
- //request a resend via phone
152
- const msgId = await requestPlaceholderResend(msgKey);
153
- logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
154
- }
155
140
  const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
156
141
  await authState.keys.transaction(async () => {
157
142
  const receipt = {
@@ -230,8 +215,6 @@ const makeMessagesRecvSocket = (config) => {
230
215
  }
231
216
  };
232
217
  const handleGroupNotification = (participant, child, msg) => {
233
- var _a, _b, _c, _d;
234
- 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;
235
218
  switch (child === null || child === void 0 ? void 0 : child.tag) {
236
219
  case 'create':
237
220
  const metadata = (0, groups_1.extractGroupMetadata)(child);
@@ -257,11 +240,6 @@ const makeMessagesRecvSocket = (config) => {
257
240
  }
258
241
  };
259
242
  break;
260
- case 'modify':
261
- const oldNumber = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
262
- msg.messageStubParameters = oldNumber || [];
263
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
264
- break;
265
243
  case 'promote':
266
244
  case 'demote':
267
245
  case 'remove':
@@ -283,11 +261,6 @@ const makeMessagesRecvSocket = (config) => {
283
261
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
284
262
  msg.messageStubParameters = [child.attrs.subject];
285
263
  break;
286
- case 'description':
287
- 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();
288
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
289
- msg.messageStubParameters = description ? [description] : undefined;
290
- break;
291
264
  case 'announcement':
292
265
  case 'not_announcement':
293
266
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
@@ -316,15 +289,6 @@ const makeMessagesRecvSocket = (config) => {
316
289
  msg.messageStubParameters = [approvalMode.attrs.state];
317
290
  }
318
291
  break;
319
- case 'created_membership_requests':
320
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
321
- msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method];
322
- break;
323
- case 'revoked_membership_requests':
324
- const isDenied = (0, WABinary_1.areJidsSameUser)(participantJid, participant);
325
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
326
- msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected'];
327
- break;
328
292
  }
329
293
  };
330
294
  const processNotification = async (node) => {
@@ -357,6 +321,9 @@ const makeMessagesRecvSocket = (config) => {
357
321
  case 'encrypt':
358
322
  await handleEncryptNotification(node);
359
323
  break;
324
+ case 'newsletter':
325
+ // TO DO
326
+ break;
360
327
  case 'devices':
361
328
  const devices = (0, WABinary_1.getBinaryNodeChildren)(child, 'device');
362
329
  if ((0, WABinary_1.areJidsSameUser)(child.attrs.jid, authState.creds.me.id)) {
@@ -375,7 +342,7 @@ const makeMessagesRecvSocket = (config) => {
375
342
  const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set');
376
343
  const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete');
377
344
  ev.emit('contacts.update', [{
378
- id: (0, WABinary_1.jidNormalizedUser)((_a = node === null || node === void 0 ? void 0 : node.attrs) === null || _a === void 0 ? void 0 : _a.from) || ((_c = (_b = (setPicture || delPicture)) === null || _b === void 0 ? void 0 : _b.attrs) === null || _c === void 0 ? void 0 : _c.hash) || '',
345
+ id: (0, WABinary_1.jidNormalizedUser)((_a = node === null || node === void 0 ? void 0 : node.attrs) === null || _a === void 0 ? void 0 : _a.jid) || ((_c = (_b = (setPicture || delPicture)) === null || _b === void 0 ? void 0 : _b.attrs) === null || _c === void 0 ? void 0 : _c.hash) || '',
379
346
  imgUrl: setPicture ? 'changed' : 'removed'
380
347
  }]);
381
348
  if ((0, WABinary_1.isJidGroup)(from)) {
@@ -420,7 +387,7 @@ const makeMessagesRecvSocket = (config) => {
420
387
  const ref = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref'));
421
388
  const primaryIdentityPublicKey = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub'));
422
389
  const primaryEphemeralPublicKeyWrapped = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
423
- const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
390
+ const codePairingPublicKey = decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
424
391
  const companionSharedKey = Utils_1.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
425
392
  const random = (0, crypto_1.randomBytes)(32);
426
393
  const linkCodeSalt = (0, crypto_1.randomBytes)(32);
@@ -477,10 +444,10 @@ const makeMessagesRecvSocket = (config) => {
477
444
  return result;
478
445
  }
479
446
  };
480
- async function decipherLinkPublicKey(data) {
447
+ function decipherLinkPublicKey(data) {
481
448
  const buffer = toRequiredBuffer(data);
482
449
  const salt = buffer.slice(0, 32);
483
- const secretKey = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
450
+ const secretKey = (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
484
451
  const iv = buffer.slice(32, 48);
485
452
  const payload = buffer.slice(48, 80);
486
453
  return (0, Utils_1.aesDecryptCTR)(payload, secretKey, iv);
@@ -515,7 +482,8 @@ const makeMessagesRecvSocket = (config) => {
515
482
  await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
516
483
  }
517
484
  logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
518
- for (const [i, msg] of msgs.entries()) {
485
+ for (let i = 0; i < msgs.length; i++) {
486
+ const msg = msgs[i];
519
487
  if (msg) {
520
488
  updateSendMessageAgainCount(ids[i], participant);
521
489
  const msgRelayOpts = { messageId: ids[i] };
@@ -558,63 +526,59 @@ const makeMessagesRecvSocket = (config) => {
558
526
  const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], 'item');
559
527
  ids.push(...items.map(i => i.attrs.id));
560
528
  }
561
- try {
562
- await Promise.all([
563
- processingMutex.mutex(async () => {
564
- const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
565
- if (typeof status !== 'undefined' &&
566
- (
567
- // basically, we only want to know when a message from us has been delivered to/read by the other person
568
- // or another device of ours has read some messages
569
- status > WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ||
570
- !isNodeFromMe)) {
571
- if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
572
- if (attrs.participant) {
573
- const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
574
- ev.emit('message-receipt.update', ids.map(id => ({
575
- key: { ...key, id },
576
- receipt: {
577
- userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
578
- [updateKey]: +attrs.t
579
- }
580
- })));
581
- }
582
- }
583
- else {
584
- ev.emit('messages.update', ids.map(id => ({
529
+ await Promise.all([
530
+ processingMutex.mutex(async () => {
531
+ const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
532
+ if (typeof status !== 'undefined' &&
533
+ (
534
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
535
+ // or another device of ours has read some messages
536
+ status > WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ||
537
+ !isNodeFromMe)) {
538
+ if ((0, WABinary_1.isJidGroup)(remoteJid)) {
539
+ if (attrs.participant) {
540
+ const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
541
+ ev.emit('message-receipt.update', ids.map(id => ({
585
542
  key: { ...key, id },
586
- update: { status }
543
+ receipt: {
544
+ userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
545
+ [updateKey]: +attrs.t
546
+ }
587
547
  })));
588
548
  }
589
549
  }
590
- if (attrs.type === 'retry') {
591
- // correctly set who is asking for the retry
592
- key.participant = key.participant || attrs.from;
593
- const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
594
- if (willSendMessageAgain(ids[0], key.participant)) {
595
- if (key.fromMe) {
596
- try {
597
- logger.debug({ attrs, key }, 'recv retry request');
598
- await sendMessagesAgain(key, ids, retryNode);
599
- }
600
- catch (error) {
601
- logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
602
- }
550
+ else {
551
+ ev.emit('messages.update', ids.map(id => ({
552
+ key: { ...key, id },
553
+ update: { status }
554
+ })));
555
+ }
556
+ }
557
+ if (attrs.type === 'retry') {
558
+ // correctly set who is asking for the retry
559
+ key.participant = key.participant || attrs.from;
560
+ const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
561
+ if (willSendMessageAgain(ids[0], key.participant)) {
562
+ if (key.fromMe) {
563
+ try {
564
+ logger.debug({ attrs, key }, 'recv retry request');
565
+ await sendMessagesAgain(key, ids, retryNode);
603
566
  }
604
- else {
605
- logger.info({ attrs, key }, 'recv retry for not fromMe message');
567
+ catch (error) {
568
+ logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
606
569
  }
607
570
  }
608
571
  else {
609
- logger.info({ attrs, key }, 'will not send message again, as sent too many times');
572
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
610
573
  }
611
574
  }
612
- })
613
- ]);
614
- }
615
- finally {
616
- await sendMessageAck(node);
617
- }
575
+ else {
576
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
577
+ }
578
+ }
579
+ }),
580
+ sendMessageAck(node)
581
+ ]);
618
582
  };
619
583
  const handleNotification = async (node) => {
620
584
  const remoteJid = node.attrs.from;
@@ -623,169 +587,89 @@ const makeMessagesRecvSocket = (config) => {
623
587
  await sendMessageAck(node);
624
588
  return;
625
589
  }
626
- try {
627
- await Promise.all([
628
- processingMutex.mutex(async () => {
629
- var _a;
630
- const msg = await processNotification(node);
631
- if (msg) {
632
- const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
633
- msg.key = {
634
- remoteJid,
635
- fromMe,
636
- participant: node.attrs.participant,
637
- id: node.attrs.id,
638
- ...(msg.key || {})
639
- };
640
- (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
641
- msg.messageTimestamp = +node.attrs.t;
642
- const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
643
- await upsertMessage(fullMsg, 'append');
644
- }
645
- })
646
- ]);
647
- }
648
- finally {
649
- await sendMessageAck(node);
650
- }
590
+ await Promise.all([
591
+ processingMutex.mutex(async () => {
592
+ var _a;
593
+ const msg = await processNotification(node);
594
+ if (msg) {
595
+ const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
596
+ msg.key = {
597
+ remoteJid,
598
+ fromMe,
599
+ participant: node.attrs.participant,
600
+ id: node.attrs.id,
601
+ ...(msg.key || {})
602
+ };
603
+ (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
604
+ msg.messageTimestamp = +node.attrs.t;
605
+ const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
606
+ await upsertMessage(fullMsg, 'append');
607
+ }
608
+ }),
609
+ sendMessageAck(node)
610
+ ]);
651
611
  };
652
612
  const handleMessage = async (node) => {
653
- var _a, _b, _c;
613
+ var _a, _b;
654
614
  if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== '@s.whatsapp.net') {
655
615
  logger.debug({ key: node.attrs.key }, 'ignored message');
656
616
  await sendMessageAck(node);
657
617
  return;
658
618
  }
659
- let response;
660
- if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable') && !(0, WABinary_1.getBinaryNodeChild)(node, 'enc')) {
661
- await sendMessageAck(node);
662
- const { key } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '').fullMessage;
663
- response = await requestPlaceholderResend(key);
664
- if (response === 'RESOLVED') {
665
- return;
666
- }
667
- logger.debug('received unavailable message, acked and requested resend from phone');
668
- }
669
- else {
670
- if (placeholderResendCache.get(node.attrs.id)) {
671
- placeholderResendCache.del(node.attrs.id);
672
- }
673
- }
674
619
  const { fullMessage: msg, category, author, decrypt } = (0, Utils_1.decryptMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
675
- if (response && ((_a = msg === null || msg === void 0 ? void 0 : msg.messageStubParameters) === null || _a === void 0 ? void 0 : _a[0]) === Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT) {
676
- msg.messageStubParameters = [Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT, response];
677
- }
678
- if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.type) === WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER && node.attrs.sender_pn) {
679
- ev.emit('chats.phoneNumberShare', { lid: node.attrs.from, jid: node.attrs.sender_pn });
620
+ if (((_b = (_a = msg.message) === null || _a === void 0 ? void 0 : _a.protocolMessage) === null || _b === void 0 ? void 0 : _b.type) === WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER) {
621
+ if (node.attrs.sender_pn) {
622
+ ev.emit('chats.phoneNumberShare', { lid: node.attrs.from, jid: node.attrs.sender_pn });
623
+ }
680
624
  }
681
- try {
682
- await Promise.all([
683
- processingMutex.mutex(async () => {
684
- var _a;
685
- await decrypt();
686
- // message failed to decrypt
687
- if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
688
- if (((_a = msg === null || msg === void 0 ? void 0 : msg.messageStubParameters) === null || _a === void 0 ? void 0 : _a[0]) === Utils_1.MISSING_KEYS_ERROR_TEXT) {
689
- return sendMessageAck(node, Utils_1.NACK_REASONS.ParsingError);
690
- }
691
- retryMutex.mutex(async () => {
692
- if (ws.isOpen) {
693
- if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable')) {
694
- return;
695
- }
696
- const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
697
- await sendRetryRequest(node, !encNode);
698
- if (retryRequestDelayMs) {
699
- await (0, Utils_1.delay)(retryRequestDelayMs);
700
- }
625
+ await Promise.all([
626
+ processingMutex.mutex(async () => {
627
+ await decrypt();
628
+ // message failed to decrypt
629
+ if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
630
+ retryMutex.mutex(async () => {
631
+ if (ws.isOpen) {
632
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
633
+ await sendRetryRequest(node, !encNode);
634
+ if (retryRequestDelayMs) {
635
+ await (0, Utils_1.delay)(retryRequestDelayMs);
701
636
  }
702
- else {
703
- logger.debug({ node }, 'connection closed, ignoring retry req');
704
- }
705
- });
706
- }
707
- else {
708
- // no type in the receipt => message delivered
709
- let type = undefined;
710
- let participant = msg.key.participant;
711
- if (category === 'peer') { // special peer message
712
- type = 'peer_msg';
713
637
  }
714
- else if (msg.key.fromMe) { // message was sent by us from a different device
715
- type = 'sender';
716
- // need to specially handle this case
717
- if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
718
- participant = author;
719
- }
720
- }
721
- else if (!sendActiveReceipts) {
722
- type = 'inactive';
638
+ else {
639
+ logger.debug({ node }, 'connection closed, ignoring retry req');
723
640
  }
724
- await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
725
- // send ack for history message
726
- const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
727
- if (isAnyHistoryMsg) {
728
- const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
729
- await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
641
+ });
642
+ }
643
+ else {
644
+ // no type in the receipt => message delivered
645
+ let type = undefined;
646
+ let participant = msg.key.participant;
647
+ if (category === 'peer') { // special peer message
648
+ type = 'peer_msg';
649
+ }
650
+ else if (msg.key.fromMe) { // message was sent by us from a different device
651
+ type = 'sender';
652
+ // need to specially handle this case
653
+ if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
654
+ participant = author;
730
655
  }
731
656
  }
732
- (0, Utils_2.cleanMessage)(msg, authState.creds.me.id);
733
- await sendMessageAck(node);
734
- await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
735
- })
736
- ]);
737
- }
738
- catch (error) {
739
- logger.error({ error, node }, 'error in handling message');
740
- }
741
- };
742
- const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
743
- var _a;
744
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
745
- throw new boom_1.Boom('Not authenticated');
746
- }
747
- const pdoMessage = {
748
- historySyncOnDemandRequest: {
749
- chatJid: oldestMsgKey.remoteJid,
750
- oldestMsgFromMe: oldestMsgKey.fromMe,
751
- oldestMsgId: oldestMsgKey.id,
752
- oldestMsgTimestampMs: oldestMsgTimestamp,
753
- onDemandMsgCount: count
754
- },
755
- peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
756
- };
757
- return sendPeerDataOperationMessage(pdoMessage);
758
- };
759
- const requestPlaceholderResend = async (messageKey) => {
760
- var _a;
761
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
762
- throw new boom_1.Boom('Not authenticated');
763
- }
764
- if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
765
- logger.debug('already requested resend', { messageKey });
766
- return;
767
- }
768
- else {
769
- placeholderResendCache.set(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id, true);
770
- }
771
- await (0, Utils_1.delay)(5000);
772
- if (!placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
773
- logger.debug('message received while resend requested', { messageKey });
774
- return 'RESOLVED';
775
- }
776
- const pdoMessage = {
777
- placeholderMessageResendRequest: [{
778
- messageKey
779
- }],
780
- peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
781
- };
782
- setTimeout(() => {
783
- if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
784
- logger.debug('PDO message without response after 15 seconds. Phone possibly offline', { messageKey });
785
- placeholderResendCache.del(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id);
786
- }
787
- }, 15000);
788
- return sendPeerDataOperationMessage(pdoMessage);
657
+ else if (!sendActiveReceipts) {
658
+ type = 'inactive';
659
+ }
660
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
661
+ // send ack for history message
662
+ const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
663
+ if (isAnyHistoryMsg) {
664
+ const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
665
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
666
+ }
667
+ }
668
+ (0, Utils_2.cleanMessage)(msg, authState.creds.me.id);
669
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
670
+ }),
671
+ sendMessageAck(node)
672
+ ]);
789
673
  };
790
674
  const handleCall = async (node) => {
791
675
  const { attrs } = node;
@@ -814,7 +698,7 @@ const makeMessagesRecvSocket = (config) => {
814
698
  call.isGroup = existingCall.isGroup;
815
699
  }
816
700
  // delete data once call has ended
817
- if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
701
+ if (status === 'reject' || status === 'accept' || status === 'timeout') {
818
702
  callOfferCache.del(call.id);
819
703
  }
820
704
  ev.emit('call', [call]);
@@ -822,19 +706,19 @@ const makeMessagesRecvSocket = (config) => {
822
706
  };
823
707
  const handleBadAck = async ({ attrs }) => {
824
708
  const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
825
- // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
826
- // // current hypothesis is that if pash is sent in the ack
827
- // // it means -- the message hasn't reached all devices yet
828
- // // we'll retry sending the message here
829
- // if(attrs.phash) {
830
- // logger.info({ attrs }, 'received phash in ack, resending message...')
831
- // const msg = await getMessage(key)
832
- // if(msg) {
833
- // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
834
- // } else {
835
- // logger.warn({ attrs }, 'could not send message again, as it was not found')
836
- // }
837
- // }
709
+ // current hypothesis is that if pash is sent in the ack
710
+ // it means -- the message hasn't reached all devices yet
711
+ // we'll retry sending the message here
712
+ if (attrs.phash) {
713
+ logger.info({ attrs }, 'received phash in ack, resending message...');
714
+ const msg = await getMessage(key);
715
+ if (msg) {
716
+ await relayMessage(key.remoteJid, msg, { messageId: key.id, useUserDevicesCache: false });
717
+ }
718
+ else {
719
+ logger.warn({ attrs }, 'could not send message again, as it was not found');
720
+ }
721
+ }
838
722
  // error in acknowledgement,
839
723
  // device could not display the message
840
724
  if (attrs.error) {
@@ -859,63 +743,22 @@ const makeMessagesRecvSocket = (config) => {
859
743
  await execTask();
860
744
  ev.flush();
861
745
  function execTask() {
862
- return exec(node, false)
746
+ return exec(node)
863
747
  .catch(err => onUnexpectedError(err, identifier));
864
748
  }
865
749
  };
866
- const makeOfflineNodeProcessor = () => {
867
- const nodeProcessorMap = new Map([
868
- ['message', handleMessage],
869
- ['call', handleCall],
870
- ['receipt', handleReceipt],
871
- ['notification', handleNotification]
872
- ]);
873
- const nodes = [];
874
- let isProcessing = false;
875
- const enqueue = (type, node) => {
876
- nodes.push({ type, node });
877
- if (isProcessing) {
878
- return;
879
- }
880
- isProcessing = true;
881
- const promise = async () => {
882
- while (nodes.length && ws.isOpen) {
883
- const { type, node } = nodes.shift();
884
- const nodeProcessor = nodeProcessorMap.get(type);
885
- if (!nodeProcessor) {
886
- onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
887
- continue;
888
- }
889
- await nodeProcessor(node);
890
- }
891
- isProcessing = false;
892
- };
893
- promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
894
- };
895
- return { enqueue };
896
- };
897
- const offlineNodeProcessor = makeOfflineNodeProcessor();
898
- const processNode = (type, node, identifier, exec) => {
899
- const isOffline = !!node.attrs.offline;
900
- if (isOffline) {
901
- offlineNodeProcessor.enqueue(type, node);
902
- }
903
- else {
904
- processNodeWithBuffer(node, identifier, exec);
905
- }
906
- };
907
750
  // recv a message
908
751
  ws.on('CB:message', (node) => {
909
- processNode('message', node, 'processing message', handleMessage);
752
+ processNodeWithBuffer(node, 'processing message', handleMessage);
910
753
  });
911
754
  ws.on('CB:call', async (node) => {
912
- processNode('call', node, 'handling call', handleCall);
755
+ processNodeWithBuffer(node, 'handling call', handleCall);
913
756
  });
914
757
  ws.on('CB:receipt', node => {
915
- processNode('receipt', node, 'handling receipt', handleReceipt);
758
+ processNodeWithBuffer(node, 'handling receipt', handleReceipt);
916
759
  });
917
760
  ws.on('CB:notification', async (node) => {
918
- processNode('notification', node, 'handling notification', handleNotification);
761
+ processNodeWithBuffer(node, 'handling notification', handleNotification);
919
762
  });
920
763
  ws.on('CB:ack,class:message', (node) => {
921
764
  handleBadAck(node)
@@ -958,9 +801,7 @@ const makeMessagesRecvSocket = (config) => {
958
801
  sendMessageAck,
959
802
  sendRetryRequest,
960
803
  offerCall,
961
- rejectCall,
962
- fetchMessageHistory,
963
- requestPlaceholderResend,
804
+ rejectCall
964
805
  };
965
806
  };
966
807
  exports.makeMessagesRecvSocket = makeMessagesRecvSocket;