@sanzoffc/baileys 3.0.1 → 3.0.3

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 (114) hide show
  1. package/LICENSE +1 -1
  2. package/WAProto/WAProto.proto +769 -233
  3. package/WAProto/index.js +65801 -141371
  4. package/lib/Defaults/index.js +117 -114
  5. package/lib/Defaults/index.js.bak +123 -0
  6. package/lib/KeyDB/BinarySearch.js +20 -0
  7. package/lib/KeyDB/KeyedDB.js +167 -0
  8. package/lib/KeyDB/index.js +4 -0
  9. package/lib/Signal/Group/ciphertext-message.js +12 -14
  10. package/lib/Signal/Group/group-session-builder.js +10 -42
  11. package/lib/Signal/Group/group_cipher.js +75 -87
  12. package/lib/Signal/Group/index.js +13 -57
  13. package/lib/Signal/Group/keyhelper.js +17 -52
  14. package/lib/Signal/Group/sender-chain-key.js +27 -33
  15. package/lib/Signal/Group/sender-key-distribution-message.js +62 -63
  16. package/lib/Signal/Group/sender-key-message.js +65 -66
  17. package/lib/Signal/Group/sender-key-name.js +45 -44
  18. package/lib/Signal/Group/sender-key-record.js +39 -49
  19. package/lib/Signal/Group/sender-key-state.js +80 -93
  20. package/lib/Signal/Group/sender-message-key.js +27 -28
  21. package/lib/Signal/libsignal.js +313 -163
  22. package/lib/Signal/lid-mapping.js +155 -0
  23. package/lib/Socket/Client/index.js +4 -18
  24. package/lib/Socket/Client/types.js +12 -12
  25. package/lib/Socket/Client/websocket.js +51 -71
  26. package/lib/Socket/Client/websocket.js.bak +53 -0
  27. package/lib/Socket/business.js +359 -242
  28. package/lib/Socket/chats.js +858 -945
  29. package/lib/Socket/communities.js +413 -0
  30. package/lib/Socket/groups.js +304 -324
  31. package/lib/Socket/index.js +15 -9
  32. package/lib/Socket/messages-recv.js +1105 -1046
  33. package/lib/Socket/messages-send.js +615 -389
  34. package/lib/Socket/mex.js +45 -0
  35. package/lib/Socket/newsletter.js +224 -227
  36. package/lib/Socket/socket.js +795 -621
  37. package/lib/Store/index.js +6 -8
  38. package/lib/Store/make-cache-manager-store.js +75 -0
  39. package/lib/Store/make-in-memory-store.js +286 -435
  40. package/lib/Store/make-ordered-dictionary.js +77 -79
  41. package/lib/Store/object-repository.js +24 -26
  42. package/lib/Types/Auth.js +3 -2
  43. package/lib/Types/Bussines.js +3 -0
  44. package/lib/Types/Call.js +3 -2
  45. package/lib/Types/Chat.js +9 -4
  46. package/lib/Types/Contact.js +3 -2
  47. package/lib/Types/Events.js +3 -2
  48. package/lib/Types/GroupMetadata.js +3 -2
  49. package/lib/Types/Label.js +24 -26
  50. package/lib/Types/LabelAssociation.js +6 -8
  51. package/lib/Types/Message.js +12 -7
  52. package/lib/Types/Newsletter.js +32 -17
  53. package/lib/Types/Newsletter.js.bak +33 -0
  54. package/lib/Types/Product.js +3 -2
  55. package/lib/Types/Signal.js +3 -2
  56. package/lib/Types/Socket.js +4 -2
  57. package/lib/Types/State.js +11 -2
  58. package/lib/Types/USync.js +3 -2
  59. package/lib/Types/index.js +27 -41
  60. package/lib/Utils/auth-utils.js +211 -191
  61. package/lib/Utils/baileys-event-stream.js +44 -0
  62. package/lib/Utils/browser-utils.js +21 -31
  63. package/lib/Utils/business.js +213 -214
  64. package/lib/Utils/chat-utils.js +711 -689
  65. package/lib/Utils/crypto.js +112 -175
  66. package/lib/Utils/decode-wa-message.js +254 -194
  67. package/lib/Utils/event-buffer.js +510 -500
  68. package/lib/Utils/generics.js +318 -430
  69. package/lib/Utils/history.js +83 -90
  70. package/lib/Utils/index.js +21 -35
  71. package/lib/Utils/link-preview.js +71 -116
  72. package/lib/Utils/logger.js +5 -7
  73. package/lib/Utils/lt-hash.js +40 -46
  74. package/lib/Utils/make-mutex.js +34 -41
  75. package/lib/Utils/message-retry-manager.js +33 -48
  76. package/lib/Utils/messages-media.js +573 -825
  77. package/lib/Utils/messages.js +349 -489
  78. package/lib/Utils/noise-handler.js +138 -144
  79. package/lib/Utils/pre-key-manager.js +85 -0
  80. package/lib/Utils/process-message.js +321 -384
  81. package/lib/Utils/signal.js +147 -139
  82. package/lib/Utils/use-multi-file-auth-state.js +95 -109
  83. package/lib/Utils/validate-connection.js +183 -212
  84. package/lib/WABinary/constants.js +1298 -1298
  85. package/lib/WABinary/decode.js +231 -256
  86. package/lib/WABinary/encode.js +207 -239
  87. package/lib/WABinary/generic-utils.js +119 -40
  88. package/lib/WABinary/index.js +7 -21
  89. package/lib/WABinary/jid-utils.js +87 -79
  90. package/lib/WABinary/types.js +3 -2
  91. package/lib/WAM/BinaryInfo.js +10 -12
  92. package/lib/WAM/constants.js +22851 -15348
  93. package/lib/WAM/encode.js +135 -136
  94. package/lib/WAM/index.js +5 -19
  95. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -30
  96. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +49 -53
  97. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -28
  98. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +36 -39
  99. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -50
  100. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +26 -20
  101. package/lib/WAUSync/Protocols/index.js +6 -20
  102. package/lib/WAUSync/USyncQuery.js +86 -85
  103. package/lib/WAUSync/USyncUser.js +23 -25
  104. package/lib/WAUSync/index.js +5 -19
  105. package/lib/index.js +18 -49
  106. package/package.json +65 -78
  107. package/README.MD +0 -1295
  108. package/WAProto/GenerateStatics.sh +0 -4
  109. package/WAProto/p.html +0 -1
  110. package/engine-requirements.js +0 -10
  111. package/lib/Defaults/wileys-version.json +0 -3
  112. package/lib/Signal/Group/queue-job.js +0 -57
  113. package/lib/Socket/usync.js +0 -70
  114. package/lib/Utils/wileys-event-stream.js +0 -63
@@ -1,1104 +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, 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
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
31
24
  });
32
- const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
33
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
34
- useClones: false
25
+ const callOfferCache = config.callOfferCache ||
26
+ new NodeCache({
27
+ stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER,
28
+ useClones: false
35
29
  });
36
- const groupParticipantJidCache = new node_cache_1.default({
37
- stdTTL: 10 * 60, // 10 mins
38
- useClones: false
30
+ const placeholderResendCache = config.placeholderResendCache ||
31
+ new NodeCache({
32
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY,
33
+ useClones: false
39
34
  });
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
- }
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
55
49
  };
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');
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
67
72
  }
73
+ ],
74
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
68
75
  };
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);
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
+ }
79
114
  }
80
- catch (error) {
81
- logger.debug({ error, groupJid, participantLid }, 'failed to resolve group participant jid');
82
- return undefined;
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
+ }
83
127
  }
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
- }
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
+ }
93
148
  };
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;
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
+ });
102
183
  }
103
- if (!!attrs.type && (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
104
- stanza.attrs.type = attrs.type;
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
+ }
105
208
  }
106
- if (tag === 'message' && (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable')) {
107
- stanza.attrs.from = authState.creds.me.id;
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
+ }
223
+ };
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
108
259
  }
109
- logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
110
- await sendNode(stanza);
260
+ ]
111
261
  };
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
- });
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;
129
306
  }
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
- }
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
+ }
140
322
  });
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',
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",
151
341
  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
- }],
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
+ ]
162
377
  });
163
- await query(stanza);
164
- return {
165
- callId,
166
- toJid,
167
- 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
+ }
168
438
  };
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
- }],
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
+ };
186
459
  });
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;
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;
199
465
  }
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}`);
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()];
207
496
  }
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
- }
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];
272
503
  }
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');
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
282
537
  }
538
+ ]);
539
+ logger.debug({ jid }, "got privacy token update");
283
540
  }
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))
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");
384
564
  }
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
- });
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);
401
571
  }
402
- if (viewsList.length) {
403
- viewsList.forEach(item => {
404
- ev.emit('newsletter.view', { id, 'server_id': serverId, count: +item.attrs.count });
405
- });
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
+ };
406
593
  }
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];
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
+ }
422
607
  }
423
- ev.emit('newsletter-participants.update', { id, author: contentPath.actor.pn, user: contentPath.user.pn, new_role: contentPath.user_new_role, action });
608
+ });
424
609
  }
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 });
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
+ }
428
617
  }
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
- }
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
522
673
  }
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);
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);
581
722
  }
582
- if (Object.keys(result).length) {
583
- 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
+ }
584
731
  }
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);
732
+ }
733
+ msgs.push(msg);
593
734
  }
594
- function toRequiredBuffer(data) {
595
- if (data === undefined) {
596
- 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 } });
597
748
  }
598
- 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
+ }
599
753
  }
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 } });
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
+ };
623
773
  }
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;
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);
631
837
  }
632
- else {
633
- msgRelayOpts.participant = {
634
- jid: participant,
635
- count: +retryNode.attrs.count
636
- };
838
+ catch (error) {
839
+ logger.error({ key, ids, trace: error instanceof Error ? error.stack : "Unknown error" }, "error in sending message again");
637
840
  }
638
- await relayMessage(key.remoteJid, msg, msgRelayOpts);
841
+ }
842
+ else {
843
+ logger.info({ attrs, key }, "recv retry for not fromMe message");
844
+ }
639
845
  }
640
846
  else {
641
- 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");
642
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);
643
913
  }
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') {
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");
779
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
+ }
780
960
  }
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);
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
+ }
786
970
  }
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;
971
+ await sendMessageAck(node, NACK_REASONS.UnhandledError);
972
+ });
897
973
  }
898
974
  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);
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;
916
984
  }
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);
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
+ }
939
995
  }
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);
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
952
1020
  };
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
- ]);
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
+ }
991
1049
  }
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));
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);
1002
1085
  }
1086
+ isProcessing = false;
1087
+ };
1088
+ promise().catch(error => onUnexpectedError(error, "processing offline nodes"));
1003
1089
  };
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);
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;
1040
1135
  }
1041
1136
  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');
1137
+ msg.messageStubType = call.isVideo ? WAMessageStubType.CALL_MISSED_VIDEO : WAMessageStubType.CALL_MISSED_VOICE;
1086
1138
  }
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
- };
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
+ };
1103
1162
  };
1104
- exports.makeMessagesRecvSocket = makeMessagesRecvSocket;
1163
+ //=======================================================//