@zetagoaurum-socket/wasocket 3.0.0 → 3.2.7

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 (94) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +67 -84
  3. package/WAProto/index.js +56886 -17506
  4. package/engine-requirements.js +10 -0
  5. package/lib/Defaults/baileys-version.json +1 -1
  6. package/lib/Defaults/index.js +50 -9
  7. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  8. package/lib/Signal/Group/ciphertext-message.js +15 -0
  9. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  10. package/lib/Signal/Group/group-session-builder.js +64 -0
  11. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  12. package/lib/Signal/Group/group_cipher.js +96 -0
  13. package/lib/Signal/Group/index.d.ts +11 -0
  14. package/lib/Signal/Group/index.js +57 -0
  15. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  16. package/lib/Signal/Group/keyhelper.js +55 -0
  17. package/lib/Signal/Group/queue-job.d.ts +1 -0
  18. package/lib/Signal/Group/queue-job.js +57 -0
  19. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  20. package/lib/Signal/Group/sender-chain-key.js +34 -0
  21. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  22. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  23. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  24. package/lib/Signal/Group/sender-key-message.js +69 -0
  25. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  26. package/lib/Signal/Group/sender-key-name.js +51 -0
  27. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  28. package/lib/Signal/Group/sender-key-record.js +53 -0
  29. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  30. package/lib/Signal/Group/sender-key-state.js +99 -0
  31. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  32. package/{WASignalGroup/sender_message_key.js → lib/Signal/Group/sender-message-key.js} +6 -16
  33. package/lib/Signal/libsignal.js +51 -29
  34. package/lib/Socket/business.d.ts +3 -2
  35. package/lib/Socket/chats.d.ts +215 -28
  36. package/lib/Socket/chats.js +185 -70
  37. package/lib/Socket/chats.js.bak +981 -0
  38. package/lib/Socket/dugong.d.ts +254 -0
  39. package/lib/Socket/dugong.js +432 -141
  40. package/lib/Socket/groups.js +20 -23
  41. package/lib/Socket/index.js +2 -15
  42. package/lib/Socket/messages-recv.d.ts +56 -55
  43. package/lib/Socket/messages-recv.js +370 -112
  44. package/lib/Socket/messages-send.d.ts +3 -2
  45. package/lib/Socket/messages-send.js +465 -368
  46. package/lib/Socket/newsletter.js +175 -28
  47. package/lib/Socket/socket.js +203 -174
  48. package/lib/Socket/usync.d.ts +3 -3
  49. package/lib/Types/GroupMetadata.d.ts +1 -0
  50. package/lib/Types/Newsletter.d.ts +97 -86
  51. package/lib/Types/Newsletter.js +38 -32
  52. package/lib/Types/USync.d.ts +25 -0
  53. package/lib/Types/USync.js +2 -0
  54. package/lib/Utils/anti-crash.js +20 -0
  55. package/lib/Utils/auto-contact.js +74 -0
  56. package/lib/Utils/chat-utils.js +17 -3
  57. package/lib/Utils/generics.js +68 -31
  58. package/lib/Utils/generics.js.bak +433 -0
  59. package/lib/Utils/history.js +6 -1
  60. package/lib/Utils/link-preview.js +4 -2
  61. package/lib/Utils/messages-media.js +145 -57
  62. package/lib/Utils/messages.js +89 -305
  63. package/lib/Utils/signal.js +48 -46
  64. package/lib/Utils/use-multi-file-auth-state.js +45 -6
  65. package/lib/Utils/validate-connection.js +91 -65
  66. package/lib/Utils/validate-connection.js.bak +237 -0
  67. package/lib/WABinary/constants.d.ts +27 -24
  68. package/lib/WABinary/encode.js +160 -123
  69. package/lib/WABinary/generic-utils.d.ts +2 -0
  70. package/lib/WABinary/generic-utils.js +124 -36
  71. package/lib/WABinary/jid-utils.js +5 -26
  72. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -1
  73. package/lib/index.d.ts +1 -0
  74. package/lib/index.js +9 -0
  75. package/package.json +105 -100
  76. package/WAProto/GenerateStatics.sh +0 -4
  77. package/WAProto/WAProto.proto +0 -3344
  78. package/WAProto/index.d.ts +0 -37016
  79. package/WASignalGroup/GroupProtocol.js +0 -1697
  80. package/WASignalGroup/ciphertext_message.js +0 -16
  81. package/WASignalGroup/group_cipher.js +0 -120
  82. package/WASignalGroup/group_session_builder.js +0 -46
  83. package/WASignalGroup/index.js +0 -5
  84. package/WASignalGroup/keyhelper.js +0 -21
  85. package/WASignalGroup/protobufs.js +0 -3
  86. package/WASignalGroup/queue_job.js +0 -69
  87. package/WASignalGroup/sender_chain_key.js +0 -50
  88. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  89. package/WASignalGroup/sender_key_message.js +0 -92
  90. package/WASignalGroup/sender_key_name.js +0 -70
  91. package/WASignalGroup/sender_key_record.js +0 -56
  92. package/WASignalGroup/sender_key_state.js +0 -129
  93. package/lib/WAUSync/Fall +0 -1
  94. package/lib/WAUSync/Protocols/Fal +0 -1
@@ -6,78 +6,147 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.makeMessagesRecvSocket = void 0;
7
7
  const boom_1 = require("@hapi/boom");
8
8
  const crypto_1 = require("crypto");
9
- const node_cache_1 = __importDefault(require("node-cache"));
9
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
10
10
  const WAProto_1 = require("../../WAProto");
11
11
  const Defaults_1 = require("../Defaults");
12
12
  const Types_1 = require("../Types");
13
13
  const Utils_1 = require("../Utils");
14
- const Utils_2 = require("../Utils");
15
14
  const make_mutex_1 = require("../Utils/make-mutex");
16
15
  const WABinary_1 = require("../WABinary");
17
16
  const groups_1 = require("./groups");
18
17
  const messages_send_1 = require("./messages-send");
18
+ const { ContactManager } = require("../Utils/auto-contact");
19
19
  const makeMessagesRecvSocket = (config) => {
20
- const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid } = config;
20
+ const {
21
+ logger,
22
+ retryRequestDelayMs,
23
+ maxMsgRetryCount,
24
+ getMessage,
25
+ shouldIgnoreJid
26
+ } = config;
21
27
  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, createParticipantNodes } = sock;
28
+ const {
29
+ ev,
30
+ authState,
31
+ ws,
32
+ processingMutex,
33
+ signalRepository,
34
+ query,
35
+ upsertMessage,
36
+ resyncAppState,
37
+ groupMetadata,
38
+ onUnexpectedError,
39
+ assertSessions,
40
+ sendNode,
41
+ relayMessage,
42
+ sendReceipt,
43
+ uploadPreKeys,
44
+ createParticipantNodes,
45
+ getUSyncDevices,
46
+ sendPeerDataOperationMessage
47
+ } = sock;
23
48
  /** this mutex ensures that each retryRequest will wait for the previous one to finish */
24
49
  const retryMutex = (0, make_mutex_1.makeMutex)();
25
50
  const msgRetryCache = config.msgRetryCounterCache || new node_cache_1.default({
26
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
51
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
27
52
  useClones: false
28
53
  });
29
54
  const callOfferCache = config.callOfferCache || new node_cache_1.default({
30
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER,
55
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
56
+ useClones: false
57
+ });
58
+ const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
59
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
31
60
  useClones: false
32
61
  });
33
62
  let sendActiveReceipts = false;
34
- const sendMessageAck = async ({ tag, attrs, content }) => {
63
+ const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
35
64
  const stanza = {
36
65
  tag: 'ack',
37
66
  attrs: {
38
67
  id: attrs.id,
39
68
  to: attrs.from,
40
- class: tag,
69
+ class: tag
41
70
  }
42
- };
71
+ }
72
+ if (!!errorCode) {
73
+ stanza.attrs.error = errorCode.toString();
74
+ }
43
75
  if (!!attrs.participant) {
44
76
  stanza.attrs.participant = attrs.participant;
45
77
  }
46
78
  if (!!attrs.recipient) {
47
79
  stanza.attrs.recipient = attrs.recipient;
48
80
  }
49
- if (!!attrs.type && (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable'))) {
81
+ if (!!attrs.type && (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
50
82
  stanza.attrs.type = attrs.type;
51
83
  }
52
84
  if (tag === 'message' && (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable')) {
53
85
  stanza.attrs.from = authState.creds.me.id;
54
86
  }
55
- logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
87
+ logger.debug({
88
+ recv: {
89
+ tag,
90
+ attrs
91
+ },
92
+ sent: stanza.attrs }, 'sent ack');
56
93
  await sendNode(stanza);
57
94
  };
58
95
  const offerCall = async (toJid, isVideo = false) => {
59
96
  const callId = (0, crypto_1.randomBytes)(16).toString('hex').toUpperCase().substring(0, 64);
60
97
  const offerContent = [];
61
- offerContent.push({ tag: 'audio', attrs: { enc: 'opus', rate: '16000' }, content: undefined });
62
- offerContent.push({ tag: 'audio', attrs: { enc: 'opus', rate: '8000' }, content: undefined });
98
+ offerContent.push({
99
+ tag: 'audio',
100
+ attrs: {
101
+ enc: 'opus',
102
+ rate: '16000'
103
+ }, content: undefined
104
+ });
105
+ offerContent.push({
106
+ tag: 'audio',
107
+ attrs: {
108
+ enc: 'opus',
109
+ rate: '8000'
110
+ }, content: undefined
111
+ });
63
112
  if (isVideo) {
64
113
  offerContent.push({
65
114
  tag: 'video',
66
- attrs: { enc: 'vp8', dec: 'vp8', orientation: '0', 'screen_width': '1920', 'screen_height': '1080', 'device_orientation': '0' },
67
- content: undefined
115
+ attrs: {
116
+ orientation: '0',
117
+ 'screen_width': '1920',
118
+ 'screen_height': '1080',
119
+ 'device_orientation': '0',
120
+ enc: 'vp8',
121
+ dec: 'vp8',
122
+ }
68
123
  });
69
124
  }
70
- offerContent.push({ tag: 'net', attrs: { medium: '3' }, content: undefined });
71
- offerContent.push({ tag: 'capability', attrs: { ver: '1' }, content: new Uint8Array([1, 4, 255, 131, 207, 4]) });
72
- offerContent.push({ tag: 'encopt', attrs: { keygen: '2' }, content: undefined });
125
+ offerContent.push({
126
+ tag: 'net',
127
+ attrs: {
128
+ medium: '3'
129
+ }, content: undefined
130
+ });
131
+ offerContent.push({
132
+ tag: 'capability',
133
+ attrs: {
134
+ ver: '1'
135
+ }, content: new Uint8Array([1, 4, 255, 131, 207, 4]) });
136
+ offerContent.push({
137
+ tag: 'encopt',
138
+ attrs: {
139
+ keygen: '2'
140
+ }, content: undefined
141
+ })
73
142
  const encKey = (0, crypto_1.randomBytes)(32);
74
143
  const devices = (await getUSyncDevices([toJid], true, false)).map(({ user, device }) => (0, WABinary_1.jidEncode)(user, 's.whatsapp.net', device));
75
144
  await assertSessions(devices, true);
76
145
  const { nodes: destinations, shouldIncludeDeviceIdentity } = await createParticipantNodes(devices, {
77
146
  call: {
78
- callKey: new Uint8Array(encKey)
147
+ callKey: encKey
79
148
  }
80
- }, { count: '0' });
149
+ });
81
150
  offerContent.push({ tag: 'destination', attrs: {}, content: destinations });
82
151
  if (shouldIncludeDeviceIdentity) {
83
152
  offerContent.push({
@@ -89,7 +158,6 @@ const makeMessagesRecvSocket = (config) => {
89
158
  const stanza = ({
90
159
  tag: 'call',
91
160
  attrs: {
92
- id: (0, Utils_1.generateMessageIDV2)(),
93
161
  to: toJid,
94
162
  },
95
163
  content: [{
@@ -103,8 +171,9 @@ const makeMessagesRecvSocket = (config) => {
103
171
  });
104
172
  await query(stanza);
105
173
  return {
106
- id: callId,
107
- to: toJid
174
+ callId,
175
+ toJid,
176
+ isVideo,
108
177
  };
109
178
  };
110
179
  const rejectCall = async (callId, callFrom) => {
@@ -127,16 +196,24 @@ const makeMessagesRecvSocket = (config) => {
127
196
  await query(stanza);
128
197
  };
129
198
  const sendRetryRequest = async (node, forceIncludeKeys = false) => {
130
- const msgId = node.attrs.id;
131
- let retryCount = msgRetryCache.get(msgId) || 0;
199
+ const { fullMessage } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '');
200
+ const { key: msgKey } = fullMessage;
201
+ const msgId = msgKey.id;
202
+ const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
203
+ let retryCount = msgRetryCache.get(key) || 0;
132
204
  if (retryCount >= maxMsgRetryCount) {
133
205
  logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
134
- msgRetryCache.del(msgId);
206
+ msgRetryCache.del(key);
135
207
  return;
136
208
  }
137
209
  retryCount += 1;
138
- msgRetryCache.set(msgId, retryCount);
210
+ msgRetryCache.set(key, retryCount);
139
211
  const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
212
+ if (retryCount === 1) {
213
+ //request a resend via phone
214
+ const msgId = await requestPlaceholderResend(msgKey);
215
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
216
+ }
140
217
  const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
141
218
  await authState.keys.transaction(async () => {
142
219
  const receipt = {
@@ -215,6 +292,8 @@ const makeMessagesRecvSocket = (config) => {
215
292
  }
216
293
  };
217
294
  const handleGroupNotification = (participant, child, msg) => {
295
+ var _a, _b, _c, _d;
296
+ 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;
218
297
  switch (child === null || child === void 0 ? void 0 : child.tag) {
219
298
  case 'create':
220
299
  const metadata = (0, groups_1.extractGroupMetadata)(child);
@@ -240,6 +319,11 @@ const makeMessagesRecvSocket = (config) => {
240
319
  }
241
320
  };
242
321
  break;
322
+ case 'modify':
323
+ const oldNumber = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
324
+ msg.messageStubParameters = oldNumber || [];
325
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
326
+ break;
243
327
  case 'promote':
244
328
  case 'demote':
245
329
  case 'remove':
@@ -261,6 +345,11 @@ const makeMessagesRecvSocket = (config) => {
261
345
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
262
346
  msg.messageStubParameters = [child.attrs.subject];
263
347
  break;
348
+ case 'description':
349
+ 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();
350
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
351
+ msg.messageStubParameters = description ? [description] : undefined;
352
+ break;
264
353
  case 'announcement':
265
354
  case 'not_announcement':
266
355
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
@@ -289,10 +378,66 @@ const makeMessagesRecvSocket = (config) => {
289
378
  msg.messageStubParameters = [approvalMode.attrs.state];
290
379
  }
291
380
  break;
381
+ case 'created_membership_requests':
382
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
383
+ msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method];
384
+ break;
385
+ case 'revoked_membership_requests':
386
+ const isDenied = (0, WABinary_1.areJidsSameUser)(participantJid, participant);
387
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
388
+ msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected'];
389
+ break;
390
+ break;
391
+ default:
392
+ // console.log("BAILEYS-DEBUG:", JSON.stringify({ ...child, content: Buffer.isBuffer(child.content) ? child.content.toString() : child.content, participant }, null, 2))
393
+ }
394
+ };
395
+ const handleNewsletterNotification = (id, node) => {
396
+ const messages = (0, WABinary_1.getBinaryNodeChild)(node, 'messages');
397
+ const message = (0, WABinary_1.getBinaryNodeChild)(messages, 'message');
398
+ const serverId = message.attrs.server_id;
399
+ const reactionsList = (0, WABinary_1.getBinaryNodeChild)(message, 'reactions');
400
+ const viewsList = (0, WABinary_1.getBinaryNodeChildren)(message, 'views_count');
401
+ if (reactionsList) {
402
+ const reactions = (0, WABinary_1.getBinaryNodeChildren)(reactionsList, 'reaction');
403
+ if (reactions.length === 0) {
404
+ ev.emit('newsletter.reaction', { id, 'server_id': serverId, reaction: { removed: true } });
405
+ }
406
+ reactions.forEach(item => {
407
+ var _a, _b;
408
+ ev.emit('newsletter.reaction', { id, 'server_id': serverId, reaction: { code: (_a = item.attrs) === null || _a === void 0 ? void 0 : _a.code, count: +((_b = item.attrs) === null || _b === void 0 ? void 0 : _b.count) } });
409
+ });
410
+ }
411
+ if (viewsList.length) {
412
+ viewsList.forEach(item => {
413
+ ev.emit('newsletter.view', { id, 'server_id': serverId, count: +item.attrs.count });
414
+ });
415
+ }
416
+ };
417
+ const handleMexNewsletterNotification = (id, node) => {
418
+ var _a;
419
+ const operation = node === null || node === void 0 ? void 0 : node.attrs.op_name;
420
+ const content = JSON.parse((_a = node === null || node === void 0 ? void 0 : node.content) === null || _a === void 0 ? void 0 : _a.toString());
421
+ let contentPath;
422
+ if (operation === Types_1.MexOperations.PROMOTE || operation === Types_1.MexOperations.DEMOTE) {
423
+ let action;
424
+ if (operation === Types_1.MexOperations.PROMOTE) {
425
+ action = 'promote';
426
+ contentPath = content.data[Types_1.XWAPaths.PROMOTE];
427
+ }
428
+ if (operation === Types_1.MexOperations.DEMOTE) {
429
+ action = 'demote';
430
+ contentPath = content.data[Types_1.XWAPaths.DEMOTE];
431
+ }
432
+ ev.emit('newsletter-participants.update', { id, author: contentPath.actor.pn, user: contentPath.user.pn, new_role: contentPath.user_new_role, action });
433
+ }
434
+ if (operation === Types_1.MexOperations.UPDATE) {
435
+ contentPath = content.data[Types_1.XWAPaths.METADATA_UPDATE];
436
+ ev.emit('newsletter-settings.update', { id, update: contentPath.thread_metadata.settings });
292
437
  }
293
438
  };
294
439
  const processNotification = async (node) => {
295
- var _a, _b, _c;
440
+ var _a, _b;
296
441
  const result = {};
297
442
  const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
298
443
  const nodeType = node.attrs.type;
@@ -311,6 +456,12 @@ const makeMessagesRecvSocket = (config) => {
311
456
  logger.debug({ jid }, 'got privacy token update');
312
457
  }
313
458
  break;
459
+ case 'newsletter':
460
+ handleNewsletterNotification(node.attrs.from, child);
461
+ break;
462
+ case 'mex':
463
+ handleMexNewsletterNotification(node.attrs.from, child);
464
+ break;
314
465
  case 'w:gp2':
315
466
  handleGroupNotification(node.attrs.participant, child, result);
316
467
  break;
@@ -321,9 +472,6 @@ const makeMessagesRecvSocket = (config) => {
321
472
  case 'encrypt':
322
473
  await handleEncryptNotification(node);
323
474
  break;
324
- case 'newsletter':
325
- // TO DO
326
- break;
327
475
  case 'devices':
328
476
  const devices = (0, WABinary_1.getBinaryNodeChildren)(child, 'device');
329
477
  if ((0, WABinary_1.areJidsSameUser)(child.attrs.jid, authState.creds.me.id)) {
@@ -342,7 +490,7 @@ const makeMessagesRecvSocket = (config) => {
342
490
  const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set');
343
491
  const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete');
344
492
  ev.emit('contacts.update', [{
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) || '',
493
+ id: from || ((_b = (_a = (setPicture || delPicture)) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.hash) || '',
346
494
  imgUrl: setPicture ? 'changed' : 'removed'
347
495
  }]);
348
496
  if ((0, WABinary_1.isJidGroup)(from)) {
@@ -387,11 +535,11 @@ const makeMessagesRecvSocket = (config) => {
387
535
  const ref = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref'));
388
536
  const primaryIdentityPublicKey = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub'));
389
537
  const primaryEphemeralPublicKeyWrapped = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
390
- const codePairingPublicKey = decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
538
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
391
539
  const companionSharedKey = Utils_1.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
392
540
  const random = (0, crypto_1.randomBytes)(32);
393
541
  const linkCodeSalt = (0, crypto_1.randomBytes)(32);
394
- const linkCodePairingExpanded = (0, Utils_1.hkdf)(companionSharedKey, 32, {
542
+ const linkCodePairingExpanded = await (0, Utils_1.hkdf)(companionSharedKey, 32, {
395
543
  salt: linkCodeSalt,
396
544
  info: 'link_code_pairing_key_bundle_encryption_key'
397
545
  });
@@ -401,7 +549,7 @@ const makeMessagesRecvSocket = (config) => {
401
549
  const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
402
550
  const identitySharedKey = Utils_1.Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
403
551
  const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
404
- authState.creds.advSecretKey = (0, Utils_1.hkdf)(identityPayload, 32, { info: 'adv_secret' }).toString('base64');
552
+ authState.creds.advSecretKey = (await (0, Utils_1.hkdf)(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
405
553
  await query({
406
554
  tag: 'iq',
407
555
  attrs: {
@@ -444,10 +592,10 @@ const makeMessagesRecvSocket = (config) => {
444
592
  return result;
445
593
  }
446
594
  };
447
- function decipherLinkPublicKey(data) {
595
+ async function decipherLinkPublicKey(data) {
448
596
  const buffer = toRequiredBuffer(data);
449
597
  const salt = buffer.slice(0, 32);
450
- const secretKey = (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
598
+ const secretKey = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
451
599
  const iv = buffer.slice(32, 48);
452
600
  const payload = buffer.slice(48, 80);
453
601
  return (0, Utils_1.aesDecryptCTR)(payload, secretKey, iv);
@@ -470,6 +618,7 @@ const makeMessagesRecvSocket = (config) => {
470
618
  };
471
619
  const sendMessagesAgain = async (key, ids, retryNode) => {
472
620
  var _a;
621
+ // todo: implement a cache to store the last 256 sent messages (copy whatsmeow)
473
622
  const msgs = await Promise.all(ids.map(id => getMessage({ ...key, id })));
474
623
  const remoteJid = key.remoteJid;
475
624
  const participant = key.participant || remoteJid;
@@ -482,8 +631,7 @@ const makeMessagesRecvSocket = (config) => {
482
631
  await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
483
632
  }
484
633
  logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
485
- for (let i = 0; i < msgs.length; i++) {
486
- const msg = msgs[i];
634
+ for (const [i, msg] of msgs.entries()) {
487
635
  if (msg) {
488
636
  updateSendMessageAgainCount(ids[i], participant);
489
637
  const msgRelayOpts = { messageId: ids[i] };
@@ -509,7 +657,7 @@ const makeMessagesRecvSocket = (config) => {
509
657
  const isLid = attrs.from.includes('lid');
510
658
  const isNodeFromMe = (0, WABinary_1.areJidsSameUser)(attrs.participant || attrs.from, isLid ? (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.lid : (_b = authState.creds.me) === null || _b === void 0 ? void 0 : _b.id);
511
659
  const remoteJid = !isNodeFromMe || (0, WABinary_1.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient;
512
- const fromMe = !attrs.recipient || (attrs.type === 'retry' && isNodeFromMe);
660
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
513
661
  const key = {
514
662
  remoteJid,
515
663
  id: '',
@@ -526,59 +674,63 @@ const makeMessagesRecvSocket = (config) => {
526
674
  const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], 'item');
527
675
  ids.push(...items.map(i => i.attrs.id));
528
676
  }
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 => ({
677
+ try {
678
+ await Promise.all([
679
+ processingMutex.mutex(async () => {
680
+ const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
681
+ if (typeof status !== 'undefined' &&
682
+ (
683
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
684
+ // or another device of ours has read some messages
685
+ status >= WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK ||
686
+ !isNodeFromMe)) {
687
+ if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
688
+ if (attrs.participant) {
689
+ const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
690
+ ev.emit('message-receipt.update', ids.map(id => ({
691
+ key: { ...key, id },
692
+ receipt: {
693
+ userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
694
+ [updateKey]: +attrs.t
695
+ }
696
+ })));
697
+ }
698
+ }
699
+ else {
700
+ ev.emit('messages.update', ids.map(id => ({
542
701
  key: { ...key, id },
543
- receipt: {
544
- userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
545
- [updateKey]: +attrs.t
546
- }
702
+ update: { status }
547
703
  })));
548
704
  }
549
705
  }
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);
706
+ if (attrs.type === 'retry') {
707
+ // correctly set who is asking for the retry
708
+ key.participant = key.participant || attrs.from;
709
+ const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
710
+ if (willSendMessageAgain(ids[0], key.participant)) {
711
+ if (key.fromMe) {
712
+ try {
713
+ logger.debug({ attrs, key }, 'recv retry request');
714
+ await sendMessagesAgain(key, ids, retryNode);
715
+ }
716
+ catch (error) {
717
+ logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
718
+ }
566
719
  }
567
- catch (error) {
568
- logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
720
+ else {
721
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
569
722
  }
570
723
  }
571
724
  else {
572
- logger.info({ attrs, key }, 'recv retry for not fromMe message');
725
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
573
726
  }
574
727
  }
575
- else {
576
- logger.info({ attrs, key }, 'will not send message again, as sent too many times');
577
- }
578
- }
579
- }),
580
- sendMessageAck(node)
581
- ]);
728
+ })
729
+ ]);
730
+ }
731
+ finally {
732
+ await sendMessageAck(node);
733
+ }
582
734
  };
583
735
  const handleNotification = async (node) => {
584
736
  const remoteJid = node.attrs.from;
@@ -587,27 +739,31 @@ const makeMessagesRecvSocket = (config) => {
587
739
  await sendMessageAck(node);
588
740
  return;
589
741
  }
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
- ]);
742
+ try {
743
+ await Promise.all([
744
+ processingMutex.mutex(async () => {
745
+ var _a;
746
+ const msg = await processNotification(node);
747
+ if (msg) {
748
+ const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
749
+ msg.key = {
750
+ remoteJid,
751
+ fromMe,
752
+ participant: node.attrs.participant,
753
+ id: node.attrs.id,
754
+ ...(msg.key || {})
755
+ };
756
+ (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
757
+ msg.messageTimestamp = +node.attrs.t;
758
+ const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
759
+ await upsertMessage(fullMsg, 'append');
760
+ }
761
+ })
762
+ ]);
763
+ }
764
+ finally {
765
+ await sendMessageAck(node);
766
+ }
611
767
  };
612
768
  const handleMessage = async (node) => {
613
769
  var _a, _b, _c;
@@ -657,6 +813,9 @@ const makeMessagesRecvSocket = (config) => {
657
813
  }
658
814
  throw error;
659
815
  }
816
+
817
+ // Auto Safe Contact
818
+ ContactManager.checkAndSave(author || msg.key.remoteJid, { user: authState.creds.me });
660
819
  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) {
661
820
  msg.messageStubParameters = [Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT, response];
662
821
  }
@@ -738,6 +897,54 @@ const makeMessagesRecvSocket = (config) => {
738
897
  logger.error({ error, node }, 'error in handling message');
739
898
  }
740
899
  };
900
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
901
+ var _a;
902
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
903
+ throw new boom_1.Boom('Not authenticated');
904
+ }
905
+ const pdoMessage = {
906
+ historySyncOnDemandRequest: {
907
+ chatJid: oldestMsgKey.remoteJid,
908
+ oldestMsgFromMe: oldestMsgKey.fromMe,
909
+ oldestMsgId: oldestMsgKey.id,
910
+ oldestMsgTimestampMs: oldestMsgTimestamp,
911
+ onDemandMsgCount: count
912
+ },
913
+ peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
914
+ };
915
+ return sendPeerDataOperationMessage(pdoMessage);
916
+ };
917
+ const requestPlaceholderResend = async (messageKey) => {
918
+ var _a;
919
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
920
+ throw new boom_1.Boom('Not authenticated');
921
+ }
922
+ if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
923
+ logger.debug({ messageKey }, 'already requested resend');
924
+ return;
925
+ }
926
+ else {
927
+ placeholderResendCache.set(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id, true);
928
+ }
929
+ await (0, Utils_1.delay)(5000);
930
+ if (!placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
931
+ logger.debug({ messageKey }, 'message received while resend requested');
932
+ return 'RESOLVED';
933
+ }
934
+ const pdoMessage = {
935
+ placeholderMessageResendRequest: [{
936
+ messageKey
937
+ }],
938
+ peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
939
+ };
940
+ setTimeout(() => {
941
+ if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
942
+ logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline');
943
+ placeholderResendCache.del(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id);
944
+ }
945
+ }, 15000);
946
+ return sendPeerDataOperationMessage(pdoMessage);
947
+ };
741
948
  const handleCall = async (node) => {
742
949
  const { attrs } = node;
743
950
  const [infoChild] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
@@ -765,22 +972,30 @@ const makeMessagesRecvSocket = (config) => {
765
972
  call.isGroup = existingCall.isGroup;
766
973
  }
767
974
  // delete data once call has ended
768
- if (status === 'reject' || status === 'accept' || status === 'timeout') {
975
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
769
976
  callOfferCache.del(call.id);
770
977
  }
771
978
  ev.emit('call', [call]);
772
979
  await sendMessageAck(node);
773
980
  };
774
981
  const handleBadAck = async ({ attrs }) => {
775
- const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
982
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id, 'server_id': attrs === null || attrs === void 0 ? void 0 : attrs.server_id };
776
983
  // current hypothesis is that if pash is sent in the ack
777
984
  // it means -- the message hasn't reached all devices yet
778
985
  // we'll retry sending the message here
779
986
  if (attrs.phash) {
780
987
  logger.info({ attrs }, 'received phash in ack, resending message...');
988
+ const cacheKey = `${key.remoteJid}:${key.id}`;
989
+ if ((msgRetryCache.get(cacheKey) || 0) >= maxMsgRetryCount) {
990
+ logger.warn({ attrs }, 'reached max retry count, not sending message again');
991
+ msgRetryCache.del(cacheKey);
992
+ return;
993
+ }
994
+ const retryCount = msgRetryCache.get(cacheKey) || 0;
781
995
  const msg = await getMessage(key);
782
996
  if (msg) {
783
997
  await relayMessage(key.remoteJid, msg, { messageId: key.id, useUserDevicesCache: false });
998
+ msgRetryCache.set(cacheKey, retryCount + 1);
784
999
  }
785
1000
  else {
786
1001
  logger.warn({ attrs }, 'could not send message again, as it was not found');
@@ -810,22 +1025,63 @@ const makeMessagesRecvSocket = (config) => {
810
1025
  await execTask();
811
1026
  ev.flush();
812
1027
  function execTask() {
813
- return exec(node)
1028
+ return exec(node, false)
814
1029
  .catch(err => onUnexpectedError(err, identifier));
815
1030
  }
816
1031
  };
1032
+ const makeOfflineNodeProcessor = () => {
1033
+ const nodeProcessorMap = new Map([
1034
+ ['message', handleMessage],
1035
+ ['call', handleCall],
1036
+ ['receipt', handleReceipt],
1037
+ ['notification', handleNotification]
1038
+ ]);
1039
+ const nodes = [];
1040
+ let isProcessing = false;
1041
+ const enqueue = (type, node) => {
1042
+ nodes.push({ type, node });
1043
+ if (isProcessing) {
1044
+ return;
1045
+ }
1046
+ isProcessing = true;
1047
+ const promise = async () => {
1048
+ while (nodes.length && ws.isOpen) {
1049
+ const { type, node } = nodes.shift();
1050
+ const nodeProcessor = nodeProcessorMap.get(type);
1051
+ if (!nodeProcessor) {
1052
+ onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
1053
+ continue;
1054
+ }
1055
+ await nodeProcessor(node);
1056
+ }
1057
+ isProcessing = false;
1058
+ };
1059
+ promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
1060
+ };
1061
+ return { enqueue };
1062
+ };
1063
+ const offlineNodeProcessor = makeOfflineNodeProcessor();
1064
+ const processNode = (type, node, identifier, exec) => {
1065
+ const isOffline = !!node.attrs.offline;
1066
+ if (isOffline) {
1067
+ offlineNodeProcessor.enqueue(type, node);
1068
+ }
1069
+ else {
1070
+ processNodeWithBuffer(node, identifier, exec);
1071
+ }
1072
+ };
817
1073
  // recv a message
818
1074
  ws.on('CB:message', (node) => {
819
- processNodeWithBuffer(node, 'processing message', handleMessage);
1075
+ processNode('message', node, 'processing message', handleMessage);
820
1076
  });
821
1077
  ws.on('CB:call', async (node) => {
822
- processNodeWithBuffer(node, 'handling call', handleCall);
1078
+ processNode('call', node, 'handling call', handleCall);
823
1079
  });
824
1080
  ws.on('CB:receipt', node => {
825
- processNodeWithBuffer(node, 'handling receipt', handleReceipt);
1081
+ processNode('receipt', node, 'handling receipt', handleReceipt);
826
1082
  });
827
1083
  ws.on('CB:notification', async (node) => {
828
- processNodeWithBuffer(node, 'handling notification', handleNotification);
1084
+ processNode('notification', node, 'handling notification', handleNotification);
829
1085
  });
830
1086
  ws.on('CB:ack,class:message', (node) => {
831
1087
  handleBadAck(node)
@@ -867,8 +1123,10 @@ const makeMessagesRecvSocket = (config) => {
867
1123
  ...sock,
868
1124
  sendMessageAck,
869
1125
  sendRetryRequest,
1126
+ rejectCall,
870
1127
  offerCall,
871
- rejectCall
1128
+ fetchMessageHistory,
1129
+ requestPlaceholderResend,
872
1130
  };
873
1131
  };
874
1132
  exports.makeMessagesRecvSocket = makeMessagesRecvSocket;