@d0v3riz/baileys 6.3.0

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 (147) hide show
  1. package/README.md +956 -0
  2. package/WAProto/GenerateStatics.sh +4 -0
  3. package/WAProto/WAProto.proto +2845 -0
  4. package/WAProto/index.d.ts +32006 -0
  5. package/WAProto/index.js +87184 -0
  6. package/WASignalGroup/GroupProtocol.js +1697 -0
  7. package/WASignalGroup/ciphertext_message.js +16 -0
  8. package/WASignalGroup/group_cipher.js +106 -0
  9. package/WASignalGroup/group_session_builder.js +46 -0
  10. package/WASignalGroup/index.js +5 -0
  11. package/WASignalGroup/keyhelper.js +21 -0
  12. package/WASignalGroup/protobufs.js +3 -0
  13. package/WASignalGroup/readme.md +6 -0
  14. package/WASignalGroup/sender_chain_key.js +50 -0
  15. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  16. package/WASignalGroup/sender_key_message.js +92 -0
  17. package/WASignalGroup/sender_key_name.js +70 -0
  18. package/WASignalGroup/sender_key_record.js +54 -0
  19. package/WASignalGroup/sender_key_state.js +129 -0
  20. package/WASignalGroup/sender_message_key.js +39 -0
  21. package/lib/Defaults/baileys-version.json +3 -0
  22. package/lib/Defaults/index.d.ts +284 -0
  23. package/lib/Defaults/index.js +115 -0
  24. package/lib/Defaults/phonenumber-mcc.json +223 -0
  25. package/lib/Signal/libsignal.d.ts +3 -0
  26. package/lib/Signal/libsignal.js +151 -0
  27. package/lib/Socket/Client/abstract-socket-client.d.ts +16 -0
  28. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  29. package/lib/Socket/Client/index.d.ts +3 -0
  30. package/lib/Socket/Client/index.js +19 -0
  31. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  32. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  33. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  34. package/lib/Socket/Client/web-socket-client.js +62 -0
  35. package/lib/Socket/business.d.ts +124 -0
  36. package/lib/Socket/business.js +259 -0
  37. package/lib/Socket/chats.d.ts +74 -0
  38. package/lib/Socket/chats.js +838 -0
  39. package/lib/Socket/groups.d.ts +105 -0
  40. package/lib/Socket/groups.js +291 -0
  41. package/lib/Socket/index.d.ts +126 -0
  42. package/lib/Socket/index.js +10 -0
  43. package/lib/Socket/messages-recv.d.ts +112 -0
  44. package/lib/Socket/messages-recv.js +641 -0
  45. package/lib/Socket/messages-send.d.ts +110 -0
  46. package/lib/Socket/messages-send.js +648 -0
  47. package/lib/Socket/registration.d.ts +211 -0
  48. package/lib/Socket/registration.js +166 -0
  49. package/lib/Socket/socket.d.ts +42 -0
  50. package/lib/Socket/socket.js +527 -0
  51. package/lib/Store/index.d.ts +3 -0
  52. package/lib/Store/index.js +10 -0
  53. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  54. package/lib/Store/make-cache-manager-store.js +83 -0
  55. package/lib/Store/make-in-memory-store.d.ts +117 -0
  56. package/lib/Store/make-in-memory-store.js +435 -0
  57. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  58. package/lib/Store/make-ordered-dictionary.js +81 -0
  59. package/lib/Store/object-repository.d.ts +10 -0
  60. package/lib/Store/object-repository.js +27 -0
  61. package/lib/Types/Auth.d.ts +106 -0
  62. package/lib/Types/Auth.js +2 -0
  63. package/lib/Types/Call.d.ts +12 -0
  64. package/lib/Types/Call.js +2 -0
  65. package/lib/Types/Chat.d.ts +102 -0
  66. package/lib/Types/Chat.js +4 -0
  67. package/lib/Types/Contact.d.ts +18 -0
  68. package/lib/Types/Contact.js +2 -0
  69. package/lib/Types/Events.d.ts +152 -0
  70. package/lib/Types/Events.js +2 -0
  71. package/lib/Types/GroupMetadata.d.ts +42 -0
  72. package/lib/Types/GroupMetadata.js +2 -0
  73. package/lib/Types/Label.d.ts +35 -0
  74. package/lib/Types/Label.js +27 -0
  75. package/lib/Types/LabelAssociation.d.ts +29 -0
  76. package/lib/Types/LabelAssociation.js +9 -0
  77. package/lib/Types/Message.d.ts +245 -0
  78. package/lib/Types/Message.js +9 -0
  79. package/lib/Types/Product.d.ts +78 -0
  80. package/lib/Types/Product.js +2 -0
  81. package/lib/Types/Signal.d.ts +57 -0
  82. package/lib/Types/Signal.js +2 -0
  83. package/lib/Types/Socket.d.ts +106 -0
  84. package/lib/Types/Socket.js +2 -0
  85. package/lib/Types/State.d.ts +27 -0
  86. package/lib/Types/State.js +2 -0
  87. package/lib/Types/index.d.ts +54 -0
  88. package/lib/Types/index.js +39 -0
  89. package/lib/Utils/auth-utils.d.ts +18 -0
  90. package/lib/Utils/auth-utils.js +202 -0
  91. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  92. package/lib/Utils/baileys-event-stream.js +63 -0
  93. package/lib/Utils/business.d.ts +22 -0
  94. package/lib/Utils/business.js +234 -0
  95. package/lib/Utils/chat-utils.d.ts +71 -0
  96. package/lib/Utils/chat-utils.js +710 -0
  97. package/lib/Utils/crypto.d.ts +38 -0
  98. package/lib/Utils/crypto.js +137 -0
  99. package/lib/Utils/decode-wa-message.d.ts +19 -0
  100. package/lib/Utils/decode-wa-message.js +160 -0
  101. package/lib/Utils/event-buffer.d.ts +35 -0
  102. package/lib/Utils/event-buffer.js +514 -0
  103. package/lib/Utils/generics.d.ts +92 -0
  104. package/lib/Utils/generics.js +368 -0
  105. package/lib/Utils/history.d.ts +15 -0
  106. package/lib/Utils/history.js +91 -0
  107. package/lib/Utils/index.d.ts +17 -0
  108. package/lib/Utils/index.js +33 -0
  109. package/lib/Utils/link-preview.d.ts +21 -0
  110. package/lib/Utils/link-preview.js +116 -0
  111. package/lib/Utils/logger.d.ts +4 -0
  112. package/lib/Utils/logger.js +7 -0
  113. package/lib/Utils/lt-hash.d.ts +12 -0
  114. package/lib/Utils/lt-hash.js +51 -0
  115. package/lib/Utils/make-mutex.d.ts +7 -0
  116. package/lib/Utils/make-mutex.js +43 -0
  117. package/lib/Utils/messages-media.d.ts +101 -0
  118. package/lib/Utils/messages-media.js +632 -0
  119. package/lib/Utils/messages.d.ts +75 -0
  120. package/lib/Utils/messages.js +738 -0
  121. package/lib/Utils/noise-handler.d.ts +20 -0
  122. package/lib/Utils/noise-handler.js +142 -0
  123. package/lib/Utils/process-message.d.ts +41 -0
  124. package/lib/Utils/process-message.js +297 -0
  125. package/lib/Utils/signal.d.ts +32 -0
  126. package/lib/Utils/signal.js +151 -0
  127. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  128. package/lib/Utils/use-multi-file-auth-state.js +80 -0
  129. package/lib/Utils/validate-connection.d.ts +11 -0
  130. package/lib/Utils/validate-connection.js +188 -0
  131. package/lib/WABinary/constants.d.ts +27 -0
  132. package/lib/WABinary/constants.js +40 -0
  133. package/lib/WABinary/decode.d.ts +7 -0
  134. package/lib/WABinary/decode.js +252 -0
  135. package/lib/WABinary/encode.d.ts +3 -0
  136. package/lib/WABinary/encode.js +228 -0
  137. package/lib/WABinary/generic-utils.d.ts +15 -0
  138. package/lib/WABinary/generic-utils.js +110 -0
  139. package/lib/WABinary/index.d.ts +5 -0
  140. package/lib/WABinary/index.js +21 -0
  141. package/lib/WABinary/jid-utils.d.ts +27 -0
  142. package/lib/WABinary/jid-utils.js +56 -0
  143. package/lib/WABinary/types.d.ts +18 -0
  144. package/lib/WABinary/types.js +2 -0
  145. package/lib/index.d.ts +9 -0
  146. package/lib/index.js +27 -0
  147. package/package.json +100 -0
@@ -0,0 +1,641 @@
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 node_cache_1 = __importDefault(require("node-cache"));
8
+ const WAProto_1 = require("../../WAProto");
9
+ const Defaults_1 = require("../Defaults");
10
+ const Types_1 = require("../Types");
11
+ const Utils_1 = require("../Utils");
12
+ const make_mutex_1 = require("../Utils/make-mutex");
13
+ const process_message_1 = require("../Utils/process-message");
14
+ const WABinary_1 = require("../WABinary");
15
+ const groups_1 = require("./groups");
16
+ const messages_send_1 = require("./messages-send");
17
+ const makeMessagesRecvSocket = (config) => {
18
+ const { logger, retryRequestDelayMs, getMessage, shouldIgnoreJid } = config;
19
+ const sock = (0, messages_send_1.makeMessagesSocket)(config);
20
+ const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, } = sock;
21
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
22
+ const retryMutex = (0, make_mutex_1.makeMutex)();
23
+ const msgRetryCache = config.msgRetryCounterCache || new node_cache_1.default({
24
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
25
+ useClones: false
26
+ });
27
+ const callOfferCache = config.callOfferCache || new node_cache_1.default({
28
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER,
29
+ useClones: false
30
+ });
31
+ let sendActiveReceipts = false;
32
+ const sendMessageAck = async ({ tag, attrs }) => {
33
+ const stanza = {
34
+ tag: 'ack',
35
+ attrs: {
36
+ id: attrs.id,
37
+ to: attrs.from,
38
+ class: tag,
39
+ }
40
+ };
41
+ if (!!attrs.participant) {
42
+ stanza.attrs.participant = attrs.participant;
43
+ }
44
+ if (!!attrs.recipient) {
45
+ stanza.attrs.recipient = attrs.recipient;
46
+ }
47
+ if (tag !== 'message' && attrs.type) {
48
+ stanza.attrs.type = attrs.type;
49
+ }
50
+ logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
51
+ await sendNode(stanza);
52
+ };
53
+ const rejectCall = async (callId, callFrom) => {
54
+ const stanza = ({
55
+ tag: 'call',
56
+ attrs: {
57
+ from: authState.creds.me.id,
58
+ to: callFrom,
59
+ },
60
+ content: [{
61
+ tag: 'reject',
62
+ attrs: {
63
+ 'call-id': callId,
64
+ 'call-creator': callFrom,
65
+ count: '0',
66
+ },
67
+ content: undefined,
68
+ }],
69
+ });
70
+ await query(stanza);
71
+ };
72
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
73
+ const msgId = node.attrs.id;
74
+ let retryCount = msgRetryCache.get(msgId) || 0;
75
+ if (retryCount >= 5) {
76
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
77
+ msgRetryCache.del(msgId);
78
+ return;
79
+ }
80
+ retryCount += 1;
81
+ msgRetryCache.set(msgId, retryCount);
82
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
83
+ const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
84
+ await authState.keys.transaction(async () => {
85
+ const receipt = {
86
+ tag: 'receipt',
87
+ attrs: {
88
+ id: msgId,
89
+ type: 'retry',
90
+ to: node.attrs.from
91
+ },
92
+ content: [
93
+ {
94
+ tag: 'retry',
95
+ attrs: {
96
+ count: retryCount.toString(),
97
+ id: node.attrs.id,
98
+ t: node.attrs.t,
99
+ v: '1'
100
+ }
101
+ },
102
+ {
103
+ tag: 'registration',
104
+ attrs: {},
105
+ content: (0, Utils_1.encodeBigEndian)(authState.creds.registrationId)
106
+ }
107
+ ]
108
+ };
109
+ if (node.attrs.recipient) {
110
+ receipt.attrs.recipient = node.attrs.recipient;
111
+ }
112
+ if (node.attrs.participant) {
113
+ receipt.attrs.participant = node.attrs.participant;
114
+ }
115
+ if (retryCount > 1 || forceIncludeKeys) {
116
+ const { update, preKeys } = await (0, Utils_1.getNextPreKeys)(authState, 1);
117
+ const [keyId] = Object.keys(preKeys);
118
+ const key = preKeys[+keyId];
119
+ const content = receipt.content;
120
+ content.push({
121
+ tag: 'keys',
122
+ attrs: {},
123
+ content: [
124
+ { tag: 'type', attrs: {}, content: Buffer.from(Defaults_1.KEY_BUNDLE_TYPE) },
125
+ { tag: 'identity', attrs: {}, content: identityKey.public },
126
+ (0, Utils_1.xmppPreKey)(key, +keyId),
127
+ (0, Utils_1.xmppSignedPreKey)(signedPreKey),
128
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
129
+ ]
130
+ });
131
+ ev.emit('creds.update', update);
132
+ }
133
+ await sendNode(receipt);
134
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
135
+ });
136
+ };
137
+ const handleEncryptNotification = async (node) => {
138
+ const from = node.attrs.from;
139
+ if (from === WABinary_1.S_WHATSAPP_NET) {
140
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(node, 'count');
141
+ const count = +countChild.attrs.value;
142
+ const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT;
143
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
144
+ if (shouldUploadMorePreKeys) {
145
+ await uploadPreKeys();
146
+ }
147
+ }
148
+ else {
149
+ const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, 'identity');
150
+ if (identityNode) {
151
+ logger.info({ jid: from }, 'identity changed');
152
+ // not handling right now
153
+ // signal will override new identity anyway
154
+ }
155
+ else {
156
+ logger.info({ node }, 'unknown encrypt notification');
157
+ }
158
+ }
159
+ };
160
+ const handleGroupNotification = (participant, child, msg) => {
161
+ switch (child === null || child === void 0 ? void 0 : child.tag) {
162
+ case 'create':
163
+ const metadata = (0, groups_1.extractGroupMetadata)(child);
164
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
165
+ msg.messageStubParameters = [metadata.subject];
166
+ msg.key = { participant: metadata.owner };
167
+ ev.emit('chats.upsert', [{
168
+ id: metadata.id,
169
+ name: metadata.subject,
170
+ conversationTimestamp: metadata.creation,
171
+ }]);
172
+ ev.emit('groups.upsert', [metadata]);
173
+ break;
174
+ case 'ephemeral':
175
+ case 'not_ephemeral':
176
+ msg.message = {
177
+ protocolMessage: {
178
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
179
+ ephemeralExpiration: +(child.attrs.expiration || 0)
180
+ }
181
+ };
182
+ break;
183
+ case 'promote':
184
+ case 'demote':
185
+ case 'remove':
186
+ case 'add':
187
+ case 'leave':
188
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
189
+ msg.messageStubType = Types_1.WAMessageStubType[stubType];
190
+ const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
191
+ if (participants.length === 1 &&
192
+ // if recv. "remove" message and sender removed themselves
193
+ // mark as left
194
+ (0, WABinary_1.areJidsSameUser)(participants[0], participant) &&
195
+ child.tag === 'remove') {
196
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
197
+ }
198
+ msg.messageStubParameters = participants;
199
+ break;
200
+ case 'subject':
201
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
202
+ msg.messageStubParameters = [child.attrs.subject];
203
+ break;
204
+ case 'announcement':
205
+ case 'not_announcement':
206
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
207
+ msg.messageStubParameters = [(child.tag === 'announcement') ? 'on' : 'off'];
208
+ break;
209
+ case 'locked':
210
+ case 'unlocked':
211
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT;
212
+ msg.messageStubParameters = [(child.tag === 'locked') ? 'on' : 'off'];
213
+ break;
214
+ case 'invite':
215
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
216
+ msg.messageStubParameters = [child.attrs.code];
217
+ break;
218
+ }
219
+ };
220
+ const processNotification = async (node) => {
221
+ const result = {};
222
+ const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
223
+ const nodeType = node.attrs.type;
224
+ const from = (0, WABinary_1.jidNormalizedUser)(node.attrs.from);
225
+ switch (nodeType) {
226
+ case 'privacy_token':
227
+ const tokenList = (0, WABinary_1.getBinaryNodeChildren)(child, 'token');
228
+ for (const { attrs, content } of tokenList) {
229
+ const jid = attrs.jid;
230
+ ev.emit('chats.update', [
231
+ {
232
+ id: jid,
233
+ tcToken: content
234
+ }
235
+ ]);
236
+ logger.debug({ jid }, 'got privacy token update');
237
+ }
238
+ break;
239
+ case 'w:gp2':
240
+ handleGroupNotification(node.attrs.participant, child, result);
241
+ break;
242
+ case 'mediaretry':
243
+ const event = (0, Utils_1.decodeMediaRetryNode)(node);
244
+ ev.emit('messages.media-update', [event]);
245
+ break;
246
+ case 'encrypt':
247
+ await handleEncryptNotification(node);
248
+ break;
249
+ case 'devices':
250
+ const devices = (0, WABinary_1.getBinaryNodeChildren)(child, 'device');
251
+ if ((0, WABinary_1.areJidsSameUser)(child.attrs.jid, authState.creds.me.id)) {
252
+ const deviceJids = devices.map(d => d.attrs.jid);
253
+ logger.info({ deviceJids }, 'got my own devices');
254
+ }
255
+ break;
256
+ case 'server_sync':
257
+ const update = (0, WABinary_1.getBinaryNodeChild)(node, 'collection');
258
+ if (update) {
259
+ const name = update.attrs.name;
260
+ await resyncAppState([name], false);
261
+ }
262
+ break;
263
+ case 'picture':
264
+ const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set');
265
+ const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete');
266
+ ev.emit('contacts.update', [{
267
+ id: from,
268
+ imgUrl: setPicture ? 'changed' : null
269
+ }]);
270
+ if ((0, WABinary_1.isJidGroup)(from)) {
271
+ const node = setPicture || delPicture;
272
+ result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON;
273
+ if (setPicture) {
274
+ result.messageStubParameters = [setPicture.attrs.id];
275
+ }
276
+ result.participant = node === null || node === void 0 ? void 0 : node.attrs.author;
277
+ result.key = {
278
+ ...result.key || {},
279
+ participant: setPicture === null || setPicture === void 0 ? void 0 : setPicture.attrs.author
280
+ };
281
+ }
282
+ break;
283
+ case 'account_sync':
284
+ if (child.tag === 'disappearing_mode') {
285
+ const newDuration = +child.attrs.duration;
286
+ const timestamp = +child.attrs.t;
287
+ logger.info({ newDuration }, 'updated account disappearing mode');
288
+ ev.emit('creds.update', {
289
+ accountSettings: {
290
+ ...authState.creds.accountSettings,
291
+ defaultDisappearingMode: {
292
+ ephemeralExpiration: newDuration,
293
+ ephemeralSettingTimestamp: timestamp,
294
+ },
295
+ }
296
+ });
297
+ }
298
+ break;
299
+ }
300
+ if (Object.keys(result).length) {
301
+ return result;
302
+ }
303
+ };
304
+ const willSendMessageAgain = (id, participant) => {
305
+ const key = `${id}:${participant}`;
306
+ const retryCount = msgRetryCache.get(key) || 0;
307
+ return retryCount < 5;
308
+ };
309
+ const updateSendMessageAgainCount = (id, participant) => {
310
+ const key = `${id}:${participant}`;
311
+ const newValue = (msgRetryCache.get(key) || 0) + 1;
312
+ msgRetryCache.set(key, newValue);
313
+ };
314
+ const sendMessagesAgain = async (key, ids, retryNode) => {
315
+ var _a;
316
+ const msgs = await Promise.all(ids.map(id => getMessage({ ...key, id })));
317
+ const remoteJid = key.remoteJid;
318
+ const participant = key.participant || remoteJid;
319
+ // if it's the primary jid sending the request
320
+ // just re-send the message to everyone
321
+ // prevents the first message decryption failure
322
+ const sendToAll = !((_a = (0, WABinary_1.jidDecode)(participant)) === null || _a === void 0 ? void 0 : _a.device);
323
+ await assertSessions([participant], true);
324
+ if ((0, WABinary_1.isJidGroup)(remoteJid)) {
325
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
326
+ }
327
+ logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
328
+ for (let i = 0; i < msgs.length; i++) {
329
+ const msg = msgs[i];
330
+ if (msg) {
331
+ updateSendMessageAgainCount(ids[i], participant);
332
+ const msgRelayOpts = { messageId: ids[i] };
333
+ if (sendToAll) {
334
+ msgRelayOpts.useUserDevicesCache = false;
335
+ }
336
+ else {
337
+ msgRelayOpts.participant = {
338
+ jid: participant,
339
+ count: +retryNode.attrs.count
340
+ };
341
+ }
342
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
343
+ }
344
+ else {
345
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
346
+ }
347
+ }
348
+ };
349
+ const handleReceipt = async (node) => {
350
+ var _a;
351
+ const { attrs, content } = node;
352
+ const isNodeFromMe = (0, WABinary_1.areJidsSameUser)(attrs.participant || attrs.from, (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id);
353
+ const remoteJid = !isNodeFromMe || (0, WABinary_1.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient;
354
+ const fromMe = !attrs.recipient || (attrs.type === 'retry' && isNodeFromMe);
355
+ const key = {
356
+ remoteJid,
357
+ id: '',
358
+ fromMe,
359
+ participant: attrs.participant
360
+ };
361
+ if (shouldIgnoreJid(remoteJid)) {
362
+ logger.debug({ remoteJid }, 'ignoring receipt from jid');
363
+ await sendMessageAck(node);
364
+ return;
365
+ }
366
+ const ids = [attrs.id];
367
+ if (Array.isArray(content)) {
368
+ const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], 'item');
369
+ ids.push(...items.map(i => i.attrs.id));
370
+ }
371
+ await Promise.all([
372
+ processingMutex.mutex(async () => {
373
+ const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
374
+ if (typeof status !== 'undefined' &&
375
+ (
376
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
377
+ // or another device of ours has read some messages
378
+ status > WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ||
379
+ !isNodeFromMe)) {
380
+ if ((0, WABinary_1.isJidGroup)(remoteJid)) {
381
+ if (attrs.participant) {
382
+ const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
383
+ ev.emit('message-receipt.update', ids.map(id => ({
384
+ key: { ...key, id },
385
+ receipt: {
386
+ userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
387
+ [updateKey]: +attrs.t
388
+ }
389
+ })));
390
+ }
391
+ }
392
+ else {
393
+ ev.emit('messages.update', ids.map(id => ({
394
+ key: { ...key, id },
395
+ update: { status }
396
+ })));
397
+ }
398
+ }
399
+ if (attrs.type === 'retry') {
400
+ // correctly set who is asking for the retry
401
+ key.participant = key.participant || attrs.from;
402
+ const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
403
+ if (willSendMessageAgain(ids[0], key.participant)) {
404
+ if (key.fromMe) {
405
+ try {
406
+ logger.debug({ attrs, key }, 'recv retry request');
407
+ await sendMessagesAgain(key, ids, retryNode);
408
+ }
409
+ catch (error) {
410
+ logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
411
+ }
412
+ }
413
+ else {
414
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
415
+ }
416
+ }
417
+ else {
418
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
419
+ }
420
+ }
421
+ }),
422
+ sendMessageAck(node)
423
+ ]);
424
+ };
425
+ const handleNotification = async (node) => {
426
+ const remoteJid = node.attrs.from;
427
+ if (shouldIgnoreJid(remoteJid)) {
428
+ logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
429
+ await sendMessageAck(node);
430
+ return;
431
+ }
432
+ await Promise.all([
433
+ processingMutex.mutex(async () => {
434
+ var _a;
435
+ const msg = await processNotification(node);
436
+ if (msg) {
437
+ const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
438
+ msg.key = {
439
+ remoteJid,
440
+ fromMe,
441
+ participant: node.attrs.participant,
442
+ id: node.attrs.id,
443
+ ...(msg.key || {})
444
+ };
445
+ (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
446
+ msg.messageTimestamp = +node.attrs.t;
447
+ const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
448
+ await upsertMessage(fullMsg, 'append');
449
+ }
450
+ }),
451
+ sendMessageAck(node)
452
+ ]);
453
+ };
454
+ const handleMessage = async (node) => {
455
+ const { fullMessage: msg, category, author, decrypt } = (0, Utils_1.decryptMessageNode)(node, authState.creds.me.id, signalRepository, logger);
456
+ if (shouldIgnoreJid(msg.key.remoteJid)) {
457
+ logger.debug({ key: msg.key }, 'ignored message');
458
+ await sendMessageAck(node);
459
+ return;
460
+ }
461
+ await Promise.all([
462
+ processingMutex.mutex(async () => {
463
+ await decrypt();
464
+ // message failed to decrypt
465
+ if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
466
+ retryMutex.mutex(async () => {
467
+ if (ws.isOpen) {
468
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
469
+ await sendRetryRequest(node, !encNode);
470
+ if (retryRequestDelayMs) {
471
+ await (0, Utils_1.delay)(retryRequestDelayMs);
472
+ }
473
+ }
474
+ else {
475
+ logger.debug({ node }, 'connection closed, ignoring retry req');
476
+ }
477
+ });
478
+ }
479
+ else {
480
+ // no type in the receipt => message delivered
481
+ let type = undefined;
482
+ let participant = msg.key.participant;
483
+ if (category === 'peer') { // special peer message
484
+ type = 'peer_msg';
485
+ }
486
+ else if (msg.key.fromMe) { // message was sent by us from a different device
487
+ type = 'sender';
488
+ // need to specially handle this case
489
+ if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
490
+ participant = author;
491
+ }
492
+ }
493
+ else if (!sendActiveReceipts) {
494
+ type = 'inactive';
495
+ }
496
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
497
+ // send ack for history message
498
+ const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
499
+ if (isAnyHistoryMsg) {
500
+ const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
501
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
502
+ }
503
+ }
504
+ (0, process_message_1.cleanMessage)(msg, authState.creds.me.id);
505
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
506
+ }),
507
+ sendMessageAck(node)
508
+ ]);
509
+ };
510
+ const handleCall = async (node) => {
511
+ const { attrs } = node;
512
+ const [infoChild] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
513
+ const callId = infoChild.attrs['call-id'];
514
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
515
+ const status = (0, Utils_1.getCallStatusFromNode)(infoChild);
516
+ const call = {
517
+ chatId: attrs.from,
518
+ from,
519
+ id: callId,
520
+ date: new Date(+attrs.t * 1000),
521
+ offline: !!attrs.offline,
522
+ status,
523
+ };
524
+ if (status === 'offer') {
525
+ call.isVideo = !!(0, WABinary_1.getBinaryNodeChild)(infoChild, 'video');
526
+ call.isGroup = infoChild.attrs.type === 'group';
527
+ callOfferCache.set(call.id, call);
528
+ }
529
+ const existingCall = callOfferCache.get(call.id);
530
+ // use existing call info to populate this event
531
+ if (existingCall) {
532
+ call.isVideo = existingCall.isVideo;
533
+ call.isGroup = existingCall.isGroup;
534
+ }
535
+ // delete data once call has ended
536
+ if (status === 'reject' || status === 'accept' || status === 'timeout') {
537
+ callOfferCache.del(call.id);
538
+ }
539
+ ev.emit('call', [call]);
540
+ await sendMessageAck(node);
541
+ };
542
+ const handleBadAck = async ({ attrs }) => {
543
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
544
+ // current hypothesis is that if pash is sent in the ack
545
+ // it means -- the message hasn't reached all devices yet
546
+ // we'll retry sending the message here
547
+ if (attrs.phash) {
548
+ logger.info({ attrs }, 'received phash in ack, resending message...');
549
+ const msg = await getMessage(key);
550
+ if (msg) {
551
+ await relayMessage(key.remoteJid, msg, { messageId: key.id, useUserDevicesCache: false });
552
+ }
553
+ else {
554
+ logger.warn({ attrs }, 'could not send message again, as it was not found');
555
+ }
556
+ }
557
+ // error in acknowledgement,
558
+ // device could not display the message
559
+ if (attrs.error) {
560
+ logger.warn({ attrs }, 'received error in ack');
561
+ ev.emit('messages.update', [
562
+ {
563
+ key,
564
+ update: {
565
+ status: Types_1.WAMessageStatus.ERROR,
566
+ messageStubParameters: [
567
+ attrs.error
568
+ ]
569
+ }
570
+ }
571
+ ]);
572
+ }
573
+ };
574
+ /// processes a node with the given function
575
+ /// and adds the task to the existing buffer if we're buffering events
576
+ const processNodeWithBuffer = async (node, identifier, exec) => {
577
+ ev.buffer();
578
+ await execTask();
579
+ ev.flush();
580
+ function execTask() {
581
+ return exec(node)
582
+ .catch(err => onUnexpectedError(err, identifier));
583
+ }
584
+ };
585
+ // recv a message
586
+ ws.on('CB:message', (node) => {
587
+ processNodeWithBuffer(node, 'processing message', handleMessage);
588
+ });
589
+ ws.on('CB:call', async (node) => {
590
+ processNodeWithBuffer(node, 'handling call', handleCall);
591
+ });
592
+ ws.on('CB:receipt', node => {
593
+ processNodeWithBuffer(node, 'handling receipt', handleReceipt);
594
+ });
595
+ ws.on('CB:notification', async (node) => {
596
+ processNodeWithBuffer(node, 'handling notification', handleNotification);
597
+ });
598
+ ws.on('CB:ack,class:message', (node) => {
599
+ handleBadAck(node)
600
+ .catch(error => onUnexpectedError(error, 'handling bad ack'));
601
+ });
602
+ ev.on('call', ([call]) => {
603
+ // missed call + group call notification message generation
604
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
605
+ const msg = {
606
+ key: {
607
+ remoteJid: call.chatId,
608
+ id: call.id,
609
+ fromMe: false
610
+ },
611
+ messageTimestamp: (0, Utils_1.unixTimestampSeconds)(call.date),
612
+ };
613
+ if (call.status === 'timeout') {
614
+ if (call.isGroup) {
615
+ msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE;
616
+ }
617
+ else {
618
+ msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_VOICE;
619
+ }
620
+ }
621
+ else {
622
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
623
+ }
624
+ const protoMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
625
+ upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
626
+ }
627
+ });
628
+ ev.on('connection.update', ({ isOnline }) => {
629
+ if (typeof isOnline !== 'undefined') {
630
+ sendActiveReceipts = isOnline;
631
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
632
+ }
633
+ });
634
+ return {
635
+ ...sock,
636
+ sendMessageAck,
637
+ sendRetryRequest,
638
+ rejectCall
639
+ };
640
+ };
641
+ exports.makeMessagesRecvSocket = makeMessagesRecvSocket;