@sanzoffc/baileys 3.0.1

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