amiudmodz 4.0.0

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 (100) hide show
  1. package/WAProto/index.js +169661 -0
  2. package/engine-requirements.js +10 -0
  3. package/lib/Defaults/baileys-version.json +3 -0
  4. package/lib/Defaults/index.js +156 -0
  5. package/lib/Defaults/phonenumber-mcc.json +223 -0
  6. package/lib/Signal/Group/ciphertext-message.js +15 -0
  7. package/lib/Signal/Group/group-session-builder.js +64 -0
  8. package/lib/Signal/Group/group_cipher.js +96 -0
  9. package/lib/Signal/Group/index.js +57 -0
  10. package/lib/Signal/Group/keyhelper.js +55 -0
  11. package/lib/Signal/Group/queue-job.js +57 -0
  12. package/lib/Signal/Group/sender-chain-key.js +34 -0
  13. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  14. package/lib/Signal/Group/sender-key-message.js +69 -0
  15. package/lib/Signal/Group/sender-key-name.js +51 -0
  16. package/lib/Signal/Group/sender-key-record.js +53 -0
  17. package/lib/Signal/Group/sender-key-state.js +99 -0
  18. package/lib/Signal/Group/sender-message-key.js +29 -0
  19. package/lib/Signal/libsignal.js +177 -0
  20. package/lib/Signal/lid-mapping.js +185 -0
  21. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  22. package/lib/Socket/Client/index.js +19 -0
  23. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  24. package/lib/Socket/Client/web-socket-client.js +66 -0
  25. package/lib/Socket/business.js +260 -0
  26. package/lib/Socket/chats.js +1066 -0
  27. package/lib/Socket/groupStatus.js +637 -0
  28. package/lib/Socket/groups.js +317 -0
  29. package/lib/Socket/index.js +11 -0
  30. package/lib/Socket/messages-recv.js +1112 -0
  31. package/lib/Socket/messages-send.js +807 -0
  32. package/lib/Socket/newsletter.js +73 -0
  33. package/lib/Socket/registration.js +166 -0
  34. package/lib/Socket/socket.js +729 -0
  35. package/lib/Socket/usync.js +70 -0
  36. package/lib/Store/index.js +10 -0
  37. package/lib/Store/make-cache-manager-store.js +83 -0
  38. package/lib/Store/make-in-memory-store.js +427 -0
  39. package/lib/Store/make-ordered-dictionary.js +81 -0
  40. package/lib/Store/object-repository.js +27 -0
  41. package/lib/Types/Auth.js +2 -0
  42. package/lib/Types/Call.js +2 -0
  43. package/lib/Types/Chat.js +4 -0
  44. package/lib/Types/Contact.js +2 -0
  45. package/lib/Types/Events.js +2 -0
  46. package/lib/Types/GroupMetadata.js +2 -0
  47. package/lib/Types/Label.js +27 -0
  48. package/lib/Types/LabelAssociation.js +9 -0
  49. package/lib/Types/Message.js +9 -0
  50. package/lib/Types/Newsletter.js +38 -0
  51. package/lib/Types/Product.js +2 -0
  52. package/lib/Types/Signal.js +2 -0
  53. package/lib/Types/Socket.js +2 -0
  54. package/lib/Types/State.js +2 -0
  55. package/lib/Types/USync.js +2 -0
  56. package/lib/Types/index.js +42 -0
  57. package/lib/Utils/auth-utils.js +206 -0
  58. package/lib/Utils/baileys-event-stream.js +63 -0
  59. package/lib/Utils/business.js +234 -0
  60. package/lib/Utils/chat-utils.js +729 -0
  61. package/lib/Utils/crypto.js +151 -0
  62. package/lib/Utils/decode-wa-message.js +198 -0
  63. package/lib/Utils/event-buffer.js +525 -0
  64. package/lib/Utils/generics.js +502 -0
  65. package/lib/Utils/history.js +96 -0
  66. package/lib/Utils/index.js +33 -0
  67. package/lib/Utils/link-preview.js +93 -0
  68. package/lib/Utils/logger.js +7 -0
  69. package/lib/Utils/lt-hash.js +51 -0
  70. package/lib/Utils/make-mutex.js +43 -0
  71. package/lib/Utils/messages-media.js +814 -0
  72. package/lib/Utils/messages.js +819 -0
  73. package/lib/Utils/noise-handler.js +155 -0
  74. package/lib/Utils/process-message.js +321 -0
  75. package/lib/Utils/signal.js +153 -0
  76. package/lib/Utils/use-multi-file-auth-state.js +126 -0
  77. package/lib/Utils/validate-connection.js +222 -0
  78. package/lib/WABinary/constants.js +1304 -0
  79. package/lib/WABinary/decode.js +283 -0
  80. package/lib/WABinary/encode.js +263 -0
  81. package/lib/WABinary/generic-utils.js +198 -0
  82. package/lib/WABinary/index.js +21 -0
  83. package/lib/WABinary/jid-utils.js +62 -0
  84. package/lib/WABinary/types.js +2 -0
  85. package/lib/WAM/BinaryInfo.js +13 -0
  86. package/lib/WAM/constants.js +15350 -0
  87. package/lib/WAM/encode.js +155 -0
  88. package/lib/WAM/index.js +19 -0
  89. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  90. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  91. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  92. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  93. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  94. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  95. package/lib/WAUSync/Protocols/index.js +20 -0
  96. package/lib/WAUSync/USyncQuery.js +89 -0
  97. package/lib/WAUSync/USyncUser.js +26 -0
  98. package/lib/WAUSync/index.js +19 -0
  99. package/lib/index.js +39 -0
  100. package/package.json +93 -0
@@ -0,0 +1,1112 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeMessagesRecvSocket = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const crypto_1 = require("crypto");
9
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
10
+ const WAProto_1 = require("../../WAProto");
11
+ const Defaults_1 = require("../Defaults");
12
+ const Types_1 = require("../Types");
13
+ const Utils_1 = require("../Utils");
14
+ const make_mutex_1 = require("../Utils/make-mutex");
15
+ const WABinary_1 = require("../WABinary");
16
+ const groups_1 = require("./groups");
17
+ const messages_send_1 = require("./messages-send");
18
+ const makeMessagesRecvSocket = (config) => {
19
+ const {
20
+ logger,
21
+ retryRequestDelayMs,
22
+ maxMsgRetryCount,
23
+ getMessage,
24
+ shouldIgnoreJid
25
+ } = config;
26
+ const sock = (0, messages_send_1.makeMessagesSocket)(config);
27
+ const {
28
+ ev,
29
+ authState,
30
+ ws,
31
+ processingMutex,
32
+ signalRepository,
33
+ query,
34
+ upsertMessage,
35
+ resyncAppState,
36
+ groupMetadata,
37
+ onUnexpectedError,
38
+ assertSessions,
39
+ sendNode,
40
+ relayMessage,
41
+ sendReceipt,
42
+ uploadPreKeys,
43
+ createParticipantNodes,
44
+ getUSyncDevices,
45
+ sendPeerDataOperationMessage
46
+ } = sock;
47
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
48
+ const retryMutex = (0, make_mutex_1.makeMutex)();
49
+ const msgRetryCache = config.msgRetryCounterCache || new node_cache_1.default({
50
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
51
+ useClones: false
52
+ });
53
+ const callOfferCache = config.callOfferCache || new node_cache_1.default({
54
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER,
55
+ useClones: false
56
+ });
57
+ const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
58
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
59
+ useClones: false
60
+ });
61
+ let sendActiveReceipts = false;
62
+ const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
63
+ const stanza = {
64
+ tag: 'ack',
65
+ attrs: {
66
+ id: attrs.id,
67
+ to: attrs.from,
68
+ class: tag
69
+ }
70
+ }
71
+ if (!!errorCode) {
72
+ stanza.attrs.error = errorCode.toString();
73
+ }
74
+ if (!!attrs.participant) {
75
+ stanza.attrs.participant = attrs.participant;
76
+ }
77
+ if (!!attrs.recipient) {
78
+ stanza.attrs.recipient = attrs.recipient;
79
+ }
80
+ if (!!attrs.type && (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
81
+ stanza.attrs.type = attrs.type;
82
+ }
83
+ if (tag === 'message' && (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable')) {
84
+ stanza.attrs.from = authState.creds.me.id;
85
+ }
86
+ logger.debug({
87
+ recv: {
88
+ tag,
89
+ attrs
90
+ },
91
+ sent: stanza.attrs
92
+ }, 'sent ack');
93
+ await sendNode(stanza);
94
+ };
95
+ const offerCall = async (toJid, isVideo = false) => {
96
+ const callId = (0, crypto_1.randomBytes)(16).toString('hex').toUpperCase().substring(0, 64);
97
+ const offerContent = [];
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
+ });
112
+ if (isVideo) {
113
+ offerContent.push({
114
+ tag: 'video',
115
+ attrs: {
116
+ orientation: '0',
117
+ 'screen_width': '1920',
118
+ 'screen_height': '1080',
119
+ 'device_orientation': '0',
120
+ enc: 'vp8',
121
+ dec: 'vp8',
122
+ }
123
+ });
124
+ }
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
+ });
137
+ offerContent.push({
138
+ tag: 'encopt',
139
+ attrs: {
140
+ keygen: '2'
141
+ }, content: undefined
142
+ })
143
+ const encKey = (0, crypto_1.randomBytes)(32);
144
+ const devices = (await getUSyncDevices([toJid], true, false)).map(({ user, device }) => (0, WABinary_1.jidEncode)(user, 's.whatsapp.net', device));
145
+ await assertSessions(devices, true);
146
+ const { nodes: destinations, shouldIncludeDeviceIdentity } = await createParticipantNodes(devices, {
147
+ call: {
148
+ callKey: encKey
149
+ }
150
+ });
151
+ offerContent.push({ tag: 'destination', attrs: {}, content: destinations });
152
+ if (shouldIncludeDeviceIdentity) {
153
+ offerContent.push({
154
+ tag: 'device-identity',
155
+ attrs: {},
156
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
157
+ });
158
+ }
159
+ const stanza = ({
160
+ tag: 'call',
161
+ attrs: {
162
+ to: toJid,
163
+ },
164
+ content: [{
165
+ tag: 'offer',
166
+ attrs: {
167
+ 'call-id': callId,
168
+ 'call-creator': authState.creds.me.id,
169
+ },
170
+ content: offerContent,
171
+ }],
172
+ });
173
+ await query(stanza);
174
+ return {
175
+ callId,
176
+ toJid,
177
+ isVideo,
178
+ };
179
+ };
180
+ const rejectCall = async (callId, callFrom) => {
181
+ const stanza = ({
182
+ tag: 'call',
183
+ attrs: {
184
+ from: authState.creds.me.id,
185
+ to: callFrom,
186
+ },
187
+ content: [{
188
+ tag: 'reject',
189
+ attrs: {
190
+ 'call-id': callId,
191
+ 'call-creator': callFrom,
192
+ count: '0',
193
+ },
194
+ content: undefined,
195
+ }],
196
+ });
197
+ await query(stanza);
198
+ };
199
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
200
+ const { fullMessage } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '');
201
+ const { key: msgKey } = fullMessage;
202
+ const msgId = msgKey.id;
203
+ const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
204
+ let retryCount = msgRetryCache.get(key) || 0;
205
+ if (retryCount >= maxMsgRetryCount) {
206
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
207
+ msgRetryCache.del(key);
208
+ return;
209
+ }
210
+ retryCount += 1;
211
+ msgRetryCache.set(key, retryCount);
212
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
213
+ if (retryCount === 1) {
214
+ //request a resend via phone
215
+ const msgId = await requestPlaceholderResend(msgKey);
216
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
217
+ }
218
+ const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
219
+ await authState.keys.transaction(async () => {
220
+ const receipt = {
221
+ tag: 'receipt',
222
+ attrs: {
223
+ id: msgId,
224
+ type: 'retry',
225
+ to: node.attrs.from
226
+ },
227
+ content: [
228
+ {
229
+ tag: 'retry',
230
+ attrs: {
231
+ count: retryCount.toString(),
232
+ id: node.attrs.id,
233
+ t: node.attrs.t,
234
+ v: '1'
235
+ }
236
+ },
237
+ {
238
+ tag: 'registration',
239
+ attrs: {},
240
+ content: (0, Utils_1.encodeBigEndian)(authState.creds.registrationId)
241
+ }
242
+ ]
243
+ };
244
+ if (node.attrs.recipient) {
245
+ receipt.attrs.recipient = node.attrs.recipient;
246
+ }
247
+ if (node.attrs.participant) {
248
+ receipt.attrs.participant = node.attrs.participant;
249
+ }
250
+ if (retryCount > 1 || forceIncludeKeys) {
251
+ const { update, preKeys } = await (0, Utils_1.getNextPreKeys)(authState, 1);
252
+ const [keyId] = Object.keys(preKeys);
253
+ const key = preKeys[+keyId];
254
+ const content = receipt.content;
255
+ content.push({
256
+ tag: 'keys',
257
+ attrs: {},
258
+ content: [
259
+ { tag: 'type', attrs: {}, content: Buffer.from(Defaults_1.KEY_BUNDLE_TYPE) },
260
+ { tag: 'identity', attrs: {}, content: identityKey.public },
261
+ (0, Utils_1.xmppPreKey)(key, +keyId),
262
+ (0, Utils_1.xmppSignedPreKey)(signedPreKey),
263
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
264
+ ]
265
+ });
266
+ ev.emit('creds.update', update);
267
+ }
268
+ await sendNode(receipt);
269
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
270
+ });
271
+ };
272
+ const handleEncryptNotification = async (node) => {
273
+ const from = node.attrs.from;
274
+ if (from === WABinary_1.S_WHATSAPP_NET) {
275
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(node, 'count');
276
+ const count = +countChild.attrs.value;
277
+ const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT;
278
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
279
+ if (shouldUploadMorePreKeys) {
280
+ await uploadPreKeys();
281
+ }
282
+ }
283
+ else {
284
+ const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, 'identity');
285
+ if (identityNode) {
286
+ logger.info({ jid: from }, 'identity changed');
287
+
288
+
289
+ }
290
+ else {
291
+ logger.info({ node }, 'unknown encrypt notification');
292
+ }
293
+ }
294
+ };
295
+ const handleGroupNotification = (participant, child, msg) => {
296
+ var _a, _b, _c, _d;
297
+ 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;
298
+ switch (child === null || child === void 0 ? void 0 : child.tag) {
299
+ case 'create':
300
+ const metadata = (0, groups_1.extractGroupMetadata)(child);
301
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
302
+ msg.messageStubParameters = [metadata.subject];
303
+ msg.key = { participant: metadata.owner };
304
+ ev.emit('chats.upsert', [{
305
+ id: metadata.id,
306
+ name: metadata.subject,
307
+ conversationTimestamp: metadata.creation,
308
+ }]);
309
+ ev.emit('groups.upsert', [{
310
+ ...metadata,
311
+ author: participant
312
+ }]);
313
+ break;
314
+ case 'ephemeral':
315
+ case 'not_ephemeral':
316
+ msg.message = {
317
+ protocolMessage: {
318
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
319
+ ephemeralExpiration: +(child.attrs.expiration || 0)
320
+ }
321
+ };
322
+ break;
323
+ case 'modify':
324
+ const oldNumber = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
325
+ msg.messageStubParameters = oldNumber || [];
326
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
327
+ break;
328
+ case 'promote':
329
+ case 'demote':
330
+ case 'remove':
331
+ case 'add':
332
+ case 'leave':
333
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
334
+ msg.messageStubType = Types_1.WAMessageStubType[stubType];
335
+ const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
336
+ if (participants.length === 1 &&
337
+
338
+
339
+ (0, WABinary_1.areJidsSameUser)(participants[0], participant) &&
340
+ child.tag === 'remove') {
341
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
342
+ }
343
+ msg.messageStubParameters = participants;
344
+ break;
345
+ case 'subject':
346
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
347
+ msg.messageStubParameters = [child.attrs.subject];
348
+ break;
349
+ case 'description':
350
+ 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();
351
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
352
+ msg.messageStubParameters = description ? [description] : undefined;
353
+ break;
354
+ case 'announcement':
355
+ case 'not_announcement':
356
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
357
+ msg.messageStubParameters = [(child.tag === 'announcement') ? 'on' : 'off'];
358
+ break;
359
+ case 'locked':
360
+ case 'unlocked':
361
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT;
362
+ msg.messageStubParameters = [(child.tag === 'locked') ? 'on' : 'off'];
363
+ break;
364
+ case 'invite':
365
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
366
+ msg.messageStubParameters = [child.attrs.code];
367
+ break;
368
+ case 'member_add_mode':
369
+ const addMode = child.content;
370
+ if (addMode) {
371
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE;
372
+ msg.messageStubParameters = [addMode.toString()];
373
+ }
374
+ break;
375
+ case 'membership_approval_mode':
376
+ const approvalMode = (0, WABinary_1.getBinaryNodeChild)(child, 'group_join');
377
+ if (approvalMode) {
378
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
379
+ msg.messageStubParameters = [approvalMode.attrs.state];
380
+ }
381
+ break;
382
+ case 'created_membership_requests':
383
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
384
+ msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method];
385
+ break;
386
+ case 'revoked_membership_requests':
387
+ const isDenied = (0, WABinary_1.areJidsSameUser)(participantJid, participant);
388
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
389
+ msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected'];
390
+ break;
391
+ break;
392
+ default:
393
+
394
+ }
395
+ };
396
+ const handleNewsletterNotification = (id, node) => {
397
+ const messages = (0, WABinary_1.getBinaryNodeChild)(node, 'messages');
398
+ const message = (0, WABinary_1.getBinaryNodeChild)(messages, 'message');
399
+ const serverId = message.attrs.server_id;
400
+ const reactionsList = (0, WABinary_1.getBinaryNodeChild)(message, 'reactions');
401
+ const viewsList = (0, WABinary_1.getBinaryNodeChildren)(message, 'views_count');
402
+ if (reactionsList) {
403
+ const reactions = (0, WABinary_1.getBinaryNodeChildren)(reactionsList, 'reaction');
404
+ if (reactions.length === 0) {
405
+ ev.emit('newsletter.reaction', { id, 'server_id': serverId, reaction: { removed: true } });
406
+ }
407
+ reactions.forEach(item => {
408
+ var _a, _b;
409
+ 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) } });
410
+ });
411
+ }
412
+ if (viewsList.length) {
413
+ viewsList.forEach(item => {
414
+ ev.emit('newsletter.view', { id, 'server_id': serverId, count: +item.attrs.count });
415
+ });
416
+ }
417
+ };
418
+ const handleMexNewsletterNotification = (id, node) => {
419
+ var _a;
420
+ const operation = node === null || node === void 0 ? void 0 : node.attrs.op_name;
421
+ const content = JSON.parse((_a = node === null || node === void 0 ? void 0 : node.content) === null || _a === void 0 ? void 0 : _a.toString());
422
+ let contentPath;
423
+ if (operation === Types_1.MexOperations.PROMOTE || operation === Types_1.MexOperations.DEMOTE) {
424
+ let action;
425
+ if (operation === Types_1.MexOperations.PROMOTE) {
426
+ action = 'promote';
427
+ contentPath = content.data[Types_1.XWAPaths.PROMOTE];
428
+ }
429
+ if (operation === Types_1.MexOperations.DEMOTE) {
430
+ action = 'demote';
431
+ contentPath = content.data[Types_1.XWAPaths.DEMOTE];
432
+ }
433
+ ev.emit('newsletter-participants.update', { id, author: contentPath.actor.pn, user: contentPath.user.pn, new_role: contentPath.user_new_role, action });
434
+ }
435
+ if (operation === Types_1.MexOperations.UPDATE) {
436
+ contentPath = content.data[Types_1.XWAPaths.METADATA_UPDATE];
437
+ ev.emit('newsletter-settings.update', { id, update: contentPath.thread_metadata.settings });
438
+ }
439
+ };
440
+ const processNotification = async (node) => {
441
+ var _a, _b;
442
+ const result = {};
443
+ const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
444
+ const nodeType = node.attrs.type;
445
+ const from = (0, WABinary_1.jidNormalizedUser)(node.attrs.from);
446
+ switch (nodeType) {
447
+ case 'privacy_token':
448
+ const tokenList = (0, WABinary_1.getBinaryNodeChildren)(child, 'token');
449
+ for (const { attrs, content } of tokenList) {
450
+ const jid = attrs.jid;
451
+ ev.emit('chats.update', [
452
+ {
453
+ id: jid,
454
+ tcToken: content
455
+ }
456
+ ]);
457
+ logger.debug({ jid }, 'got privacy token update');
458
+ }
459
+ break;
460
+ case 'newsletter':
461
+ handleNewsletterNotification(node.attrs.from, child);
462
+ break;
463
+ case 'mex':
464
+ handleMexNewsletterNotification(node.attrs.from, child);
465
+ break;
466
+ case 'w:gp2':
467
+ handleGroupNotification(node.attrs.participant, child, result);
468
+ break;
469
+ case 'mediaretry':
470
+ const event = (0, Utils_1.decodeMediaRetryNode)(node);
471
+ ev.emit('messages.media-update', [event]);
472
+ break;
473
+ case 'encrypt':
474
+ await handleEncryptNotification(node);
475
+ break;
476
+ case 'devices':
477
+ const devices = (0, WABinary_1.getBinaryNodeChildren)(child, 'device');
478
+ if ((0, WABinary_1.areJidsSameUser)(child.attrs.jid, authState.creds.me.id)) {
479
+ const deviceJids = devices.map(d => d.attrs.jid);
480
+ logger.info({ deviceJids }, 'got my own devices');
481
+ }
482
+ break;
483
+ case 'server_sync':
484
+ const update = (0, WABinary_1.getBinaryNodeChild)(node, 'collection');
485
+ if (update) {
486
+ const name = update.attrs.name;
487
+ await resyncAppState([name], false);
488
+ }
489
+ break;
490
+ case 'picture':
491
+ const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set');
492
+ const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete');
493
+ ev.emit('contacts.update', [{
494
+ id: from || ((_b = (_a = (setPicture || delPicture)) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.hash) || '',
495
+ imgUrl: setPicture ? 'changed' : 'removed'
496
+ }]);
497
+ if ((0, WABinary_1.isJidGroup)(from)) {
498
+ const node = setPicture || delPicture;
499
+ result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON;
500
+ if (setPicture) {
501
+ result.messageStubParameters = [setPicture.attrs.id];
502
+ }
503
+ result.participant = node === null || node === void 0 ? void 0 : node.attrs.author;
504
+ result.key = {
505
+ ...result.key || {},
506
+ participant: setPicture === null || setPicture === void 0 ? void 0 : setPicture.attrs.author
507
+ };
508
+ }
509
+ break;
510
+ case 'account_sync':
511
+ if (child.tag === 'disappearing_mode') {
512
+ const newDuration = +child.attrs.duration;
513
+ const timestamp = +child.attrs.t;
514
+ logger.info({ newDuration }, 'updated account disappearing mode');
515
+ ev.emit('creds.update', {
516
+ accountSettings: {
517
+ ...authState.creds.accountSettings,
518
+ defaultDisappearingMode: {
519
+ ephemeralExpiration: newDuration,
520
+ ephemeralSettingTimestamp: timestamp,
521
+ },
522
+ }
523
+ });
524
+ }
525
+ else if (child.tag === 'blocklist') {
526
+ const blocklists = (0, WABinary_1.getBinaryNodeChildren)(child, 'item');
527
+ for (const { attrs } of blocklists) {
528
+ const blocklist = [attrs.jid];
529
+ const type = (attrs.action === 'block') ? 'add' : 'remove';
530
+ ev.emit('blocklist.update', { blocklist, type });
531
+ }
532
+ }
533
+ break;
534
+ case 'link_code_companion_reg':
535
+ const linkCodeCompanionReg = (0, WABinary_1.getBinaryNodeChild)(node, 'link_code_companion_reg');
536
+ const ref = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref'));
537
+ const primaryIdentityPublicKey = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub'));
538
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
539
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
540
+ const companionSharedKey = Utils_1.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
541
+ const random = (0, crypto_1.randomBytes)(32);
542
+ const linkCodeSalt = (0, crypto_1.randomBytes)(32);
543
+ const linkCodePairingExpanded = await (0, Utils_1.hkdf)(companionSharedKey, 32, {
544
+ salt: linkCodeSalt,
545
+ info: 'link_code_pairing_key_bundle_encryption_key'
546
+ });
547
+ const encryptPayload = Buffer.concat([Buffer.from(authState.creds.signedIdentityKey.public), primaryIdentityPublicKey, random]);
548
+ const encryptIv = (0, crypto_1.randomBytes)(12);
549
+ const encrypted = (0, Utils_1.aesEncryptGCM)(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
550
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
551
+ const identitySharedKey = Utils_1.Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
552
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
553
+ authState.creds.advSecretKey = (await (0, Utils_1.hkdf)(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
554
+ await query({
555
+ tag: 'iq',
556
+ attrs: {
557
+ to: WABinary_1.S_WHATSAPP_NET,
558
+ type: 'set',
559
+ id: sock.generateMessageTag(),
560
+ xmlns: 'md'
561
+ },
562
+ content: [
563
+ {
564
+ tag: 'link_code_companion_reg',
565
+ attrs: {
566
+ jid: authState.creds.me.id,
567
+ stage: 'companion_finish',
568
+ },
569
+ content: [
570
+ {
571
+ tag: 'link_code_pairing_wrapped_key_bundle',
572
+ attrs: {},
573
+ content: encryptedPayload
574
+ },
575
+ {
576
+ tag: 'companion_identity_public',
577
+ attrs: {},
578
+ content: authState.creds.signedIdentityKey.public
579
+ },
580
+ {
581
+ tag: 'link_code_pairing_ref',
582
+ attrs: {},
583
+ content: ref
584
+ }
585
+ ]
586
+ }
587
+ ]
588
+ });
589
+ authState.creds.registered = true;
590
+ ev.emit('creds.update', authState.creds);
591
+ }
592
+ if (Object.keys(result).length) {
593
+ return result;
594
+ }
595
+ };
596
+ async function decipherLinkPublicKey(data) {
597
+ const buffer = toRequiredBuffer(data);
598
+ const salt = buffer.slice(0, 32);
599
+ const secretKey = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
600
+ const iv = buffer.slice(32, 48);
601
+ const payload = buffer.slice(48, 80);
602
+ return (0, Utils_1.aesDecryptCTR)(payload, secretKey, iv);
603
+ }
604
+ function toRequiredBuffer(data) {
605
+ if (data === undefined) {
606
+ throw new boom_1.Boom('Invalid buffer', { statusCode: 400 });
607
+ }
608
+ return data instanceof Buffer ? data : Buffer.from(data);
609
+ }
610
+ const willSendMessageAgain = (id, participant) => {
611
+ const key = `${id}:${participant}`;
612
+ const retryCount = msgRetryCache.get(key) || 0;
613
+ return retryCount < maxMsgRetryCount;
614
+ };
615
+ const updateSendMessageAgainCount = (id, participant) => {
616
+ const key = `${id}:${participant}`;
617
+ const newValue = (msgRetryCache.get(key) || 0) + 1;
618
+ msgRetryCache.set(key, newValue);
619
+ };
620
+ const sendMessagesAgain = async (key, ids, retryNode) => {
621
+ var _a;
622
+
623
+ const msgs = await Promise.all(ids.map(id => getMessage({ ...key, id })));
624
+ const remoteJid = key.remoteJid;
625
+ const participant = key.participant || remoteJid;
626
+
627
+
628
+
629
+ const sendToAll = !((_a = (0, WABinary_1.jidDecode)(participant)) === null || _a === void 0 ? void 0 : _a.device);
630
+ await assertSessions([participant], true);
631
+ if ((0, WABinary_1.isJidGroup)(remoteJid)) {
632
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
633
+ }
634
+ logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
635
+ for (const [i, msg] of msgs.entries()) {
636
+ if (msg) {
637
+ updateSendMessageAgainCount(ids[i], participant);
638
+ const msgRelayOpts = { messageId: ids[i] };
639
+ if (sendToAll) {
640
+ msgRelayOpts.useUserDevicesCache = false;
641
+ }
642
+ else {
643
+ msgRelayOpts.participant = {
644
+ jid: participant,
645
+ count: +retryNode.attrs.count
646
+ };
647
+ }
648
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
649
+ }
650
+ else {
651
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
652
+ }
653
+ }
654
+ };
655
+ const handleReceipt = async (node) => {
656
+ var _a, _b;
657
+ const { attrs, content } = node;
658
+ const isLid = attrs.from.includes('lid');
659
+ 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);
660
+ const remoteJid = !isNodeFromMe || (0, WABinary_1.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient;
661
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
662
+ const key = {
663
+ remoteJid,
664
+ id: '',
665
+ fromMe,
666
+ participant: attrs.participant
667
+ };
668
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
669
+ logger.debug({ remoteJid }, 'ignoring receipt from jid');
670
+ await sendMessageAck(node);
671
+ return;
672
+ }
673
+ const ids = [attrs.id];
674
+ if (Array.isArray(content)) {
675
+ const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], 'item');
676
+ ids.push(...items.map(i => i.attrs.id));
677
+ }
678
+ try {
679
+ await Promise.all([
680
+ processingMutex.mutex(async () => {
681
+ const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
682
+ if (typeof status !== 'undefined' &&
683
+ (
684
+
685
+
686
+ status >= WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK ||
687
+ !isNodeFromMe)) {
688
+ if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
689
+ if (attrs.participant) {
690
+ const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
691
+ ev.emit('message-receipt.update', ids.map(id => ({
692
+ key: { ...key, id },
693
+ receipt: {
694
+ userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
695
+ [updateKey]: +attrs.t
696
+ }
697
+ })));
698
+ }
699
+ }
700
+ else {
701
+ ev.emit('messages.update', ids.map(id => ({
702
+ key: { ...key, id },
703
+ update: { status }
704
+ })));
705
+ }
706
+ }
707
+ if (attrs.type === 'retry') {
708
+
709
+ key.participant = key.participant || attrs.from;
710
+ const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
711
+ if (willSendMessageAgain(ids[0], key.participant)) {
712
+ if (key.fromMe) {
713
+ try {
714
+ logger.debug({ attrs, key }, 'recv retry request');
715
+ await sendMessagesAgain(key, ids, retryNode);
716
+ }
717
+ catch (error) {
718
+ logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
719
+ }
720
+ }
721
+ else {
722
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
723
+ }
724
+ }
725
+ else {
726
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
727
+ }
728
+ }
729
+ })
730
+ ]);
731
+ }
732
+ finally {
733
+ await sendMessageAck(node);
734
+ }
735
+ };
736
+ const handleNotification = async (node) => {
737
+ const remoteJid = node.attrs.from;
738
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
739
+ logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
740
+ await sendMessageAck(node);
741
+ return;
742
+ }
743
+ try {
744
+ await Promise.all([
745
+ processingMutex.mutex(async () => {
746
+ var _a;
747
+ const msg = await processNotification(node);
748
+ if (msg) {
749
+ const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
750
+ msg.key = {
751
+ remoteJid,
752
+ fromMe,
753
+ participant: node.attrs.participant,
754
+ id: node.attrs.id,
755
+ ...(msg.key || {})
756
+ };
757
+ (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
758
+ msg.messageTimestamp = +node.attrs.t;
759
+ const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
760
+ await upsertMessage(fullMsg, 'append');
761
+ }
762
+ })
763
+ ]);
764
+ }
765
+ finally {
766
+ await sendMessageAck(node);
767
+ }
768
+ };
769
+ const handleMessage = async (node) => {
770
+ var _a, _b, _c;
771
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== '@s.whatsapp.net') {
772
+ logger.debug({ key: node.attrs.key }, 'ignored message');
773
+ await sendMessageAck(node);
774
+ return;
775
+ }
776
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
777
+
778
+ if (encNode && encNode.attrs.type === 'msmsg') {
779
+ logger.debug({ key: node.attrs.key }, 'ignored msmsg');
780
+ await sendMessageAck(node);
781
+ return;
782
+ }
783
+ let response;
784
+ if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable') && !encNode) {
785
+ await sendMessageAck(node);
786
+ const { key } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '').fullMessage;
787
+ response = await requestPlaceholderResend(key);
788
+ if (response === 'RESOLVED') {
789
+ return;
790
+ }
791
+ logger.debug('received unavailable message, acked and requested resend from phone');
792
+ }
793
+ else {
794
+ if (placeholderResendCache.get(node.attrs.id)) {
795
+ placeholderResendCache.del(node.attrs.id);
796
+ }
797
+ }
798
+ const { fullMessage: msg, category, author, decrypt } = (0, Utils_1.decryptMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
799
+ 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) {
800
+ msg.messageStubParameters = [Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT, response];
801
+ }
802
+ 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) {
803
+ ev.emit('chats.phoneNumberShare', { lid: node.attrs.from, jid: node.attrs.sender_pn });
804
+ }
805
+ try {
806
+ await Promise.all([
807
+ processingMutex.mutex(async () => {
808
+ var _a, _b, _c, _d, _e, _f;
809
+ await decrypt();
810
+
811
+ if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
812
+ 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) {
813
+ return sendMessageAck(node, Utils_1.NACK_REASONS.ParsingError);
814
+ }
815
+ retryMutex.mutex(async () => {
816
+ if (ws.isOpen) {
817
+ if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable')) {
818
+ return;
819
+ }
820
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
821
+ await sendRetryRequest(node, !encNode);
822
+ if (retryRequestDelayMs) {
823
+ await (0, Utils_1.delay)(retryRequestDelayMs);
824
+ }
825
+ }
826
+ else {
827
+ logger.debug({ node }, 'connection closed, ignoring retry req');
828
+ }
829
+ });
830
+ }
831
+ else {
832
+
833
+ let type = undefined;
834
+ if ((_b = msg.key.participant) === null || _b === void 0 ? void 0 : _b.endsWith('@lid')) {
835
+ msg.key.participant = node.attrs.participant_pn || authState.creds.me.id;
836
+ }
837
+ if ((0, WABinary_1.isJidGroup)(msg.key.remoteJid) && ((_f = (_e = (_d = (_c = msg.message) === null || _c === void 0 ? void 0 : _c.extendedTextMessage) === null || _d === void 0 ? void 0 : _d.contextInfo) === null || _e === void 0 ? void 0 : _e.participant) === null || _f === void 0 ? void 0 : _f.endsWith('@lid'))) {
838
+ if (msg.message.extendedTextMessage.contextInfo) {
839
+ const metadata = await groupMetadata(msg.key.remoteJid);
840
+ const sender = msg.message.extendedTextMessage.contextInfo.participant;
841
+ const found = metadata.participants.find(p => p.id === sender);
842
+ msg.message.extendedTextMessage.contextInfo.participant = (found === null || found === void 0 ? void 0 : found.jid) || sender;
843
+ }
844
+ }
845
+ if (!(0, WABinary_1.isJidGroup)(msg.key.remoteJid) && (0, WABinary_1.isLidUser)(msg.key.remoteJid)) {
846
+ msg.key.remoteJid = node.attrs.sender_pn || node.attrs.peer_recipient_pn;
847
+ }
848
+ let participant = msg.key.participant;
849
+ if (category === 'peer') {
850
+ type = 'peer_msg';
851
+ }
852
+ else if (msg.key.fromMe) {
853
+ type = 'sender';
854
+
855
+ if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
856
+ participant = author;
857
+ }
858
+ }
859
+ else if (!sendActiveReceipts) {
860
+ type = 'inactive';
861
+ }
862
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
863
+
864
+ const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
865
+ if (isAnyHistoryMsg) {
866
+ const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
867
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
868
+ }
869
+ }
870
+ (0, Utils_1.cleanMessage)(msg, authState.creds.me.id);
871
+ await sendMessageAck(node);
872
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
873
+ })
874
+ ]);
875
+ }
876
+ catch (error) {
877
+ logger.error({ error, node }, 'error in handling message');
878
+ }
879
+ };
880
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
881
+ var _a;
882
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
883
+ throw new boom_1.Boom('Not authenticated');
884
+ }
885
+ const pdoMessage = {
886
+ historySyncOnDemandRequest: {
887
+ chatJid: oldestMsgKey.remoteJid,
888
+ oldestMsgFromMe: oldestMsgKey.fromMe,
889
+ oldestMsgId: oldestMsgKey.id,
890
+ oldestMsgTimestampMs: oldestMsgTimestamp,
891
+ onDemandMsgCount: count
892
+ },
893
+ peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
894
+ };
895
+ return sendPeerDataOperationMessage(pdoMessage);
896
+ };
897
+ const requestPlaceholderResend = async (messageKey) => {
898
+ var _a;
899
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
900
+ throw new boom_1.Boom('Not authenticated');
901
+ }
902
+ if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
903
+ logger.debug({ messageKey }, 'already requested resend');
904
+ return;
905
+ }
906
+ else {
907
+ placeholderResendCache.set(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id, true);
908
+ }
909
+ await (0, Utils_1.delay)(5000);
910
+ if (!placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
911
+ logger.debug({ messageKey }, 'message received while resend requested');
912
+ return 'RESOLVED';
913
+ }
914
+ const pdoMessage = {
915
+ placeholderMessageResendRequest: [{
916
+ messageKey
917
+ }],
918
+ peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
919
+ };
920
+ setTimeout(() => {
921
+ if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
922
+ logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline');
923
+ placeholderResendCache.del(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id);
924
+ }
925
+ }, 15000);
926
+ return sendPeerDataOperationMessage(pdoMessage);
927
+ };
928
+ const handleCall = async (node) => {
929
+ const { attrs } = node;
930
+ const [infoChild] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
931
+ const callId = infoChild.attrs['call-id'];
932
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
933
+ const status = (0, Utils_1.getCallStatusFromNode)(infoChild);
934
+ const call = {
935
+ chatId: attrs.from,
936
+ from,
937
+ id: callId,
938
+ date: new Date(+attrs.t * 1000),
939
+ offline: !!attrs.offline,
940
+ status,
941
+ };
942
+ if (status === 'offer') {
943
+ call.isVideo = !!(0, WABinary_1.getBinaryNodeChild)(infoChild, 'video');
944
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
945
+ call.groupJid = infoChild.attrs['group-jid'];
946
+ callOfferCache.set(call.id, call);
947
+ }
948
+ const existingCall = callOfferCache.get(call.id);
949
+
950
+ if (existingCall) {
951
+ call.isVideo = existingCall.isVideo;
952
+ call.isGroup = existingCall.isGroup;
953
+ }
954
+
955
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
956
+ callOfferCache.del(call.id);
957
+ }
958
+ ev.emit('call', [call]);
959
+ await sendMessageAck(node);
960
+ };
961
+ const handleBadAck = async ({ attrs }) => {
962
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id, 'server_id': attrs === null || attrs === void 0 ? void 0 : attrs.server_id };
963
+
964
+
965
+
966
+ if (attrs.phash) {
967
+ logger.info({ attrs }, 'received phash in ack, resending message...');
968
+ const cacheKey = `${key.remoteJid}:${key.id}`;
969
+ if ((msgRetryCache.get(cacheKey) || 0) >= maxMsgRetryCount) {
970
+ logger.warn({ attrs }, 'reached max retry count, not sending message again');
971
+ msgRetryCache.del(cacheKey);
972
+ return;
973
+ }
974
+ const retryCount = msgRetryCache.get(cacheKey) || 0;
975
+ const msg = await getMessage(key);
976
+ if (msg) {
977
+ await relayMessage(key.remoteJid, msg, { messageId: key.id, useUserDevicesCache: false });
978
+ msgRetryCache.set(cacheKey, retryCount + 1);
979
+ }
980
+ else {
981
+ logger.warn({ attrs }, 'could not send message again, as it was not found');
982
+ }
983
+ }
984
+
985
+
986
+ if (attrs.error) {
987
+ logger.warn({ attrs }, 'received error in ack');
988
+ ev.emit('messages.update', [
989
+ {
990
+ key,
991
+ update: {
992
+ status: Types_1.WAMessageStatus.ERROR,
993
+ messageStubParameters: [
994
+ attrs.error
995
+ ]
996
+ }
997
+ }
998
+ ]);
999
+ }
1000
+ };
1001
+ /
1002
+ /
1003
+ const processNodeWithBuffer = async (node, identifier, exec) => {
1004
+ ev.buffer();
1005
+ await execTask();
1006
+ ev.flush();
1007
+ function execTask() {
1008
+ return exec(node, false)
1009
+ .catch(err => onUnexpectedError(err, identifier));
1010
+ }
1011
+ };
1012
+ const makeOfflineNodeProcessor = () => {
1013
+ const nodeProcessorMap = new Map([
1014
+ ['message', handleMessage],
1015
+ ['call', handleCall],
1016
+ ['receipt', handleReceipt],
1017
+ ['notification', handleNotification]
1018
+ ]);
1019
+ const nodes = [];
1020
+ let isProcessing = false;
1021
+ const enqueue = (type, node) => {
1022
+ nodes.push({ type, node });
1023
+ if (isProcessing) {
1024
+ return;
1025
+ }
1026
+ isProcessing = true;
1027
+ const promise = async () => {
1028
+ while (nodes.length && ws.isOpen) {
1029
+ const { type, node } = nodes.shift();
1030
+ const nodeProcessor = nodeProcessorMap.get(type);
1031
+ if (!nodeProcessor) {
1032
+ onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
1033
+ continue;
1034
+ }
1035
+ await nodeProcessor(node);
1036
+ }
1037
+ isProcessing = false;
1038
+ };
1039
+ promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
1040
+ };
1041
+ return { enqueue };
1042
+ };
1043
+ const offlineNodeProcessor = makeOfflineNodeProcessor();
1044
+ const processNode = (type, node, identifier, exec) => {
1045
+ const isOffline = !!node.attrs.offline;
1046
+ if (isOffline) {
1047
+ offlineNodeProcessor.enqueue(type, node);
1048
+ }
1049
+ else {
1050
+ processNodeWithBuffer(node, identifier, exec);
1051
+ }
1052
+ };
1053
+
1054
+ ws.on('CB:message', (node) => {
1055
+ processNode('message', node, 'processing message', handleMessage);
1056
+ });
1057
+ ws.on('CB:call', async (node) => {
1058
+ processNode('call', node, 'handling call', handleCall);
1059
+ });
1060
+ ws.on('CB:receipt', node => {
1061
+ processNode('receipt', node, 'handling receipt', handleReceipt);
1062
+ });
1063
+ ws.on('CB:notification', async (node) => {
1064
+ processNode('notification', node, 'handling notification', handleNotification);
1065
+ });
1066
+ ws.on('CB:ack,class:message', (node) => {
1067
+ handleBadAck(node)
1068
+ .catch(error => onUnexpectedError(error, 'handling bad ack'));
1069
+ });
1070
+ ev.on('call', ([call]) => {
1071
+
1072
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
1073
+ const msg = {
1074
+ key: {
1075
+ remoteJid: call.chatId,
1076
+ id: call.id,
1077
+ fromMe: false
1078
+ },
1079
+ messageTimestamp: (0, Utils_1.unixTimestampSeconds)(call.date),
1080
+ };
1081
+ if (call.status === 'timeout') {
1082
+ if (call.isGroup) {
1083
+ msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE;
1084
+ }
1085
+ else {
1086
+ msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_VOICE;
1087
+ }
1088
+ }
1089
+ else {
1090
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
1091
+ }
1092
+ const protoMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
1093
+ upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1094
+ }
1095
+ });
1096
+ ev.on('connection.update', ({ isOnline }) => {
1097
+ if (typeof isOnline !== 'undefined') {
1098
+ sendActiveReceipts = isOnline;
1099
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1100
+ }
1101
+ });
1102
+ return {
1103
+ ...sock,
1104
+ sendMessageAck,
1105
+ sendRetryRequest,
1106
+ rejectCall,
1107
+ offerCall,
1108
+ fetchMessageHistory,
1109
+ requestPlaceholderResend,
1110
+ };
1111
+ };
1112
+ exports.makeMessagesRecvSocket = makeMessagesRecvSocket;