ndikzv1 26.0.12

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