@neelegirly/baileys 2.2.16

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 (206) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +108 -0
  3. package/WAProto/WAProto.proto +5007 -0
  4. package/WAProto/index.d.ts +57712 -0
  5. package/WAProto/index.js +178969 -0
  6. package/lib/Defaults/baileys-version.json +1 -0
  7. package/lib/Defaults/index.d.ts +68 -0
  8. package/lib/Defaults/index.js +155 -0
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Signal/WASignalGroup/GroupProtocol.js +1909 -0
  11. package/lib/Signal/WASignalGroup/ciphertext_message.js +16 -0
  12. package/lib/Signal/WASignalGroup/generate-proto.sh +1 -0
  13. package/lib/Signal/WASignalGroup/group.proto +42 -0
  14. package/lib/Signal/WASignalGroup/group_cipher.js +120 -0
  15. package/lib/Signal/WASignalGroup/group_session_builder.js +46 -0
  16. package/lib/Signal/WASignalGroup/index.js +6 -0
  17. package/lib/Signal/WASignalGroup/keyhelper.js +22 -0
  18. package/lib/Signal/WASignalGroup/protobufs.js +3 -0
  19. package/lib/Signal/WASignalGroup/queue_job.js +69 -0
  20. package/lib/Signal/WASignalGroup/readme.md +6 -0
  21. package/lib/Signal/WASignalGroup/sender_chain_key.js +50 -0
  22. package/lib/Signal/WASignalGroup/sender_key_distribution_message.js +78 -0
  23. package/lib/Signal/WASignalGroup/sender_key_message.js +92 -0
  24. package/lib/Signal/WASignalGroup/sender_key_name.js +70 -0
  25. package/lib/Signal/WASignalGroup/sender_key_record.js +56 -0
  26. package/lib/Signal/WASignalGroup/sender_key_state.js +129 -0
  27. package/lib/Signal/WASignalGroup/sender_message_key.js +39 -0
  28. package/lib/Signal/libsignal.d.ts +4 -0
  29. package/lib/Signal/libsignal.js +427 -0
  30. package/lib/Socket/Client/abstract-socket-client.d.ts +15 -0
  31. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  32. package/lib/Socket/Client/index.d.ts +2 -0
  33. package/lib/Socket/Client/index.js +22 -0
  34. package/lib/Socket/Client/mobile-socket-client.d.ts +12 -0
  35. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  36. package/lib/Socket/Client/types.d.ts +16 -0
  37. package/lib/Socket/Client/types.js +18 -0
  38. package/lib/Socket/Client/websocket.d.ts +13 -0
  39. package/lib/Socket/Client/websocket.js +62 -0
  40. package/lib/Socket/business.d.ts +187 -0
  41. package/lib/Socket/business.js +268 -0
  42. package/lib/Socket/chats.d.ts +98 -0
  43. package/lib/Socket/chats.js +1133 -0
  44. package/lib/Socket/communities.d.ts +223 -0
  45. package/lib/Socket/communities.js +433 -0
  46. package/lib/Socket/groups.d.ts +131 -0
  47. package/lib/Socket/groups.js +352 -0
  48. package/lib/Socket/index.d.ts +191 -0
  49. package/lib/Socket/index.js +23 -0
  50. package/lib/Socket/messages-recv.d.ts +177 -0
  51. package/lib/Socket/messages-recv.js +1826 -0
  52. package/lib/Socket/messages-send.d.ts +168 -0
  53. package/lib/Socket/messages-send.js +1537 -0
  54. package/lib/Socket/mex.d.ts +2 -0
  55. package/lib/Socket/mex.js +47 -0
  56. package/lib/Socket/newsletter.d.ts +147 -0
  57. package/lib/Socket/newsletter.js +286 -0
  58. package/lib/Socket/registration.d.ts +266 -0
  59. package/lib/Socket/registration.js +166 -0
  60. package/lib/Socket/socket.d.ts +45 -0
  61. package/lib/Socket/socket.js +928 -0
  62. package/lib/Socket/usync.d.ts +37 -0
  63. package/lib/Socket/usync.js +83 -0
  64. package/lib/Store/index.d.ts +4 -0
  65. package/lib/Store/index.js +24 -0
  66. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  67. package/lib/Store/make-cache-manager-store.js +90 -0
  68. package/lib/Store/make-in-memory-store.d.ts +123 -0
  69. package/lib/Store/make-in-memory-store.js +429 -0
  70. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  71. package/lib/Store/make-ordered-dictionary.js +86 -0
  72. package/lib/Store/object-repository.d.ts +10 -0
  73. package/lib/Store/object-repository.js +31 -0
  74. package/lib/Types/Auth.d.ts +120 -0
  75. package/lib/Types/Auth.js +3 -0
  76. package/lib/Types/Bussines.d.ts +20 -0
  77. package/lib/Types/Bussines.js +2 -0
  78. package/lib/Types/Call.d.ts +14 -0
  79. package/lib/Types/Call.js +3 -0
  80. package/lib/Types/Chat.d.ts +141 -0
  81. package/lib/Types/Chat.js +9 -0
  82. package/lib/Types/Contact.d.ts +20 -0
  83. package/lib/Types/Contact.js +3 -0
  84. package/lib/Types/Events.d.ts +237 -0
  85. package/lib/Types/Events.js +3 -0
  86. package/lib/Types/GroupMetadata.d.ts +66 -0
  87. package/lib/Types/GroupMetadata.js +3 -0
  88. package/lib/Types/Label.d.ts +48 -0
  89. package/lib/Types/Label.js +31 -0
  90. package/lib/Types/LabelAssociation.d.ts +35 -0
  91. package/lib/Types/LabelAssociation.js +13 -0
  92. package/lib/Types/Message.d.ts +473 -0
  93. package/lib/Types/Message.js +13 -0
  94. package/lib/Types/MexUpdates.d.ts +9 -0
  95. package/lib/Types/MexUpdates.js +18 -0
  96. package/lib/Types/Newsletter.d.ts +109 -0
  97. package/lib/Types/Newsletter.js +40 -0
  98. package/lib/Types/Product.d.ts +92 -0
  99. package/lib/Types/Product.js +3 -0
  100. package/lib/Types/Signal.d.ts +68 -0
  101. package/lib/Types/Signal.js +3 -0
  102. package/lib/Types/Socket.d.ts +122 -0
  103. package/lib/Types/Socket.js +3 -0
  104. package/lib/Types/State.d.ts +41 -0
  105. package/lib/Types/State.js +14 -0
  106. package/lib/Types/USync.d.ts +26 -0
  107. package/lib/Types/USync.js +3 -0
  108. package/lib/Types/index.d.ts +80 -0
  109. package/lib/Types/index.js +48 -0
  110. package/lib/Utils/auth-utils.d.ts +21 -0
  111. package/lib/Utils/auth-utils.js +205 -0
  112. package/lib/Utils/baileys-event-stream.d.ts +18 -0
  113. package/lib/Utils/baileys-event-stream.js +70 -0
  114. package/lib/Utils/branding.d.ts +24 -0
  115. package/lib/Utils/branding.js +209 -0
  116. package/lib/Utils/business.d.ts +29 -0
  117. package/lib/Utils/business.js +255 -0
  118. package/lib/Utils/chat-utils.d.ts +82 -0
  119. package/lib/Utils/chat-utils.js +798 -0
  120. package/lib/Utils/check-npm-version.d.ts +18 -0
  121. package/lib/Utils/check-npm-version.js +130 -0
  122. package/lib/Utils/crypto.d.ts +56 -0
  123. package/lib/Utils/crypto.js +179 -0
  124. package/lib/Utils/decode-wa-message.d.ts +41 -0
  125. package/lib/Utils/decode-wa-message.js +288 -0
  126. package/lib/Utils/event-buffer.d.ts +39 -0
  127. package/lib/Utils/event-buffer.js +565 -0
  128. package/lib/Utils/generics.d.ts +129 -0
  129. package/lib/Utils/generics.js +630 -0
  130. package/lib/Utils/history.d.ts +23 -0
  131. package/lib/Utils/history.js +110 -0
  132. package/lib/Utils/index.d.ts +22 -0
  133. package/lib/Utils/index.js +42 -0
  134. package/lib/Utils/link-preview.d.ts +23 -0
  135. package/lib/Utils/link-preview.js +120 -0
  136. package/lib/Utils/logger.d.ts +13 -0
  137. package/lib/Utils/logger.js +7 -0
  138. package/lib/Utils/lt-hash.d.ts +14 -0
  139. package/lib/Utils/lt-hash.js +58 -0
  140. package/lib/Utils/make-mutex.d.ts +9 -0
  141. package/lib/Utils/make-mutex.js +49 -0
  142. package/lib/Utils/message-retry-manager.d.ts +84 -0
  143. package/lib/Utils/message-retry-manager.js +179 -0
  144. package/lib/Utils/messages-media.d.ts +129 -0
  145. package/lib/Utils/messages-media.js +806 -0
  146. package/lib/Utils/messages.d.ts +103 -0
  147. package/lib/Utils/messages.js +1579 -0
  148. package/lib/Utils/noise-handler.d.ts +20 -0
  149. package/lib/Utils/noise-handler.js +155 -0
  150. package/lib/Utils/process-message.d.ts +49 -0
  151. package/lib/Utils/process-message.js +443 -0
  152. package/lib/Utils/signal.d.ts +42 -0
  153. package/lib/Utils/signal.js +168 -0
  154. package/lib/Utils/use-mongo-file-auth-state.d.ts +6 -0
  155. package/lib/Utils/use-mongo-file-auth-state.js +84 -0
  156. package/lib/Utils/use-multi-file-auth-state.d.ts +18 -0
  157. package/lib/Utils/use-multi-file-auth-state.js +249 -0
  158. package/lib/Utils/use-single-file-auth-state.d.ts +13 -0
  159. package/lib/Utils/use-single-file-auth-state.js +80 -0
  160. package/lib/Utils/validate-connection.d.ts +13 -0
  161. package/lib/Utils/validate-connection.js +218 -0
  162. package/lib/WABinary/constants.d.ts +30 -0
  163. package/lib/WABinary/constants.js +1316 -0
  164. package/lib/WABinary/decode.d.ts +9 -0
  165. package/lib/WABinary/decode.js +288 -0
  166. package/lib/WABinary/encode.d.ts +3 -0
  167. package/lib/WABinary/encode.js +265 -0
  168. package/lib/WABinary/generic-utils.d.ts +28 -0
  169. package/lib/WABinary/generic-utils.js +142 -0
  170. package/lib/WABinary/index.d.ts +5 -0
  171. package/lib/WABinary/index.js +25 -0
  172. package/lib/WABinary/jid-utils.d.ts +59 -0
  173. package/lib/WABinary/jid-utils.js +105 -0
  174. package/lib/WABinary/types.d.ts +22 -0
  175. package/lib/WABinary/types.js +3 -0
  176. package/lib/WAM/BinaryInfo.d.ts +16 -0
  177. package/lib/WAM/BinaryInfo.js +17 -0
  178. package/lib/WAM/constants.d.ts +47 -0
  179. package/lib/WAM/constants.js +15371 -0
  180. package/lib/WAM/encode.d.ts +3 -0
  181. package/lib/WAM/encode.js +165 -0
  182. package/lib/WAM/index.d.ts +3 -0
  183. package/lib/WAM/index.js +23 -0
  184. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +28 -0
  185. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +69 -0
  186. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  187. package/lib/WAUSync/Protocols/USyncContactProtocol.js +36 -0
  188. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +26 -0
  189. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +62 -0
  190. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +14 -0
  191. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +35 -0
  192. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +9 -0
  193. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
  194. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +14 -0
  195. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +46 -0
  196. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  197. package/lib/WAUSync/Protocols/index.js +26 -0
  198. package/lib/WAUSync/USyncQuery.d.ts +31 -0
  199. package/lib/WAUSync/USyncQuery.js +82 -0
  200. package/lib/WAUSync/USyncUser.d.ts +12 -0
  201. package/lib/WAUSync/USyncUser.js +30 -0
  202. package/lib/WAUSync/index.d.ts +3 -0
  203. package/lib/WAUSync/index.js +23 -0
  204. package/lib/index.d.ts +13 -0
  205. package/lib/index.js +33 -0
  206. package/package.json +120 -0
@@ -0,0 +1,1826 @@
1
+ "use strict";
2
+
3
+ var __importDefault =
4
+ (this && this.__importDefault) ||
5
+ function (mod) {
6
+ return mod && mod.__esModule ? mod : { default: mod };
7
+ };
8
+
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+
11
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
12
+ const boom_1 = require("@hapi/boom");
13
+ const crypto_1 = require("crypto");
14
+ const WAProto_1 = require("../../WAProto");
15
+ const Defaults_1 = require("../Defaults");
16
+ const Types_1 = require("../Types");
17
+ const Utils_1 = require("../Utils");
18
+ const make_mutex_1 = require("../Utils/make-mutex");
19
+ const WABinary_1 = require("../WABinary");
20
+ const groups_1 = require("./groups");
21
+ const messages_send_1 = require("./messages-send");
22
+
23
+ const makeMessagesRecvSocket = (config) => {
24
+ const {
25
+ logger,
26
+ retryRequestDelayMs,
27
+ maxMsgRetryCount,
28
+ getMessage,
29
+ shouldIgnoreJid,
30
+ } = config;
31
+ const Neele = messages_send_1.makeMessagesSocket(config);
32
+ const {
33
+ ev,
34
+ authState,
35
+ ws,
36
+ processingMutex,
37
+ signalRepository,
38
+ query,
39
+ upsertMessage,
40
+ groupMetadata,
41
+ resyncAppState,
42
+ onUnexpectedError,
43
+ assertSessions,
44
+ sendNode,
45
+ relayMessage,
46
+ sendReceipt,
47
+ uploadPreKeys,
48
+ getUSyncDevices,
49
+ createParticipantNodes,
50
+ sendPeerDataOperationMessage,
51
+ } = Neele;
52
+
53
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
54
+ const retryMutex = make_mutex_1.makeMutex();
55
+
56
+ const msgRetryCache =
57
+ config.msgRetryCounterCache ||
58
+ new node_cache_1.default({
59
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
60
+ useClones: false,
61
+ });
62
+
63
+ const callOfferCache =
64
+ config.callOfferCache ||
65
+ new node_cache_1.default({
66
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER,
67
+ useClones: false,
68
+ });
69
+
70
+ const placeholderResendCache =
71
+ config.placeholderResendCache ||
72
+ new node_cache_1.default({
73
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
74
+ useClones: false,
75
+ });
76
+
77
+ let sendActiveReceipts = false;
78
+
79
+ const normalizeOptionalJid = (jid) =>
80
+ jid ? WABinary_1.jidNormalizedUser(jid) : "";
81
+
82
+ const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
83
+ const stanza = {
84
+ tag: "ack",
85
+ attrs: {
86
+ id: attrs.id,
87
+ to: attrs.from,
88
+ class: tag,
89
+ },
90
+ };
91
+
92
+ if (!!errorCode) {
93
+ stanza.attrs.error = errorCode.toString();
94
+ }
95
+
96
+ if (!!attrs.participant) {
97
+ stanza.attrs.participant = attrs.participant;
98
+ }
99
+
100
+ if (!!attrs.recipient) {
101
+ stanza.attrs.recipient = attrs.recipient;
102
+ }
103
+
104
+ if (
105
+ !!attrs.type &&
106
+ (tag !== "message" ||
107
+ WABinary_1.getBinaryNodeChild({ tag, attrs, content }, "unavailable") ||
108
+ errorCode !== 0)
109
+ ) {
110
+ stanza.attrs.type = attrs.type;
111
+ }
112
+
113
+ if (
114
+ tag === "message" &&
115
+ WABinary_1.getBinaryNodeChild({ tag, attrs, content }, "unavailable")
116
+ ) {
117
+ stanza.attrs.from = authState.creds.me.id;
118
+ }
119
+
120
+ logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, "sent ack");
121
+ await sendNode(stanza);
122
+ };
123
+
124
+ const offerCall = async (toJid, isVideo = false) => {
125
+ const callId = crypto_1
126
+ .randomBytes(16)
127
+ .toString("hex")
128
+ .toUpperCase()
129
+ .substring(0, 64);
130
+ const offerContent = [];
131
+ offerContent.push({
132
+ tag: "audio",
133
+ attrs: { enc: "opus", rate: "16000" },
134
+ content: undefined,
135
+ });
136
+ offerContent.push({
137
+ tag: "audio",
138
+ attrs: { enc: "opus", rate: "8000" },
139
+ content: undefined,
140
+ });
141
+ if (isVideo) {
142
+ offerContent.push({
143
+ tag: "video",
144
+ attrs: {
145
+ enc: "vp8",
146
+ dec: "vp8",
147
+ orientation: "0",
148
+ screen_width: "1920",
149
+ screen_height: "1080",
150
+ device_orientation: "0",
151
+ },
152
+ content: undefined,
153
+ });
154
+ }
155
+ offerContent.push({
156
+ tag: "net",
157
+ attrs: { medium: "3" },
158
+ content: undefined,
159
+ });
160
+ offerContent.push({
161
+ tag: "capability",
162
+ attrs: { ver: "1" },
163
+ content: new Uint8Array([1, 4, 255, 131, 207, 4]),
164
+ });
165
+ offerContent.push({
166
+ tag: "encopt",
167
+ attrs: { keygen: "2" },
168
+ content: undefined,
169
+ });
170
+ const encKey = crypto_1.randomBytes(32);
171
+ const rawDevices = await getUSyncDevices([toJid], true, false);
172
+ const devices = rawDevices.map(({ user, device }) =>
173
+ WABinary_1.jidEncode(user, "s.whatsapp.net", device)
174
+ );
175
+ await assertSessions(devices, true);
176
+ const { nodes: destinations, shouldIncludeDeviceIdentity } =
177
+ await createParticipantNodes(
178
+ devices,
179
+ { call: { callKey: new Uint8Array(encKey) } },
180
+ { count: "0" }
181
+ );
182
+ offerContent.push({ tag: "destination", attrs: {}, content: destinations });
183
+ if (shouldIncludeDeviceIdentity) {
184
+ offerContent.push({
185
+ tag: "device-identity",
186
+ attrs: {},
187
+ content: Utils_1.encodeSignedDeviceIdentity(
188
+ authState.creds.account,
189
+ true
190
+ ),
191
+ });
192
+ }
193
+ const stanza = {
194
+ tag: "call",
195
+ attrs: {
196
+ id: Utils_1.generateMessageIDV2(),
197
+ to: toJid,
198
+ },
199
+ content: [
200
+ {
201
+ tag: "offer",
202
+ attrs: {
203
+ "call-id": callId,
204
+ "call-creator": authState.creds.me.id,
205
+ },
206
+ content: offerContent,
207
+ },
208
+ ],
209
+ };
210
+ await query(stanza);
211
+ return {
212
+ id: callId,
213
+ to: toJid,
214
+ };
215
+ };
216
+
217
+ const rejectCall = async (callId, callFrom) => {
218
+ const stanza = {
219
+ tag: "call",
220
+ attrs: {
221
+ from: authState.creds.me.id,
222
+ to: callFrom,
223
+ },
224
+ content: [
225
+ {
226
+ tag: "reject",
227
+ attrs: {
228
+ "call-id": callId,
229
+ "call-creator": callFrom,
230
+ count: "0",
231
+ },
232
+ content: undefined,
233
+ },
234
+ ],
235
+ };
236
+
237
+ await query(stanza);
238
+ };
239
+
240
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
241
+ const { fullMessage } = Utils_1.decodeMessageNode(
242
+ node,
243
+ authState.creds.me.id,
244
+ authState.creds.me.lid || ""
245
+ );
246
+ const { key: msgKey } = fullMessage;
247
+ const msgId = msgKey.id;
248
+ const key = `${msgId}:${msgKey?.participant}`;
249
+ let retryCount = msgRetryCache.get(key) || 0;
250
+
251
+ if (retryCount >= maxMsgRetryCount) {
252
+ logger.debug({ retryCount, msgId }, "reached retry limit, clearing");
253
+ msgRetryCache.del(key);
254
+ return;
255
+ }
256
+ retryCount += 1;
257
+ msgRetryCache.set(key, retryCount);
258
+
259
+ const {
260
+ account,
261
+ signedPreKey,
262
+ signedIdentityKey: identityKey,
263
+ } = authState.creds;
264
+
265
+ if (retryCount === 1) {
266
+ //request a resend via phone
267
+ const msgId = await requestPlaceholderResend(msgKey);
268
+ logger.debug(
269
+ `sendRetryRequest: requested placeholder resend for message ${msgId}`
270
+ );
271
+ }
272
+
273
+ const deviceIdentity = Utils_1.encodeSignedDeviceIdentity(account, true);
274
+
275
+ await authState.keys.transaction(async () => {
276
+ const receipt = {
277
+ tag: "receipt",
278
+ attrs: {
279
+ id: msgId,
280
+ type: "retry",
281
+ to: node.attrs.from,
282
+ },
283
+ content: [
284
+ {
285
+ tag: "retry",
286
+ attrs: {
287
+ count: retryCount.toString(),
288
+ id: node.attrs.id,
289
+ t: node.attrs.t,
290
+ v: "1",
291
+ },
292
+ },
293
+ {
294
+ tag: "registration",
295
+ attrs: {},
296
+ content: Utils_1.encodeBigEndian(authState.creds.registrationId),
297
+ },
298
+ ],
299
+ };
300
+
301
+ if (node.attrs.recipient) {
302
+ receipt.attrs.recipient = node.attrs.recipient;
303
+ }
304
+
305
+ if (node.attrs.participant) {
306
+ receipt.attrs.participant = node.attrs.participant;
307
+ }
308
+
309
+ if (retryCount > 1 || forceIncludeKeys) {
310
+ const { update, preKeys } = await Utils_1.getNextPreKeys(authState, 1);
311
+ const [keyId] = Object.keys(preKeys);
312
+ const key = preKeys[+keyId];
313
+ const content = receipt.content;
314
+
315
+ content.push({
316
+ tag: "keys",
317
+ attrs: {},
318
+ content: [
319
+ {
320
+ tag: "type",
321
+ attrs: {},
322
+ content: Buffer.from(Defaults_1.KEY_BUNDLE_TYPE),
323
+ },
324
+ { tag: "identity", attrs: {}, content: identityKey.public },
325
+ Utils_1.xmppPreKey(key, +keyId),
326
+ Utils_1.xmppSignedPreKey(signedPreKey),
327
+ { tag: "device-identity", attrs: {}, content: deviceIdentity },
328
+ ],
329
+ });
330
+ ev.emit("creds.update", update);
331
+ }
332
+
333
+ await sendNode(receipt);
334
+
335
+ logger.info({ msgAttrs: node.attrs, retryCount }, "sent retry receipt");
336
+ });
337
+ };
338
+
339
+ const handleEncryptNotification = async (node) => {
340
+ const from = node.attrs.from;
341
+ if (from === WABinary_1.S_WHATSAPP_NET) {
342
+ const countChild = WABinary_1.getBinaryNodeChild(node, "count");
343
+ const count = +countChild.attrs.value;
344
+ const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT;
345
+ logger.debug({ count, shouldUploadMorePreKeys }, "recv pre-key count");
346
+
347
+ if (shouldUploadMorePreKeys) {
348
+ await uploadPreKeys();
349
+ }
350
+ } else {
351
+ const identityNode = WABinary_1.getBinaryNodeChild(node, "identity");
352
+ if (identityNode) {
353
+ logger.info({ jid: from }, "identity changed");
354
+ // not handling right now
355
+ // signal will override new identity anyway
356
+ } else {
357
+ logger.info({ node }, "unknown encrypt notification");
358
+ }
359
+ }
360
+ };
361
+
362
+ const handleGroupNotification = (
363
+ participant,
364
+ child,
365
+ msg,
366
+ participantPhoneNumber,
367
+ mode
368
+ ) => {
369
+ if (participant && participant.endsWith("@lid") && participantPhoneNumber) {
370
+ participant = participantPhoneNumber;
371
+ }
372
+
373
+ const participantNode = WABinary_1.getBinaryNodeChild(child, "participant");
374
+
375
+ const participantJid = participantNode
376
+ ? [participantNode]
377
+ .map((p) => {
378
+ const { jid, lid, phone_number } = p.attrs;
379
+
380
+ if (phone_number && phone_number.endsWith("@s.whatsapp.net")) {
381
+ return phone_number;
382
+ }
383
+
384
+ if (jid && (0, WABinary_1.isJidUser)(jid)) {
385
+ return jid;
386
+ }
387
+
388
+ if (phone_number) {
389
+ return (0, WABinary_1.jidNormalizedUser)(phone_number);
390
+ }
391
+
392
+ if (lid && lid.endsWith("@lid")) {
393
+ return lid;
394
+ }
395
+
396
+ return null;
397
+ })
398
+ .filter(Boolean)[0]
399
+ : null;
400
+
401
+ msg.participant_pn = participantPhoneNumber;
402
+ if (participantPhoneNumber) {
403
+ msg.key = {
404
+ ...(msg.key || {}),
405
+ participant: participantPhoneNumber,
406
+ };
407
+ }
408
+
409
+ switch (child.tag) {
410
+ case "create":
411
+ const metadata = groups_1.extractGroupMetadata(child);
412
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
413
+ msg.messageStubParameters = [metadata.subject];
414
+ msg.key = { participant: metadata.owner };
415
+ ev.emit("chats.upsert", [
416
+ {
417
+ id: metadata.id,
418
+ name: metadata.subject,
419
+ conversationTimestamp: metadata.creation,
420
+ },
421
+ ]);
422
+ ev.emit("groups.upsert", [
423
+ {
424
+ ...metadata,
425
+ author: participant,
426
+ },
427
+ ]);
428
+ break;
429
+ case "delete":
430
+ msg.messageStubType =
431
+ Types_1.WAMessageStubType.COMMUNITY_PARENT_GROUP_DELETED;
432
+ msg.messageStubParameters = [participantJid, "delete"];
433
+ break;
434
+ case "ephemeral":
435
+ case "not_ephemeral":
436
+ msg.message = {
437
+ protocolMessage: {
438
+ type: WAProto_1.proto.Message.ProtocolMessage.Type
439
+ .EPHEMERAL_SETTING,
440
+ ephemeralExpiration: +(child.attrs.expiration || 0),
441
+ },
442
+ };
443
+ break;
444
+ case "modify":
445
+ const oldNumber = WABinary_1.getBinaryNodeChildren(
446
+ child,
447
+ "participant"
448
+ ).map((p) => p.attrs.jid);
449
+ msg.messageStubParameters = oldNumber || [];
450
+ msg.messageStubType =
451
+ Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
452
+ break;
453
+ case "promote":
454
+ case "demote":
455
+ case "remove":
456
+ case "add":
457
+ case "leave":
458
+ let stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
459
+ if (child.attrs?.reason === "linked_group_join") {
460
+ stubType = GROUP_PARTICIPANT_LINKED_GROUP_JOIN;
461
+ }
462
+ msg.messageStubType = Types_1.WAMessageStubType[stubType];
463
+ const participants = (0, WABinary_1.getBinaryNodeChildren)(
464
+ child,
465
+ "participant"
466
+ )
467
+ .map((p) => {
468
+ const { jid, lid, phone_number } = p.attrs;
469
+ if (phone_number && phone_number.endsWith("@s.whatsapp.net")) {
470
+ return phone_number;
471
+ }
472
+ if (jid && jid.endsWith("@s.whatsapp.net")) {
473
+ return jid;
474
+ }
475
+ if (lid && lid.endsWith("@lid")) {
476
+ }
477
+ return null;
478
+ })
479
+ .filter(Boolean);
480
+
481
+ if (
482
+ participants.length === 1 &&
483
+ // if recv. "remove" message and sender removed themselves
484
+ // mark as left
485
+ WABinary_1.areJidsSameUser(participants[0], participant) &&
486
+ child.tag === "remove"
487
+ ) {
488
+ msg.messageStubType =
489
+ Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
490
+ }
491
+ msg.messageStubParameters = participants;
492
+ break;
493
+ case "subject":
494
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
495
+ msg.messageStubType =
496
+ Types_1.WAMessageStubType.COMMUNITY_PARENT_GROUP_SUBJECT_CHANGED;
497
+ msg.messageStubParameters = [participantJid, child.attrs.subject];
498
+ break;
499
+ case "description":
500
+ const description = WABinary_1.getBinaryNodeChild(
501
+ child,
502
+ "body"
503
+ )?.content?.toString();
504
+ msg.messageStubType =
505
+ Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
506
+ msg.messageStubType =
507
+ Types_1.WAMessageStubType.COMMUNITY_CHANGE_DESCRIPTION;
508
+ msg.messageStubParameters = description ? [description] : undefined;
509
+
510
+ break;
511
+ case "announcement":
512
+ case "not_announcement":
513
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
514
+ msg.messageStubParameters = [
515
+ child.tag === "announcement" ? "on" : "off",
516
+ ];
517
+ break;
518
+ case "locked":
519
+ case "unlocked":
520
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT;
521
+ msg.messageStubParameters = [child.tag === "locked" ? "on" : "off"];
522
+ break;
523
+ case "invite":
524
+ msg.messageStubType =
525
+ Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
526
+ msg.messageStubParameters = [child.attrs.code];
527
+ break;
528
+ case "member_add_mode":
529
+ const addMode = child.content;
530
+ if (addMode) {
531
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE;
532
+ msg.messageStubParameters = [addMode.toString()];
533
+ }
534
+ break;
535
+ case "membership_approval_mode":
536
+ const approvalMode = WABinary_1.getBinaryNodeChild(child, "group_join");
537
+ if (approvalMode) {
538
+ msg.messageStubType =
539
+ Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
540
+ msg.messageStubParameters = [approvalMode.attrs.state];
541
+ }
542
+ break;
543
+ case "created_membership_requests":
544
+ msg.messageStubType =
545
+ Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
546
+ msg.messageStubParameters = [
547
+ participantJid,
548
+ "created",
549
+ child.attrs.request_method,
550
+ ];
551
+ break;
552
+ case "revoked_membership_requests":
553
+ const isDenied = WABinary_1.areJidsSameUser(
554
+ participantJid,
555
+ participant
556
+ );
557
+ msg.messageStubType =
558
+ Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
559
+ msg.messageStubParameters = [
560
+ participantJid,
561
+ isDenied ? "revoked" : "rejected",
562
+ ];
563
+ break;
564
+ case "link":
565
+ case "unlink":
566
+ const type = child.attrs?.unlink_type || child.attrs?.link_type;
567
+ const stubMap = {
568
+ parent_group:
569
+ Types_1.WAMessageStubType[
570
+ `COMMUNITY_${child.tag.toUpperCase()}_PARENT_GROUP`
571
+ ],
572
+ sibling_group:
573
+ Types_1.WAMessageStubType[
574
+ `COMMUNITY_${child.tag.toUpperCase()}_SIBLING_GROUP`
575
+ ],
576
+ sub_group:
577
+ Types_1.WAMessageStubType[
578
+ `COMMUNITY_${child.tag.toUpperCase()}_SUB_GROUP`
579
+ ],
580
+ };
581
+ const groups = WABinary_1.getBinaryNodeChildren(child, "group")
582
+ .map((g) => g.attrs?.jid || g.attrs?.subject || "")
583
+ .filter((x) => x);
584
+ msg.messageStubType =
585
+ stubMap?.[type] ||
586
+ Types_1.WAMessageStubType[
587
+ `COMMUNITY_${child.tag.toUpperCase()}_PARENT_GROUP`
588
+ ];
589
+ msg.messageStubParameters = [participantJid, child.tag, groups];
590
+ break;
591
+ case "linked_group_promote":
592
+ case "linked_group_demote":
593
+ const stubtype = `COMMUNITY_PARTICIPANT_${child.tag
594
+ .split("_")[2]
595
+ .toUpperCase()}`;
596
+ const participantS =
597
+ mode === "lid"
598
+ ? WABinary_1.getBinaryNodeChildren(child, "participant").map(
599
+ (p) => p.attrs.phone_number
600
+ )
601
+ : WABinary_1.getBinaryNodeChildren(child, "participant").map(
602
+ (p) => p.attrs.jid
603
+ );
604
+ msg.messageStubType = Types_1.WAMessageStubType[stubtype];
605
+ msg.messageStubParameters = participantS;
606
+ break;
607
+ case "created_sub_group_suggestion":
608
+ msg.messageStubType =
609
+ Types_1.WAMessageStubType.SUGGESTED_SUBGROUP_ANNOUNCE;
610
+ msg.messageStubParameters = [participantJid, "add"];
611
+ break;
612
+ case "revoked_sub_group_suggestions":
613
+ const res = WABinary_1.getBinaryNodeChildren(
614
+ child,
615
+ "sub_group_suggestions"
616
+ );
617
+ const reason = res.attrs?.reason;
618
+ if (reason === "approved")
619
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
620
+ else
621
+ msg.messageStubType = Types_1.WAMessageStubType.GENERIC_NOTIFICATION;
622
+ msg.messageStubParameters = [participantJid, reason];
623
+ break;
624
+ default:
625
+ logger.warn(child.tag, "Unhandled group node");
626
+ break;
627
+ }
628
+ };
629
+
630
+ const handleNewsletterNotification = (id, node) => {
631
+ const messages = WABinary_1.getBinaryNodeChild(node, "messages");
632
+ const message = WABinary_1.getBinaryNodeChild(node, "message");
633
+ const serverId = node.attrs.server_id;
634
+
635
+ const reactionsList = WABinary_1.getBinaryNodeChild(node, "reactions");
636
+ const viewsList = WABinary_1.getBinaryNodeChild(node, "views_count");
637
+
638
+ if (reactionsList) {
639
+ const reactions = WABinary_1.getBinaryNodeChild(
640
+ reactionsList,
641
+ "reaction"
642
+ );
643
+
644
+ if (reactions.length === 0) {
645
+ ev.emit("newsletter.reaction", {
646
+ id,
647
+ newsletter_server_id: serverId,
648
+ reaction: {
649
+ removed: true,
650
+ },
651
+ });
652
+ }
653
+
654
+ reactions.forEach((item) => {
655
+ ev.emit("newsletter.reaction", {
656
+ id,
657
+ newsletter_server_id: serverId,
658
+ reaction: {
659
+ code: item.attrs?.code,
660
+ count: +item.attrs.count,
661
+ },
662
+ });
663
+ });
664
+ }
665
+
666
+ if (viewsList.length) {
667
+ viewsList.forEach((item) => {
668
+ ev.emit("newsletter.view", {
669
+ id,
670
+ newsletter_server_id: serverId,
671
+ count: +item.attrs.count,
672
+ });
673
+ });
674
+ }
675
+ };
676
+
677
+ const handleMexNotification = (id, node) => {
678
+ const operation = node?.attrs?.op_name;
679
+ const content = JSON.parse(node?.content);
680
+
681
+ let contentPath;
682
+ let action;
683
+
684
+ if (operation === Types_1.MexOperations.UPDATE) {
685
+ contentPath = content.data[Types_1.XWAPaths.METADATA_UPDATE];
686
+
687
+ ev.emit("newsletter-settings.update", {
688
+ id,
689
+ update: contentPath.thread_metadata.settings,
690
+ });
691
+ } else if (operation === Types_1.MexUpdatesOperations.GROUP_LIMIT_SHARING) {
692
+ contentPath =
693
+ content.data[Types_1.XWAPathsMexUpdates.GROUP_SHARING_CHANGE];
694
+
695
+ ev.emit("limit-sharing.update", {
696
+ id,
697
+ author: contentPath.updated_by?.pn
698
+ ? contentPath.updated_by.pn
699
+ : contentPath.updated_by.id,
700
+ action: `${
701
+ contentPath.properties.limit_sharing.limit_sharing_enabled
702
+ ? "on"
703
+ : "off"
704
+ }`,
705
+ trigger: contentPath.properties.limit_sharing.limit_sharing_trigger,
706
+ update_time: contentPath.update_time,
707
+ });
708
+ } else if (operation === Types_1.MexUpdatesOperations.OWNER_COMMUNITY) {
709
+ contentPath =
710
+ content.data[Types_1.XWAPathsMexUpdates.COMMUNITY_OWNER_CHANGE];
711
+
712
+ ev.emit("community-owner.update", {
713
+ id,
714
+ author: contentPath.updated_by?.pn
715
+ ? contentPath.updated_by.pn
716
+ : contentPath.updated_by.id,
717
+ user: contentPath.role_updates[0].user?.pn
718
+ ? contentPath.role_updates[0].user.pn
719
+ : contentPath.role_updates[0].user.jid,
720
+ new_role: contentPath.role_updates[0].new_role,
721
+ update_time: contentPath.update_time,
722
+ });
723
+ } else {
724
+ if (operation === Types_1.MexOperations.PROMOTE) {
725
+ action = "promote";
726
+ contentPath = content.data[Types_1.XWAPaths.PROMOTE];
727
+ } else {
728
+ action = "demote";
729
+ contentPath = content.data[Types_1.XWAPaths.DEMOTE];
730
+ }
731
+
732
+ ev.emit("newsletter-participants.update", {
733
+ id,
734
+ author: contentPath.actor.pn,
735
+ user: contentPath.user.pn,
736
+ new_role: contentPath.user_new_role,
737
+ action,
738
+ });
739
+ }
740
+ };
741
+
742
+ const processNotification = async (node) => {
743
+ const result = {};
744
+ const [child] = WABinary_1.getAllBinaryNodeChildren(node);
745
+ const nodeType = node.attrs.type;
746
+ const from = WABinary_1.jidNormalizedUser(node.attrs.from);
747
+
748
+ switch (nodeType) {
749
+ case "privacy_token":
750
+ const tokenList = WABinary_1.getBinaryNodeChildren(child, "token");
751
+ for (const { attrs, content } of tokenList) {
752
+ const jid = attrs.jid;
753
+ ev.emit("chats.update", [
754
+ {
755
+ id: jid,
756
+ tcToken: content,
757
+ },
758
+ ]);
759
+ logger.debug({ jid }, "got privacy token update");
760
+ }
761
+ break;
762
+ case "w:gp2":
763
+ const mode = node.attrs.addressing_mode;
764
+ handleGroupNotification(
765
+ node.attrs.participant,
766
+ child,
767
+ result,
768
+ node.attrs.participant_pn,
769
+ mode
770
+ );
771
+ break;
772
+ case "newsletter":
773
+ handleNewsletterNotification(node.attrs.from, child);
774
+ break;
775
+ case "mex":
776
+ handleMexNotification(node.attrs.from, child);
777
+ break;
778
+ case "mediaretry":
779
+ const event = Utils_1.decodeMediaRetryNode(node);
780
+ ev.emit("messages.media-update", [event]);
781
+ break;
782
+ case "encrypt":
783
+ await handleEncryptNotification(node);
784
+ break;
785
+ case "devices":
786
+ const devices = WABinary_1.getBinaryNodeChildren(child, "device");
787
+ if (
788
+ WABinary_1.areJidsSameUser(child.attrs.jid, authState.creds.me.id)
789
+ ) {
790
+ const deviceJids = devices.map((d) => d.attrs.jid);
791
+ logger.info({ deviceJids }, "got my own devices");
792
+ }
793
+ break;
794
+ case "server_sync":
795
+ const update = WABinary_1.getBinaryNodeChild(node, "collection");
796
+ if (update) {
797
+ const name = update.attrs.name;
798
+ await resyncAppState([name], false);
799
+ }
800
+ break;
801
+ case "picture":
802
+ const setPicture = WABinary_1.getBinaryNodeChild(node, "set");
803
+ const delPicture = WABinary_1.getBinaryNodeChild(node, "delete");
804
+ ev.emit("contacts.update", [
805
+ {
806
+ id:
807
+ WABinary_1.jidNormalizedUser(node?.attrs?.from) ||
808
+ (setPicture || delPicture)?.attrs?.hash ||
809
+ "",
810
+ imgUrl: setPicture ? "changed" : "removed",
811
+ },
812
+ ]);
813
+ if (WABinary_1.isJidGroup(from)) {
814
+ const node = setPicture || delPicture;
815
+ result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON;
816
+ if (setPicture) {
817
+ result.messageStubParameters = [setPicture.attrs.id];
818
+ }
819
+ result.participant = node?.attrs?.author;
820
+ result.key = {
821
+ ...(result.key || {}),
822
+ participant: setPicture?.attrs?.author,
823
+ };
824
+ }
825
+ break;
826
+ case "account_sync":
827
+ if (child.tag === "disappearing_mode") {
828
+ const newDuration = +child.attrs.duration;
829
+ const timestamp = +child.attrs.t;
830
+ logger.info({ newDuration }, "updated account disappearing mode");
831
+ ev.emit("creds.update", {
832
+ accountSettings: {
833
+ ...authState.creds.accountSettings,
834
+ defaultDisappearingMode: {
835
+ ephemeralExpiration: newDuration,
836
+ ephemeralSettingTimestamp: timestamp,
837
+ },
838
+ },
839
+ });
840
+ } else if (child.tag === "blocklist") {
841
+ const blocklists = WABinary_1.getBinaryNodeChildren(child, "item");
842
+ for (const { attrs } of blocklists) {
843
+ const blocklist = [attrs.jid];
844
+ const type = attrs.action === "block" ? "add" : "remove";
845
+ ev.emit("blocklist.update", { blocklist, type });
846
+ }
847
+ }
848
+ break;
849
+ case "link_code_companion_reg":
850
+ const linkCodeCompanionReg = WABinary_1.getBinaryNodeChild(
851
+ node,
852
+ "link_code_companion_reg"
853
+ );
854
+ const ref = toRequiredBuffer(
855
+ WABinary_1.getBinaryNodeChildBuffer(
856
+ linkCodeCompanionReg,
857
+ "link_code_pairing_ref"
858
+ )
859
+ );
860
+ const primaryIdentityPublicKey = toRequiredBuffer(
861
+ WABinary_1.getBinaryNodeChildBuffer(
862
+ linkCodeCompanionReg,
863
+ "primary_identity_pub"
864
+ )
865
+ );
866
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(
867
+ WABinary_1.getBinaryNodeChildBuffer(
868
+ linkCodeCompanionReg,
869
+ "link_code_pairing_wrapped_primary_ephemeral_pub"
870
+ )
871
+ );
872
+ const codePairingPublicKey = await decipherLinkPublicKey(
873
+ primaryEphemeralPublicKeyWrapped
874
+ );
875
+ const companionSharedKey = Utils_1.Curve.sharedKey(
876
+ authState.creds.pairingEphemeralKeyPair.private,
877
+ codePairingPublicKey
878
+ );
879
+ const random = crypto_1.randomBytes(32);
880
+ const linkCodeSalt = crypto_1.randomBytes(32);
881
+
882
+ const linkCodePairingExpanded = await Utils_1.hkdf(
883
+ companionSharedKey,
884
+ 32,
885
+ {
886
+ salt: linkCodeSalt,
887
+ info: "link_code_pairing_key_bundle_encryption_key",
888
+ }
889
+ );
890
+
891
+ const encryptPayload = Buffer.concat([
892
+ Buffer.from(authState.creds.signedIdentityKey.public),
893
+ primaryIdentityPublicKey,
894
+ random,
895
+ ]);
896
+ const encryptIv = crypto_1.randomBytes(12);
897
+ const encrypted = Utils_1.aesEncryptGCM(
898
+ encryptPayload,
899
+ linkCodePairingExpanded,
900
+ encryptIv,
901
+ Buffer.alloc(0)
902
+ );
903
+ const encryptedPayload = Buffer.concat([
904
+ linkCodeSalt,
905
+ encryptIv,
906
+ encrypted,
907
+ ]);
908
+ const identitySharedKey = Utils_1.Curve.sharedKey(
909
+ authState.creds.signedIdentityKey.private,
910
+ primaryIdentityPublicKey
911
+ );
912
+ const identityPayload = Buffer.concat([
913
+ companionSharedKey,
914
+ identitySharedKey,
915
+ random,
916
+ ]);
917
+
918
+ authState.creds.advSecretKey = (
919
+ await Utils_1.hkdf(identityPayload, 32, { info: "adv_secret" })
920
+ ).toString("base64");
921
+
922
+ await query({
923
+ tag: "iq",
924
+ attrs: {
925
+ to: WABinary_1.S_WHATSAPP_NET,
926
+ type: "set",
927
+ id: Neele.generateMessageTag(),
928
+ xmlns: "md",
929
+ },
930
+ content: [
931
+ {
932
+ tag: "link_code_companion_reg",
933
+ attrs: {
934
+ jid: authState.creds.me.id,
935
+ stage: "companion_finish",
936
+ },
937
+ content: [
938
+ {
939
+ tag: "link_code_pairing_wrapped_key_bundle",
940
+ attrs: {},
941
+ content: encryptedPayload,
942
+ },
943
+ {
944
+ tag: "companion_identity_public",
945
+ attrs: {},
946
+ content: authState.creds.signedIdentityKey.public,
947
+ },
948
+ {
949
+ tag: "link_code_pairing_ref",
950
+ attrs: {},
951
+ content: ref,
952
+ },
953
+ ],
954
+ },
955
+ ],
956
+ });
957
+
958
+ authState.creds.registered = true;
959
+ ev.emit("creds.update", authState.creds);
960
+ }
961
+
962
+ if (Object.keys(result).length) {
963
+ return result;
964
+ }
965
+ };
966
+
967
+ async function decipherLinkPublicKey(data) {
968
+ const buffer = toRequiredBuffer(data);
969
+ const salt = buffer.slice(0, 32);
970
+ const secretKey = await Utils_1.derivePairingCodeKey(
971
+ authState.creds.pairingCode,
972
+ salt
973
+ );
974
+ const iv = buffer.slice(32, 48);
975
+ const payload = buffer.slice(48, 80);
976
+ return Utils_1.aesDecryptCTR(payload, secretKey, iv);
977
+ }
978
+
979
+ function toRequiredBuffer(data) {
980
+ if (data === undefined) {
981
+ throw new boom_1.Boom("Invalid buffer", { statusCode: 400 });
982
+ }
983
+ return data instanceof Buffer ? data : Buffer.from(data);
984
+ }
985
+
986
+ const willSendMessageAgain = (id, participant) => {
987
+ const key = `${id}:${participant}`;
988
+ const retryCount = msgRetryCache.get(key) || 0;
989
+ return retryCount < maxMsgRetryCount;
990
+ };
991
+
992
+ const updateSendMessageAgainCount = (id, participant) => {
993
+ const key = `${id}:${participant}`;
994
+ const newValue = (msgRetryCache.get(key) || 0) + 1;
995
+ msgRetryCache.set(key, newValue);
996
+ };
997
+
998
+ const sendMessagesAgain = async (key, ids, retryNode) => {
999
+ const msgs = await Promise.all(ids.map((id) => getMessage({ ...key, id })));
1000
+ const remoteJid = key.remoteJid;
1001
+ const participant = key.participant || remoteJid;
1002
+
1003
+ // if it's the primary jid sending the request
1004
+ // just re-send the message to everyone
1005
+ // prevents the first message decryption failure
1006
+ const sendToAll = !WABinary_1.jidDecode(participant)?.device;
1007
+ await assertSessions([participant], true);
1008
+
1009
+ if (WABinary_1.isJidGroup(remoteJid)) {
1010
+ await authState.keys.set({ "sender-key-memory": { [remoteJid]: null } });
1011
+ }
1012
+
1013
+ logger.debug(
1014
+ { participant, sendToAll },
1015
+ "forced new session for retry recp"
1016
+ );
1017
+
1018
+ for (const [i, msg] of msgs.entries()) {
1019
+ if (msg) {
1020
+ updateSendMessageAgainCount(ids[i], participant);
1021
+ const msgRelayOpts = { messageId: ids[i] };
1022
+
1023
+ if (sendToAll) {
1024
+ msgRelayOpts.useUserDevicesCache = false;
1025
+ } else {
1026
+ msgRelayOpts.participant = {
1027
+ jid: participant,
1028
+ count: +retryNode.attrs.count,
1029
+ };
1030
+ }
1031
+
1032
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
1033
+ } else {
1034
+ logger.debug(
1035
+ { jid: key.remoteJid, id: ids[i] },
1036
+ "recv retry request, but message not available"
1037
+ );
1038
+ }
1039
+ }
1040
+ };
1041
+
1042
+ const handleReceipt = async (node) => {
1043
+ const { attrs, content } = node;
1044
+ const isLid = attrs.from.includes("lid");
1045
+ const isNodeFromMe = WABinary_1.areJidsSameUser(
1046
+ attrs.participant || attrs.from,
1047
+ isLid ? authState.creds.me?.lid : authState.creds.me?.id
1048
+ );
1049
+ const remoteJid =
1050
+ !isNodeFromMe || WABinary_1.isJidGroup(attrs.from)
1051
+ ? attrs.from
1052
+ : attrs.recipient;
1053
+ const fromMe =
1054
+ !attrs.recipient ||
1055
+ ((attrs.type === "retry" || attrs.type === "sender") && isNodeFromMe);
1056
+
1057
+ const key = {
1058
+ remoteJid,
1059
+ id: "",
1060
+ fromMe,
1061
+ participant: attrs.participant,
1062
+ };
1063
+
1064
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== "@s.whatsapp.net") {
1065
+ logger.debug({ remoteJid }, "ignoring receipt from jid");
1066
+ await sendMessageAck(node);
1067
+ return;
1068
+ }
1069
+
1070
+ const ids = [attrs.id];
1071
+ if (Array.isArray(content)) {
1072
+ const items = WABinary_1.getBinaryNodeChildren(content[0], "item");
1073
+ ids.push(...items.map((i) => i.attrs.id));
1074
+ }
1075
+
1076
+ try {
1077
+ await Promise.all([
1078
+ processingMutex.mutex(async () => {
1079
+ const status = Utils_1.getStatusFromReceiptType(attrs.type);
1080
+
1081
+ if (
1082
+ typeof status !== "undefined" &&
1083
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
1084
+ // or another device of ours has read some messages
1085
+ (status >= WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK ||
1086
+ !isNodeFromMe)
1087
+ ) {
1088
+ if (
1089
+ WABinary_1.isJidGroup(remoteJid) ||
1090
+ WABinary_1.isJidStatusBroadcast(remoteJid)
1091
+ ) {
1092
+ if (attrs.participant) {
1093
+ const updateKey =
1094
+ status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK
1095
+ ? "receiptTimestamp"
1096
+ : "readTimestamp";
1097
+ ev.emit(
1098
+ "message-receipt.update",
1099
+ ids.map((id) => ({
1100
+ key: { ...key, id },
1101
+ receipt: {
1102
+ userJid: WABinary_1.jidNormalizedUser(attrs.participant),
1103
+ [updateKey]: +attrs.t,
1104
+ },
1105
+ }))
1106
+ );
1107
+ }
1108
+ } else {
1109
+ ev.emit(
1110
+ "messages.update",
1111
+ ids.map((id) => ({
1112
+ key: { ...key, id },
1113
+ update: { status },
1114
+ }))
1115
+ );
1116
+ }
1117
+ }
1118
+
1119
+ if (attrs.type === "retry") {
1120
+ // correctly set who is asking for the retry
1121
+ key.participant = key.participant || attrs.from;
1122
+ const retryNode = WABinary_1.getBinaryNodeChild(node, "retry");
1123
+
1124
+ if (willSendMessageAgain(ids[0], key.participant)) {
1125
+ if (key.fromMe) {
1126
+ try {
1127
+ logger.debug({ attrs, key }, "recv retry request");
1128
+ await sendMessagesAgain(key, ids, retryNode);
1129
+ } catch (error) {
1130
+ logger.error(
1131
+ { key, ids, trace: error.stack },
1132
+ "error in sending message again"
1133
+ );
1134
+ }
1135
+ } else {
1136
+ logger.info(
1137
+ { attrs, key },
1138
+ "recv retry for not fromMe message"
1139
+ );
1140
+ }
1141
+ } else {
1142
+ logger.info(
1143
+ { attrs, key },
1144
+ "will not send message again, as sent too many times"
1145
+ );
1146
+ }
1147
+ }
1148
+ }),
1149
+ ]);
1150
+ } finally {
1151
+ await sendMessageAck(node);
1152
+ }
1153
+ };
1154
+
1155
+ const handleNotification = async (node) => {
1156
+ const remoteJid = node.attrs.from;
1157
+
1158
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== "@s.whatsapp.net") {
1159
+ logger.debug({ remoteJid, id: node.attrs.id }, "ignored notification");
1160
+ await sendMessageAck(node);
1161
+ return;
1162
+ }
1163
+
1164
+ try {
1165
+ await Promise.all([
1166
+ processingMutex.mutex(async () => {
1167
+ const msg = await processNotification(node);
1168
+
1169
+ if (msg) {
1170
+ const fromMe = WABinary_1.areJidsSameUser(
1171
+ node.attrs.participant || remoteJid,
1172
+ authState.creds.me.id
1173
+ );
1174
+ msg.key = {
1175
+ remoteJid,
1176
+ fromMe,
1177
+ participant: node.attrs.participant,
1178
+ id: node.attrs.id,
1179
+ ...(msg.key || {}),
1180
+ };
1181
+ msg.participant = msg.participant
1182
+ ? msg.participant
1183
+ : node.attrs.participant;
1184
+ msg.messageTimestamp = +node.attrs.t;
1185
+ const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
1186
+ await upsertMessage(fullMsg, "append");
1187
+ }
1188
+ }),
1189
+ ]);
1190
+ } finally {
1191
+ await sendMessageAck(node);
1192
+ }
1193
+ };
1194
+
1195
+ const handleMessage = async (node) => {
1196
+ if (
1197
+ shouldIgnoreJid(node.attrs.from) &&
1198
+ node.attrs.from !== "@s.whatsapp.net"
1199
+ ) {
1200
+ logger.debug({ key: node.attrs.key }, "ignored message");
1201
+ await sendMessageAck(node);
1202
+ return;
1203
+ }
1204
+ const groupJid = node.attrs.from;
1205
+ const communityJid = linkedParentMap[groupJid];
1206
+ let response;
1207
+
1208
+ if (
1209
+ WABinary_1.getBinaryNodeChild(node, "unavailable") &&
1210
+ !WABinary_1.getBinaryNodeChild(node, "enc")
1211
+ ) {
1212
+ await sendMessageAck(node);
1213
+ const { key } = Utils_1.decodeMessageNode(
1214
+ node,
1215
+ authState.creds.me.id,
1216
+ authState.creds.me.lid || ""
1217
+ ).fullMessage;
1218
+ response = await requestPlaceholderResend(key);
1219
+
1220
+ if (response === "RESOLVED") {
1221
+ return;
1222
+ }
1223
+
1224
+ logger.debug(
1225
+ "received unavailable message, acked and requested resend from phone"
1226
+ );
1227
+ } else {
1228
+ if (placeholderResendCache.get(node.attrs.id)) {
1229
+ placeholderResendCache.del(node.attrs.id);
1230
+ }
1231
+ }
1232
+
1233
+ const {
1234
+ fullMessage: msg,
1235
+ category,
1236
+ author,
1237
+ decrypt,
1238
+ } = Utils_1.decryptMessageNode(
1239
+ node,
1240
+ authState.creds.me.id,
1241
+ authState.creds.me.lid || "",
1242
+ signalRepository,
1243
+ logger
1244
+ );
1245
+
1246
+ if (
1247
+ response &&
1248
+ msg?.messageStubParameters?.[0] === Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT
1249
+ ) {
1250
+ msg.messageStubParameters = [
1251
+ Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT,
1252
+ response,
1253
+ ];
1254
+ }
1255
+
1256
+ if (
1257
+ msg.message?.protocolMessage?.type ===
1258
+ WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER &&
1259
+ node.attrs.sender_pn
1260
+ ) {
1261
+ ev.emit("chats.phoneNumberShare", {
1262
+ lid: node.attrs.from,
1263
+ jid: node.attrs.sender_pn,
1264
+ });
1265
+ }
1266
+
1267
+ try {
1268
+ await Promise.all([
1269
+ processingMutex.mutex(async () => {
1270
+ const lidPnMappings = [];
1271
+ const normalizedFrom = normalizeOptionalJid(node.attrs.from);
1272
+ const normalizedParticipant = normalizeOptionalJid(
1273
+ node.attrs.participant
1274
+ );
1275
+ const normalizedSenderPn = normalizeOptionalJid(
1276
+ node.attrs.sender_pn || node.attrs.peer_recipient_pn
1277
+ );
1278
+ const normalizedParticipantPn = normalizeOptionalJid(
1279
+ node.attrs.participant_pn
1280
+ );
1281
+
1282
+ if (
1283
+ WABinary_1.isLidUser(normalizedFrom) &&
1284
+ normalizedSenderPn &&
1285
+ !WABinary_1.areJidsSameUser(normalizedFrom, normalizedSenderPn)
1286
+ ) {
1287
+ lidPnMappings.push({ lid: normalizedFrom, pn: normalizedSenderPn });
1288
+ }
1289
+
1290
+ if (
1291
+ WABinary_1.isLidUser(normalizedParticipant) &&
1292
+ normalizedParticipantPn &&
1293
+ !WABinary_1.areJidsSameUser(
1294
+ normalizedParticipant,
1295
+ normalizedParticipantPn
1296
+ )
1297
+ ) {
1298
+ lidPnMappings.push({
1299
+ lid: normalizedParticipant,
1300
+ pn: normalizedParticipantPn,
1301
+ });
1302
+ }
1303
+
1304
+ if (lidPnMappings.length > 0) {
1305
+ if (signalRepository?.lidMapping?.storeLIDPNMappings) {
1306
+ await signalRepository.lidMapping.storeLIDPNMappings(
1307
+ lidPnMappings
1308
+ );
1309
+ }
1310
+ if (signalRepository?.migrateSession) {
1311
+ for (const mapping of lidPnMappings) {
1312
+ await signalRepository.migrateSession(mapping.pn, mapping.lid);
1313
+ }
1314
+ }
1315
+ }
1316
+
1317
+ await decrypt();
1318
+ // message failed to decrypt
1319
+ if (
1320
+ msg.messageStubType ===
1321
+ WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT
1322
+ ) {
1323
+ if (
1324
+ msg?.messageStubParameters?.[0] ===
1325
+ Utils_1.MISSING_KEYS_ERROR_TEXT
1326
+ ) {
1327
+ return sendMessageAck(node, Utils_1.NACK_REASONS.ParsingError);
1328
+ }
1329
+
1330
+ retryMutex.mutex(async () => {
1331
+ if (ws.isOpen) {
1332
+ if (WABinary_1.getBinaryNodeChild(node, "unavailable")) {
1333
+ return;
1334
+ }
1335
+
1336
+ const encNode = WABinary_1.getBinaryNodeChild(node, "enc");
1337
+ await sendRetryRequest(node, !encNode);
1338
+
1339
+ if (retryRequestDelayMs) {
1340
+ await Utils_1.delay(retryRequestDelayMs);
1341
+ }
1342
+ } else {
1343
+ logger.debug({ node }, "connection closed, ignoring retry req");
1344
+ }
1345
+ });
1346
+ } else {
1347
+ // no type in the receipt => message delivered
1348
+ let type = undefined;
1349
+ if (communityJid) {
1350
+ msg.communityJid = communityJid;
1351
+ }
1352
+ const content = Utils_1.normalizeMessageContent(msg.message);
1353
+ const type_2 = Utils_1.getContentType(content);
1354
+ const message = msg.message[type_2];
1355
+ const participantPn = normalizeOptionalJid(node.attrs.participant_pn);
1356
+
1357
+ if (node?.attrs?.addressing_mode === "lid") {
1358
+ const metadata = await groupMetadata(node.attrs.from);
1359
+ let found = metadata.participants.find(
1360
+ (p) => p.lid === node.attrs.participant
1361
+ );
1362
+
1363
+ if (participantPn) {
1364
+ msg.key.participant = participantPn;
1365
+ } else if (found?.id) {
1366
+ msg.key.participant = found.id;
1367
+ }
1368
+
1369
+ if (message?.contextInfo?.participant) {
1370
+ found = metadata.participants.find(
1371
+ (p) => p.lid === msg.message[type_2].contextInfo.participant
1372
+ );
1373
+ if (found?.id) {
1374
+ msg.message[type_2].contextInfo.participant = found.id;
1375
+ }
1376
+ }
1377
+
1378
+ if (message?.contextInfo?.mentionedJid?.length > 0) {
1379
+ let mentions = [];
1380
+ for (const id of message.contextInfo.mentionedJid) {
1381
+ found = metadata.participants.find((p) => p.lid === id);
1382
+ mentions.push(found?.id || id);
1383
+ }
1384
+ msg.message[type_2].contextInfo.mentionedJid = mentions;
1385
+ }
1386
+ }
1387
+
1388
+ if (
1389
+ !WABinary_1.isJidGroup(node.attrs.from) &&
1390
+ WABinary_1.isLidUser(
1391
+ WABinary_1.jidNormalizedUser(node.attrs.from)
1392
+ )
1393
+ ) {
1394
+ const senderPn = WABinary_1.jidNormalizedUser(
1395
+ node.attrs.peer_recipient_pn || node.attrs.sender_pn
1396
+ );
1397
+ if (senderPn) {
1398
+ msg.key.remoteJid = senderPn;
1399
+ }
1400
+
1401
+ if (message?.contextInfo?.participant) {
1402
+ const isMe =
1403
+ msg.message[type_2].contextInfo.participant ===
1404
+ WABinary_1.jidNormalizedUser(authState.creds.me.lid);
1405
+ msg.message[type_2].contextInfo.participant = isMe
1406
+ ? WABinary_1.jidNormalizedUser(authState.creds.me.id)
1407
+ : senderPn || msg.message[type_2].contextInfo.participant;
1408
+ }
1409
+
1410
+ if (message?.contextInfo?.mentionedJid?.length > 0) {
1411
+ msg.message[type_2].contextInfo.mentionedJid = senderPn
1412
+ ? [senderPn]
1413
+ : msg.message[type_2].contextInfo.mentionedJid;
1414
+ }
1415
+ }
1416
+
1417
+ let participant = msg.key.participant;
1418
+
1419
+ if (category === "peer") {
1420
+ // special peer message
1421
+ type = "peer_msg";
1422
+ } else if (msg.key.fromMe) {
1423
+ // message was sent by us from a different device
1424
+ type = "sender";
1425
+ // need to specially handle this case
1426
+ if (WABinary_1.isJidUser(msg.key.remoteJid)) {
1427
+ participant = author;
1428
+ }
1429
+ } else if (!sendActiveReceipts) {
1430
+ type = "inactive";
1431
+ }
1432
+
1433
+ await sendReceipt(
1434
+ msg.key.remoteJid,
1435
+ participant,
1436
+ [msg.key.id],
1437
+ type
1438
+ );
1439
+ // send ack for history message
1440
+ const isAnyHistoryMsg = Utils_1.getHistoryMsg(msg.message);
1441
+
1442
+ if (isAnyHistoryMsg) {
1443
+ const jid = WABinary_1.jidNormalizedUser(msg.key.remoteJid);
1444
+ await sendReceipt(jid, undefined, [msg.key.id], "hist_sync");
1445
+ }
1446
+ }
1447
+
1448
+ // if (node?.attrs?.addressing_mode === 'lid' && node?.attrs?.participant_pn) {
1449
+ // msg.key.participant = WABinary_1.jidNormalizedUser(node.attrs.participant_pn)
1450
+ // }
1451
+
1452
+ Utils_1.cleanMessage(msg, authState.creds.me.id, authState.creds.me?.lid);
1453
+ await sendMessageAck(node);
1454
+ await upsertMessage(msg, node.attrs.offline ? "append" : "notify");
1455
+ }),
1456
+ ]);
1457
+ } catch (error) {
1458
+ logger.error({ error, node }, "error in handling message");
1459
+ }
1460
+ };
1461
+
1462
+ const fetchMessageHistory = async (
1463
+ count,
1464
+ oldestMsgKey,
1465
+ oldestMsgTimestamp
1466
+ ) => {
1467
+ if (!authState.creds.me?.id) {
1468
+ throw new boom_1.Boom("Not authenticated");
1469
+ }
1470
+
1471
+ const pdoMessage = {
1472
+ historySyncOnDemandRequest: {
1473
+ chatJid: oldestMsgKey.remoteJid,
1474
+ oldestMsgFromMe: oldestMsgKey.fromMe,
1475
+ oldestMsgId: oldestMsgKey.id,
1476
+ oldestMsgTimestampMs: oldestMsgTimestamp,
1477
+ onDemandMsgCount: count,
1478
+ },
1479
+ peerDataOperationRequestType:
1480
+ WAProto_1.proto.Message.PeerDataOperationRequestType
1481
+ .HISTORY_SYNC_ON_DEMAND,
1482
+ };
1483
+
1484
+ return sendPeerDataOperationMessage(pdoMessage);
1485
+ };
1486
+
1487
+ const requestPlaceholderResend = async (messageKey) => {
1488
+ if (!authState.creds.me?.id) {
1489
+ throw new boom_1.Boom("Not authenticated");
1490
+ }
1491
+
1492
+ if (placeholderResendCache.get(messageKey?.id)) {
1493
+ logger.debug({ messageKey }, "already requested resend");
1494
+ return;
1495
+ } else {
1496
+ placeholderResendCache.set(messageKey?.id, true);
1497
+ }
1498
+
1499
+ await Utils_1.delay(5000);
1500
+
1501
+ if (!placeholderResendCache.get(messageKey?.id)) {
1502
+ logger.debug({ messageKey }, "message received while resend requested");
1503
+ return "RESOLVED";
1504
+ }
1505
+
1506
+ const pdoMessage = {
1507
+ placeholderMessageResendRequest: [
1508
+ {
1509
+ messageKey,
1510
+ },
1511
+ ],
1512
+ peerDataOperationRequestType:
1513
+ WAProto_1.proto.Message.PeerDataOperationRequestType
1514
+ .PLACEHOLDER_MESSAGE_RESEND,
1515
+ };
1516
+
1517
+ setTimeout(() => {
1518
+ if (placeholderResendCache.get(messageKey?.id)) {
1519
+ logger.debug(
1520
+ { messageKey },
1521
+ "PDO message without response after 15 seconds. Phone possibly offline"
1522
+ );
1523
+ placeholderResendCache.del(messageKey?.id);
1524
+ }
1525
+ }, 15000);
1526
+
1527
+ return sendPeerDataOperationMessage(pdoMessage);
1528
+ };
1529
+
1530
+ const handleCall = async (node) => {
1531
+ let status;
1532
+
1533
+ const { attrs } = node;
1534
+ const [infoChild] = WABinary_1.getAllBinaryNodeChildren(node);
1535
+ const callId = infoChild.attrs["call-id"];
1536
+ const from = infoChild.attrs.from || infoChild.attrs["call-creator"];
1537
+ status = Utils_1.getCallStatusFromNode(infoChild);
1538
+
1539
+ if (WABinary_1.isLidUser(from) && infoChild.tag === "relaylatency") {
1540
+ const verify = callOfferCache.get(callId);
1541
+
1542
+ if (!verify) {
1543
+ status = "offer";
1544
+
1545
+ const callLid = {
1546
+ chatId: attrs.from,
1547
+ from,
1548
+ id: callId,
1549
+ date: new Date(+attrs.t * 1000),
1550
+ offline: !!attrs.offline,
1551
+ status,
1552
+ };
1553
+ callOfferCache.set(callId, callLid);
1554
+ }
1555
+ }
1556
+
1557
+ const call = {
1558
+ chatId: attrs.from,
1559
+ from,
1560
+ id: callId,
1561
+ date: new Date(+attrs.t * 1000),
1562
+ offline: !!attrs.offline,
1563
+ status,
1564
+ };
1565
+
1566
+ if (status === "offer") {
1567
+ call.isVideo = !!WABinary_1.getBinaryNodeChild(infoChild, "video");
1568
+ call.isGroup =
1569
+ infoChild.attrs.type === "group" || !!infoChild.attrs["group-jid"];
1570
+ call.groupJid = infoChild.attrs["group-jid"];
1571
+ callOfferCache.set(call.id, call);
1572
+ }
1573
+
1574
+ const existingCall = callOfferCache.get(call.id);
1575
+
1576
+ // use existing call info to populate this event
1577
+ if (existingCall) {
1578
+ call.isVideo = existingCall.isVideo;
1579
+ call.isGroup = existingCall.isGroup;
1580
+ }
1581
+
1582
+ // delete data once call has ended
1583
+ if (
1584
+ status === "reject" ||
1585
+ status === "accept" ||
1586
+ status === "timeout" ||
1587
+ status === "terminate"
1588
+ ) {
1589
+ callOfferCache.del(call.id);
1590
+ }
1591
+
1592
+ ev.emit("call", [call]);
1593
+
1594
+ await sendMessageAck(node);
1595
+ };
1596
+
1597
+ const handleBadAck = async ({ attrs }) => {
1598
+ const key = {
1599
+ remoteJid: attrs.from,
1600
+ fromMe: true,
1601
+ id: attrs.id,
1602
+ newsletter_server_id: attrs?.server_id,
1603
+ };
1604
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
1605
+ // // current hypothesis is that if pash is sent in the ack
1606
+ // // it means -- the message hasn't reached all devices yet
1607
+ // // we'll retry sending the message here
1608
+ // if(attrs.phash) {
1609
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
1610
+ // const msg = await getMessage(key)
1611
+ // if(msg) {
1612
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
1613
+ // } else {
1614
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
1615
+ // }
1616
+ // }
1617
+ // error in acknowledgement,
1618
+ // device could not display the message
1619
+ if (attrs.error) {
1620
+ logger.warn({ attrs }, "received error in ack");
1621
+ ev.emit("messages.update", [
1622
+ {
1623
+ key,
1624
+ update: {
1625
+ status: Types_1.WAMessageStatus.ERROR,
1626
+ messageStubParameters: [attrs.error],
1627
+ },
1628
+ },
1629
+ ]);
1630
+ }
1631
+ };
1632
+
1633
+ /// processes a node with the given function
1634
+ /// and adds the task to the existing buffer if we're buffering events
1635
+ const processNodeWithBuffer = async (node, identifier, exec) => {
1636
+ ev.buffer();
1637
+ await execTask();
1638
+ ev.flush();
1639
+ function execTask() {
1640
+ return exec(node, false).catch((err) =>
1641
+ onUnexpectedError(err, identifier)
1642
+ );
1643
+ }
1644
+ };
1645
+
1646
+ let latestNodeInMemory = null;
1647
+ const nodelogger = (node) => {
1648
+ if (!node) return null;
1649
+ latestNodeInMemory = node;
1650
+ return latestNodeInMemory;
1651
+ };
1652
+ const setNodeLoggerListener = () => {
1653
+ return latestNodeInMemory;
1654
+ };
1655
+
1656
+ const makeOfflineNodeProcessor = () => {
1657
+ const nodeProcessorMap = new Map([
1658
+ ["message", handleMessage],
1659
+ ["call", handleCall],
1660
+ ["receipt", handleReceipt],
1661
+ ["notification", handleNotification],
1662
+ ]);
1663
+
1664
+ const nodes = [];
1665
+ let isProcessing = false;
1666
+
1667
+ const enqueue = (type, node) => {
1668
+ nodes.push({ type, node });
1669
+
1670
+ if (isProcessing) {
1671
+ return;
1672
+ }
1673
+
1674
+ isProcessing = true;
1675
+
1676
+ const promise = async () => {
1677
+ while (nodes.length && ws.isOpen) {
1678
+ const { type, node } = nodes.shift();
1679
+ const nodeProcessor = nodeProcessorMap.get(type);
1680
+ if (!nodeProcessor) {
1681
+ onUnexpectedError(
1682
+ new Error(`unknown offline node type: ${type}`),
1683
+ "processing offline node"
1684
+ );
1685
+ continue;
1686
+ }
1687
+ await nodeProcessor(node);
1688
+ }
1689
+ isProcessing = false;
1690
+ };
1691
+ promise().catch((error) =>
1692
+ onUnexpectedError(error, "processing offline nodes")
1693
+ );
1694
+ };
1695
+
1696
+ return { enqueue };
1697
+ };
1698
+
1699
+ const offlineNodeProcessor = makeOfflineNodeProcessor();
1700
+
1701
+ const processNode = (type, node, identifier, exec) => {
1702
+ const isOffline = !!node.attrs.offline;
1703
+
1704
+ if (isOffline) {
1705
+ offlineNodeProcessor.enqueue(type, node);
1706
+ } else {
1707
+ processNodeWithBuffer(node, identifier, exec);
1708
+ }
1709
+ };
1710
+
1711
+ // recv a message
1712
+ ws.on("CB:message", (node) => {
1713
+ processNode("message", node, "processing message", handleMessage);
1714
+ nodelogger(node);
1715
+ const messageJid = node.attrs.from;
1716
+
1717
+ if (linkedParentMap[messageJid]) {
1718
+ // console.log(`Community JID for ${messageJid}: ${linkedParentMap[messageJid]}`);
1719
+ } else {
1720
+ // console.log(`No Community JID found for ${messageJid}`);
1721
+ }
1722
+ });
1723
+ ws.on("CB:call", async (node) => {
1724
+ processNode("call", node, "handling call", handleCall);
1725
+ nodelogger(node);
1726
+ });
1727
+ ws.on("CB:receipt", (node) => {
1728
+ processNode("receipt", node, "handling receipt", handleReceipt);
1729
+ });
1730
+ ws.on("CB:notification", async (node) => {
1731
+ processNode(
1732
+ "notification",
1733
+ node,
1734
+ "handling notification",
1735
+ handleNotification
1736
+ );
1737
+ // nodelogger(node)
1738
+ });
1739
+ ws.on("CB:ack,class:message", (node) => {
1740
+ handleBadAck(node).catch((error) =>
1741
+ onUnexpectedError(error, "handling bad ack")
1742
+ );
1743
+ // nodelogger(node)
1744
+ });
1745
+ const linkedParentMap = {};
1746
+ ws.on("CB:iq", (node) => {
1747
+ if (node && node.tag === "iq" && node.attrs.type === "result") {
1748
+ const groups = node.content;
1749
+
1750
+ if (Array.isArray(groups)) {
1751
+ for (const group of groups) {
1752
+ const groupId = group.attrs.id + "@g.us";
1753
+
1754
+ if (group && Array.isArray(group.content)) {
1755
+ for (const item of group.content) {
1756
+ if (
1757
+ item.tag === "linked_parent" &&
1758
+ item.attrs &&
1759
+ item.attrs.jid
1760
+ ) {
1761
+ linkedParentMap[groupId] = item.attrs.jid;
1762
+ }
1763
+ }
1764
+ }
1765
+ }
1766
+ }
1767
+ }
1768
+ });
1769
+ // codes in telegram channel @wegschleifen
1770
+ ev.on("call", ([call]) => {
1771
+ // missed call + group call notification message generation
1772
+ if (
1773
+ call.status === "timeout" ||
1774
+ (call.status === "offer" && call.isGroup)
1775
+ ) {
1776
+ const msg = {
1777
+ key: {
1778
+ remoteJid: call.chatId,
1779
+ id: call.id,
1780
+ fromMe: false,
1781
+ },
1782
+ messageTimestamp: Utils_1.unixTimestampSeconds(call.date),
1783
+ };
1784
+
1785
+ if (call.status === "timeout") {
1786
+ if (call.isGroup) {
1787
+ msg.messageStubType = call.isVideo
1788
+ ? Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO
1789
+ : Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE;
1790
+ } else {
1791
+ msg.messageStubType = call.isVideo
1792
+ ? Types_1.WAMessageStubType.CALL_MISSED_VIDEO
1793
+ : Types_1.WAMessageStubType.CALL_MISSED_VOICE;
1794
+ }
1795
+ } else {
1796
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
1797
+ }
1798
+
1799
+ const protoMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
1800
+ upsertMessage(protoMsg, call.offline ? "append" : "notify");
1801
+ }
1802
+ });
1803
+
1804
+ ev.on("connection.update", ({ isOnline }) => {
1805
+ if (typeof isOnline !== "undefined") {
1806
+ sendActiveReceipts = isOnline;
1807
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1808
+ }
1809
+ });
1810
+
1811
+ return {
1812
+ ...Neele,
1813
+ sendMessageAck,
1814
+ sendRetryRequest,
1815
+ offerCall,
1816
+ rejectCall,
1817
+ nodelogger,
1818
+ setNodeLoggerListener,
1819
+ fetchMessageHistory,
1820
+ requestPlaceholderResend,
1821
+ };
1822
+ };
1823
+
1824
+ module.exports = {
1825
+ makeMessagesRecvSocket,
1826
+ };