@zannstore/baileys 2.2.6

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