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