ichigo-baileys 1.0.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 (99) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +98 -0
  3. package/WAProto/index.d.ts +15933 -0
  4. package/WAProto/index.js +115857 -0
  5. package/engine-requirements.js +10 -0
  6. package/lib/Defaults/index.js +120 -0
  7. package/lib/Defaults/noxleyss-version.json +3 -0
  8. package/lib/Signal/Group/ciphertext-message.js +15 -0
  9. package/lib/Signal/Group/group-session-builder.js +64 -0
  10. package/lib/Signal/Group/group_cipher.js +96 -0
  11. package/lib/Signal/Group/index.js +57 -0
  12. package/lib/Signal/Group/keyhelper.js +55 -0
  13. package/lib/Signal/Group/queue-job.js +57 -0
  14. package/lib/Signal/Group/sender-chain-key.js +34 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  16. package/lib/Signal/Group/sender-key-message.js +69 -0
  17. package/lib/Signal/Group/sender-key-name.js +51 -0
  18. package/lib/Signal/Group/sender-key-record.js +53 -0
  19. package/lib/Signal/Group/sender-key-state.js +99 -0
  20. package/lib/Signal/Group/sender-message-key.js +29 -0
  21. package/lib/Signal/libsignal.js +184 -0
  22. package/lib/Socket/Client/index.js +18 -0
  23. package/lib/Socket/Client/types.js +13 -0
  24. package/lib/Socket/Client/websocket.js +72 -0
  25. package/lib/Socket/business.js +260 -0
  26. package/lib/Socket/chats.js +997 -0
  27. package/lib/Socket/groups.js +332 -0
  28. package/lib/Socket/index.js +10 -0
  29. package/lib/Socket/messages-recv.js +1149 -0
  30. package/lib/Socket/messages-send.js +944 -0
  31. package/lib/Socket/newsletter.js +279 -0
  32. package/lib/Socket/socket.js +646 -0
  33. package/lib/Socket/usync.js +70 -0
  34. package/lib/Store/index.js +8 -0
  35. package/lib/Store/make-in-memory-store.js +439 -0
  36. package/lib/Store/make-ordered-dictionary.js +81 -0
  37. package/lib/Store/object-repository.js +27 -0
  38. package/lib/Types/Auth.js +2 -0
  39. package/lib/Types/Call.js +2 -0
  40. package/lib/Types/Chat.js +4 -0
  41. package/lib/Types/Contact.js +2 -0
  42. package/lib/Types/Events.js +2 -0
  43. package/lib/Types/GroupMetadata.js +2 -0
  44. package/lib/Types/Label.js +27 -0
  45. package/lib/Types/LabelAssociation.js +9 -0
  46. package/lib/Types/Message.js +7 -0
  47. package/lib/Types/Newsletter.js +18 -0
  48. package/lib/Types/Product.js +2 -0
  49. package/lib/Types/Signal.js +2 -0
  50. package/lib/Types/Socket.js +2 -0
  51. package/lib/Types/State.js +2 -0
  52. package/lib/Types/USync.js +2 -0
  53. package/lib/Types/index.js +42 -0
  54. package/lib/Utils/auth-utils.js +199 -0
  55. package/lib/Utils/browser-utils.js +35 -0
  56. package/lib/Utils/business.js +234 -0
  57. package/lib/Utils/chat-utils.js +730 -0
  58. package/lib/Utils/crypto.js +193 -0
  59. package/lib/Utils/decode-wa-message.js +217 -0
  60. package/lib/Utils/event-buffer.js +518 -0
  61. package/lib/Utils/generics.js +467 -0
  62. package/lib/Utils/history.js +94 -0
  63. package/lib/Utils/index.js +35 -0
  64. package/lib/Utils/link-preview.js +126 -0
  65. package/lib/Utils/logger.js +7 -0
  66. package/lib/Utils/lt-hash.js +51 -0
  67. package/lib/Utils/make-mutex.js +43 -0
  68. package/lib/Utils/message-retry-manager.js +185 -0
  69. package/lib/Utils/messages-media.js +879 -0
  70. package/lib/Utils/messages.js +1944 -0
  71. package/lib/Utils/noise-handler.js +150 -0
  72. package/lib/Utils/noxleyss-event-stream.js +63 -0
  73. package/lib/Utils/process-message.js +404 -0
  74. package/lib/Utils/signal.js +153 -0
  75. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  76. package/lib/Utils/validate-connection.js +229 -0
  77. package/lib/WABinary/constants.js +1303 -0
  78. package/lib/WABinary/decode.js +265 -0
  79. package/lib/WABinary/encode.js +250 -0
  80. package/lib/WABinary/generic-utils.js +110 -0
  81. package/lib/WABinary/index.js +21 -0
  82. package/lib/WABinary/jid-utils.js +85 -0
  83. package/lib/WABinary/types.js +2 -0
  84. package/lib/WAM/BinaryInfo.js +13 -0
  85. package/lib/WAM/constants.js +15350 -0
  86. package/lib/WAM/encode.js +155 -0
  87. package/lib/WAM/index.js +19 -0
  88. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  89. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  90. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  91. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  92. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  93. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  94. package/lib/WAUSync/Protocols/index.js +20 -0
  95. package/lib/WAUSync/USyncQuery.js +89 -0
  96. package/lib/WAUSync/USyncUser.js +26 -0
  97. package/lib/WAUSync/index.js +19 -0
  98. package/lib/index.js +116 -0
  99. package/package.json +119 -0
@@ -0,0 +1,944 @@
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.makeMessagesSocket = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
+ const crypto_1 = require("crypto");
10
+ const WAProto_1 = require("../../WAProto");
11
+ const Defaults_1 = require("../Defaults");
12
+ const Utils_1 = require("../Utils");
13
+ const link_preview_1 = require("../Utils/link-preview");
14
+ const WABinary_1 = require("../WABinary");
15
+ const WAUSync_1 = require("../WAUSync");
16
+ const newsletter_1 = require("./newsletter");
17
+ const makeMessagesSocket = (config) => {
18
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, albumMessageItemDelayMs = 0, } = config;
19
+ const sock = (0, newsletter_1.makeNewsletterSocket)(config);
20
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, } = sock;
21
+ const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
22
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
23
+ useClones: false
24
+ });
25
+ let mediaConn;
26
+ const refreshMediaConn = async (forceGet = false) => {
27
+ const media = await mediaConn;
28
+ if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
29
+ mediaConn = (async () => {
30
+ const result = await query({
31
+ tag: 'iq',
32
+ attrs: {
33
+ type: 'set',
34
+ xmlns: 'w:m',
35
+ to: WABinary_1.S_WHATSAPP_NET,
36
+ },
37
+ content: [{ tag: 'media_conn', attrs: {} }]
38
+ });
39
+ const mediaConnNode = (0, WABinary_1.getBinaryNodeChild)(result, 'media_conn');
40
+ const node = {
41
+ hosts: (0, WABinary_1.getBinaryNodeChildren)(mediaConnNode, 'host').map(({ attrs }) => ({
42
+ hostname: attrs.hostname,
43
+ maxContentLengthBytes: +attrs.maxContentLengthBytes,
44
+ })),
45
+ auth: mediaConnNode.attrs.auth,
46
+ ttl: +mediaConnNode.attrs.ttl,
47
+ fetchDate: new Date()
48
+ };
49
+ logger.debug('fetched media conn');
50
+ return node;
51
+ })();
52
+ }
53
+ return mediaConn;
54
+ };
55
+ /**
56
+ * generic send receipt function
57
+ * used for receipts of phone call, read, delivery etc.
58
+ * */
59
+ const sendReceipt = async (jid, participant, messageIds, type) => {
60
+ const node = {
61
+ tag: 'receipt',
62
+ attrs: {
63
+ id: messageIds[0],
64
+ },
65
+ };
66
+ const isReadReceipt = type === 'read' || type === 'read-self';
67
+ if (isReadReceipt) {
68
+ node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString();
69
+ }
70
+ if (type === 'sender' && (0, WABinary_1.isJidUser)(jid)) {
71
+ node.attrs.recipient = jid;
72
+ node.attrs.to = participant;
73
+ }
74
+ else {
75
+ node.attrs.to = jid;
76
+ if (participant) {
77
+ node.attrs.participant = participant;
78
+ }
79
+ }
80
+ if (type) {
81
+ node.attrs.type = (0, WABinary_1.isJidNewsletter)(jid) ? 'read-self' : type;
82
+ }
83
+ const remainingMessageIds = messageIds.slice(1);
84
+ if (remainingMessageIds.length) {
85
+ node.content = [
86
+ {
87
+ tag: 'list',
88
+ attrs: {},
89
+ content: remainingMessageIds.map(id => ({
90
+ tag: 'item',
91
+ attrs: { id }
92
+ }))
93
+ }
94
+ ];
95
+ }
96
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
97
+ await sendNode(node);
98
+ };
99
+ /** Correctly bulk send receipts to multiple chats, participants */
100
+ const sendReceipts = async (keys, type) => {
101
+ const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
102
+ for (const { jid, participant, messageIds } of recps) {
103
+ await sendReceipt(jid, participant, messageIds, type);
104
+ }
105
+ };
106
+ /** Bulk read messages. Keys can be from different chats & participants */
107
+ const readMessages = async (keys) => {
108
+ const privacySettings = await fetchPrivacySettings();
109
+ // based on privacy settings, we have to change the read type
110
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
111
+ await sendReceipts(keys, readType);
112
+ };
113
+ /** Fetch all the devices we've to send a message to */
114
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
115
+ var _a;
116
+ const deviceResults = [];
117
+ if (!useCache) {
118
+ logger.debug('not using cache for devices');
119
+ }
120
+ const toFetch = [];
121
+ jids = Array.from(new Set(jids));
122
+ for (let jid of jids) {
123
+ const user = (_a = (0, WABinary_1.jidDecode)(jid)) === null || _a === void 0 ? void 0 : _a.user;
124
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
125
+ if (useCache) {
126
+ const devices = userDevicesCache.get(user);
127
+ if (devices) {
128
+ deviceResults.push(...devices);
129
+ logger.trace({ user }, 'using cache for devices');
130
+ }
131
+ else {
132
+ toFetch.push(jid);
133
+ }
134
+ }
135
+ else {
136
+ toFetch.push(jid);
137
+ }
138
+ }
139
+ if (!toFetch.length) {
140
+ return deviceResults;
141
+ }
142
+ const query = new WAUSync_1.USyncQuery()
143
+ .withContext('message')
144
+ .withDeviceProtocol();
145
+ for (const jid of toFetch) {
146
+ query.withUser(new WAUSync_1.USyncUser().withId(jid));
147
+ }
148
+ const result = await sock.executeUSyncQuery(query);
149
+ if (result) {
150
+ const extracted = (0, Utils_1.extractDeviceJids)(result === null || result === void 0 ? void 0 : result.list, authState.creds.me.id, ignoreZeroDevices);
151
+ const deviceMap = {};
152
+ for (const item of extracted) {
153
+ deviceMap[item.user] = deviceMap[item.user] || [];
154
+ deviceMap[item.user].push(item);
155
+ deviceResults.push(item);
156
+ }
157
+ for (const key in deviceMap) {
158
+ userDevicesCache.set(key, deviceMap[key]);
159
+ }
160
+ }
161
+ return deviceResults;
162
+ };
163
+ const assertSessions = async (jids, force) => {
164
+ let didFetchNewSession = false;
165
+ let jidsRequiringFetch = [];
166
+ if (force) {
167
+ jidsRequiringFetch = jids;
168
+ }
169
+ else {
170
+ const addrs = jids.map(jid => (signalRepository
171
+ .jidToSignalProtocolAddress(jid)));
172
+ const sessions = await authState.keys.get('session', addrs);
173
+ for (const jid of jids) {
174
+ const signalId = signalRepository
175
+ .jidToSignalProtocolAddress(jid);
176
+ if (!sessions[signalId]) {
177
+ jidsRequiringFetch.push(jid);
178
+ }
179
+ }
180
+ }
181
+ if (jidsRequiringFetch.length) {
182
+ logger.debug({ jidsRequiringFetch }, 'fetching sessions');
183
+ const result = await query({
184
+ tag: 'iq',
185
+ attrs: {
186
+ xmlns: 'encrypt',
187
+ type: 'get',
188
+ to: WABinary_1.S_WHATSAPP_NET,
189
+ },
190
+ content: [
191
+ {
192
+ tag: 'key',
193
+ attrs: {},
194
+ content: jidsRequiringFetch.map(jid => ({
195
+ tag: 'user',
196
+ attrs: { jid },
197
+ }))
198
+ }
199
+ ]
200
+ });
201
+ await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
202
+ didFetchNewSession = true;
203
+ }
204
+ return didFetchNewSession;
205
+ };
206
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
207
+ var _a;
208
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
209
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
210
+ throw new boom_1.Boom('Not authenticated');
211
+ }
212
+ const protocolMessage = {
213
+ protocolMessage: {
214
+ peerDataOperationRequestMessage: pdoMessage,
215
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
216
+ }
217
+ };
218
+ const meJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id);
219
+ const msgId = await relayMessage(meJid, protocolMessage, {
220
+ additionalAttributes: {
221
+ category: 'peer',
222
+ // eslint-disable-next-line camelcase
223
+ push_priority: 'high_force',
224
+ },
225
+ });
226
+ return msgId;
227
+ };
228
+ const createParticipantNodes = async (jids, message, extraAttrs) => {
229
+ let patched = await patchMessageBeforeSending(message, jids);
230
+ if (!Array.isArray(patched)) {
231
+ patched = jids ? jids.map(jid => ({ recipientJid: jid, ...patched })) : [patched];
232
+ }
233
+ let shouldIncludeDeviceIdentity = false;
234
+ const nodes = await Promise.all(patched.map(async (patchedMessageWithJid) => {
235
+ const { recipientJid: jid, ...patchedMessage } = patchedMessageWithJid;
236
+ if (!jid) {
237
+ return {};
238
+ }
239
+ const bytes = (0, Utils_1.encodeWAMessage)(patchedMessage);
240
+ const { type, ciphertext } = await signalRepository
241
+ .encryptMessage({ jid, data: bytes });
242
+ if (type === 'pkmsg') {
243
+ shouldIncludeDeviceIdentity = true;
244
+ }
245
+ const node = {
246
+ tag: 'to',
247
+ attrs: { jid },
248
+ content: [{
249
+ tag: 'enc',
250
+ attrs: {
251
+ v: '2',
252
+ type,
253
+ ...extraAttrs || {}
254
+ },
255
+ content: ciphertext
256
+ }]
257
+ };
258
+ return node;
259
+ }));
260
+ return { nodes, shouldIncludeDeviceIdentity };
261
+ };
262
+ const relayMessage = async (
263
+ jid,
264
+ message,
265
+ {
266
+ messageId: msgId,
267
+ participant,
268
+ onTarget,
269
+ additionalAttributes,
270
+ additionalNodes,
271
+ useUserDevicesCache,
272
+ useCachedGroupMetadata,
273
+ statusJidList
274
+ } = {}
275
+ ) => {
276
+ var _a;
277
+ const meId = authState.creds.me.id;
278
+ let shouldIncludeDeviceIdentity = false;
279
+ const { user, server } = (0, WABinary_1.jidDecode)(jid);
280
+ const statusJid = 'status@broadcast';
281
+ const isGroup = server === 'g.us';
282
+ const isNewsletter = server === 'newsletter';
283
+ const isStatus = jid === statusJid;
284
+ const isLid = server === 'lid';
285
+ msgId = msgId || (0, Utils_1.generateMessageIDV2)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id);
286
+ useUserDevicesCache = useUserDevicesCache !== false;
287
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
288
+ const participants = [];
289
+ const destinationJid = (!isStatus) ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
290
+ const binaryNodeContent = [];
291
+ const devices = [];
292
+ const meMsg = {
293
+ deviceSentMessage: {
294
+ destinationJid,
295
+ message
296
+ },
297
+ messageContextInfo: message.messageContextInfo
298
+ };
299
+ const extraAttrs = {};
300
+ if (participant) {
301
+ // when the retry request is not for a group
302
+ // only send to the specific device that asked for a retry
303
+ // otherwise the message is sent out to every device that should be a recipient
304
+ if (!isGroup && !isStatus) {
305
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
306
+ }
307
+ const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
308
+ devices.push({ user, device });
309
+ }
310
+ await authState.keys.transaction(async () => {
311
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
312
+ const mediaType = getMediaType(message);
313
+ if (mediaType) {
314
+ extraAttrs['mediatype'] = mediaType;
315
+ }
316
+ if ((_a = (0, Utils_1.normalizeMessageContent)(message)) === null || _a === void 0 ? void 0 : _a.pinInChatMessage) {
317
+ extraAttrs['decrypt-fail'] = 'hide';
318
+ }
319
+ if (isGroup || isStatus) {
320
+ const [groupData, senderKeyMap] = await Promise.all([
321
+ (async () => {
322
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
323
+ if (groupData && Array.isArray(groupData === null || groupData === void 0 ? void 0 : groupData.participants)) {
324
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
325
+ }
326
+ else if (!isStatus) {
327
+ groupData = await groupMetadata(jid);
328
+ }
329
+ return groupData;
330
+ })(),
331
+ (async () => {
332
+ if (!participant && !isStatus) {
333
+ const result = await authState.keys.get('sender-key-memory', [jid]);
334
+ return result[jid] || {};
335
+ }
336
+ return {};
337
+ })()
338
+ ]);
339
+ if (!participant) {
340
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
341
+ if (isStatus && statusJidList) {
342
+ participantsList.push(...statusJidList);
343
+ }
344
+ if (!isStatus) {
345
+ additionalAttributes = {
346
+ ...additionalAttributes,
347
+ // eslint-disable-next-line camelcase
348
+ addressing_mode: (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) || 'pn'
349
+ };
350
+ }
351
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
352
+ devices.push(...additionalDevices);
353
+ }
354
+ const patched = await patchMessageBeforeSending(message);
355
+ if (Array.isArray(patched)) {
356
+ throw new boom_1.Boom('Per-jid patching is not supported in groups');
357
+ }
358
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
359
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
360
+ group: destinationJid,
361
+ data: bytes,
362
+ meId,
363
+ });
364
+ const senderKeyJids = [];
365
+ // ensure a connection is established with every device
366
+ for (const { user, device } of devices) {
367
+ const jid = (0, WABinary_1.jidEncode)(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
368
+ if (!senderKeyMap[jid] || !!participant) {
369
+ senderKeyJids.push(jid);
370
+ // store that this person has had the sender keys sent to them
371
+ senderKeyMap[jid] = true;
372
+ }
373
+ }
374
+ // if there are some participants with whom the session has not been established
375
+ // if there are, we re-send the senderkey
376
+ if (senderKeyJids.length) {
377
+ logger.debug({ senderKeyJids }, 'sending new sender key');
378
+ const senderKeyMsg = {
379
+ senderKeyDistributionMessage: {
380
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
381
+ groupId: destinationJid
382
+ }
383
+ };
384
+ await assertSessions(senderKeyJids, false);
385
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs);
386
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
387
+ participants.push(...result.nodes);
388
+ }
389
+ binaryNodeContent.push({
390
+ tag: 'enc',
391
+ attrs: { v: '2', type: 'skmsg' },
392
+ content: ciphertext
393
+ });
394
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
395
+ }
396
+ else if (isNewsletter) {
397
+ // Message edit
398
+ if ((_b = message.protocolMessage) === null || _b === void 0 ? void 0 : _b.editedMessage) {
399
+ msgId = (_c = message.protocolMessage.key) === null || _c === void 0 ? void 0 : _c.id;
400
+ message = message.protocolMessage.editedMessage;
401
+ }
402
+ // Message delete
403
+ if (((_d = message.protocolMessage) === null || _d === void 0 ? void 0 : _d.type) === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
404
+ msgId = (_e = message.protocolMessage.key) === null || _e === void 0 ? void 0 : _e.id;
405
+ message = {};
406
+ }
407
+ const patched = await patchMessageBeforeSending(message, []);
408
+ if (Array.isArray(patched)) {
409
+ throw new boom_1.Boom('Per-jid patching is not supported in channel');
410
+ }
411
+ const bytes = (0, Utils_1.encodeNewsletterMessage)(patched);
412
+ binaryNodeContent.push({
413
+ tag: 'plaintext',
414
+ attrs: mediaType ? { mediatype: mediaType } : {},
415
+ content: bytes
416
+ });
417
+ }
418
+ else {
419
+ const { user: meUser } = (0, WABinary_1.jidDecode)(meId);
420
+ if (!participant) {
421
+ devices.push({ user });
422
+ if (user !== meUser) {
423
+ devices.push({ user: meUser });
424
+ }
425
+ if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) !== 'peer') {
426
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
427
+ devices.push(...additionalDevices);
428
+ }
429
+ }
430
+
431
+ const allJids = [];
432
+ const meJids = [];
433
+ const otherJids = [];
434
+
435
+ const meLid = authState.creds.me?.lid;
436
+ const { user: mePnUser } = (0, WABinary_1.jidDecode)(meId);
437
+ const { user: meLidUser } = meLid
438
+ ? (0, WABinary_1.jidDecode)(meLid)
439
+ : { user: null };
440
+
441
+ for (const { user, device } of devices) {
442
+ const jid = (0, WABinary_1.jidEncode)(
443
+ user === meLidUser && isLid
444
+ ? (meLid?.split(":")[0] || user)
445
+ : user,
446
+ isLid ? "lid" : "s.whatsapp.net",
447
+ device
448
+ );
449
+
450
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
451
+ const isMe = user === mePnUser || user === meLidUser;
452
+
453
+ let skip = false;
454
+
455
+ if ((participant || onTarget) && !((0, WABinary_1.isJidGroup)(jid) || isStatus)) {
456
+ if (isExactSenderDevice) {
457
+ skip = true;
458
+ } else if (isMe) {
459
+ skip = true;
460
+ }
461
+ }
462
+
463
+ if (!skip) {
464
+ if (isMe) {
465
+ meJids.push(jid);
466
+ } else {
467
+ otherJids.push(jid);
468
+ }
469
+
470
+ allJids.push(jid);
471
+ }
472
+ }
473
+
474
+ await assertSessions(allJids, false);
475
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
476
+ createParticipantNodes(meJids, meMsg, extraAttrs),
477
+ createParticipantNodes(otherJids, message, extraAttrs)
478
+ ]);
479
+ participants.push(...meNodes);
480
+ participants.push(...otherNodes);
481
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
482
+ }
483
+ if (participants.length) {
484
+ if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer') {
485
+ const peerNode = (_j = (_h = participants[0]) === null || _h === void 0 ? void 0 : _h.content) === null || _j === void 0 ? void 0 : _j[0];
486
+ if (peerNode) {
487
+ binaryNodeContent.push(peerNode); // push only enc
488
+ }
489
+ }
490
+ else {
491
+ binaryNodeContent.push({
492
+ tag: 'participants',
493
+ attrs: {},
494
+ content: participants
495
+ });
496
+ }
497
+ }
498
+ const stanza = {
499
+ tag: 'message',
500
+ attrs: {
501
+ id: msgId,
502
+ type: isNewsletter ? getTypeMessage(message) : 'text',
503
+ ...(additionalAttributes || {})
504
+ },
505
+ content: binaryNodeContent
506
+ };
507
+ // if the participant to send to is explicitly specified (generally retry recp)
508
+ // ensure the message is only sent to that person
509
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
510
+ if (participant) {
511
+ if ((0, WABinary_1.isJidGroup)(destinationJid)) {
512
+ stanza.attrs.to = destinationJid;
513
+ stanza.attrs.participant = participant.jid;
514
+ }
515
+ else if ((0, WABinary_1.areJidsSameUser)(participant.jid, meId)) {
516
+ stanza.attrs.to = participant.jid;
517
+ stanza.attrs.recipient = destinationJid;
518
+ }
519
+ else {
520
+ stanza.attrs.to = participant.jid;
521
+ }
522
+ }
523
+ else {
524
+ stanza.attrs.to = destinationJid;
525
+ }
526
+ if (shouldIncludeDeviceIdentity) {
527
+ stanza.content.push({
528
+ tag: 'device-identity',
529
+ attrs: {},
530
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
531
+ });
532
+ logger.debug({ jid }, 'adding device identity');
533
+ }
534
+ if (additionalNodes && additionalNodes.length > 0) {
535
+ stanza.content.push(...additionalNodes);
536
+ }
537
+ const content = (0, Utils_1.normalizeMessageContent)(message);
538
+ const contentType = (0, Utils_1.getContentType)(content);
539
+ if (((0, WABinary_1.isJidGroup)(jid) || (0, WABinary_1.isJidUser)(jid)) && (contentType === 'interactiveMessage' ||
540
+ contentType === 'buttonsMessage' ||
541
+ contentType === 'listMessage')) {
542
+ const bizNode = { tag: 'biz', attrs: {} };
543
+ if ((((_l = (_k = message === null || message === void 0 ? void 0 : message.viewOnceMessage) === null || _k === void 0 ? void 0 : _k.message) === null || _l === void 0 ? void 0 : _l.interactiveMessage) || ((_o = (_m = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) === null || _m === void 0 ? void 0 : _m.message) === null || _o === void 0 ? void 0 : _o.interactiveMessage) || ((_q = (_p = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) === null || _p === void 0 ? void 0 : _p.message) === null || _q === void 0 ? void 0 : _q.interactiveMessage) || (message === null || message === void 0 ? void 0 : message.interactiveMessage)) || (((_s = (_r = message === null || message === void 0 ? void 0 : message.viewOnceMessage) === null || _r === void 0 ? void 0 : _r.message) === null || _s === void 0 ? void 0 : _s.buttonsMessage) || ((_u = (_t = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) === null || _t === void 0 ? void 0 : _t.message) === null || _u === void 0 ? void 0 : _u.buttonsMessage) || ((_w = (_v = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) === null || _v === void 0 ? void 0 : _v.message) === null || _w === void 0 ? void 0 : _w.buttonsMessage) || (message === null || message === void 0 ? void 0 : message.buttonsMessage))) {
544
+ bizNode.content = [{
545
+ tag: 'interactive',
546
+ attrs: {
547
+ type: 'native_flow',
548
+ v: '1'
549
+ },
550
+ content: [{
551
+ tag: 'native_flow',
552
+ attrs: { v: '9', name: 'mixed' }
553
+ }]
554
+ }];
555
+ }
556
+ else if (message === null || message === void 0 ? void 0 : message.listMessage) {
557
+ // list message only support in private chat
558
+ bizNode.content = [{
559
+ tag: 'list',
560
+ attrs: {
561
+ type: 'product_list',
562
+ v: '2'
563
+ }
564
+ }];
565
+ }
566
+ stanza.content.push(bizNode);
567
+ }
568
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
569
+ await sendNode(stanza);
570
+ });
571
+ return msgId;
572
+ };
573
+ const getTypeMessage = (msg) => {
574
+ if (msg.viewOnceMessage) {
575
+ return getTypeMessage(msg.viewOnceMessage.message);
576
+ }
577
+ else if (msg.viewOnceMessageV2) {
578
+ return getTypeMessage(msg.viewOnceMessageV2.message);
579
+ }
580
+ else if (msg.viewOnceMessageV2Extension) {
581
+ return getTypeMessage(msg.viewOnceMessageV2Extension.message);
582
+ }
583
+ else if (msg.ephemeralMessage) {
584
+ return getTypeMessage(msg.ephemeralMessage.message);
585
+ }
586
+ else if (msg.documentWithCaptionMessage) {
587
+ return getTypeMessage(msg.documentWithCaptionMessage.message);
588
+ }
589
+ else if (msg.reactionMessage) {
590
+ return 'reaction';
591
+ }
592
+ else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
593
+ return 'poll';
594
+ }
595
+ else if (getMediaType(msg)) {
596
+ return 'media';
597
+ }
598
+ else {
599
+ return 'text';
600
+ }
601
+ };
602
+ const getMediaType = (message) => {
603
+ if (message.imageMessage) {
604
+ return 'image';
605
+ }
606
+ else if (message.videoMessage) {
607
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
608
+ }
609
+ else if (message.audioMessage) {
610
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
611
+ }
612
+ else if (message.contactMessage) {
613
+ return 'vcard';
614
+ }
615
+ else if (message.documentMessage) {
616
+ return 'document';
617
+ }
618
+ else if (message.contactsArrayMessage) {
619
+ return 'contact_array';
620
+ }
621
+ else if (message.liveLocationMessage) {
622
+ return 'livelocation';
623
+ }
624
+ else if (message.stickerMessage) {
625
+ return 'sticker';
626
+ }
627
+ else if (message.listMessage) {
628
+ return 'list';
629
+ }
630
+ else if (message.listResponseMessage) {
631
+ return 'list_response';
632
+ }
633
+ else if (message.buttonsResponseMessage) {
634
+ return 'buttons_response';
635
+ }
636
+ else if (message.orderMessage) {
637
+ return 'order';
638
+ }
639
+ else if (message.productMessage) {
640
+ return 'product';
641
+ }
642
+ else if (message.interactiveResponseMessage) {
643
+ return 'native_flow_response';
644
+ }
645
+ else if (message.groupInviteMessage) {
646
+ return 'url';
647
+ }
648
+ };
649
+ const getPrivacyTokens = async (jids) => {
650
+ const t = (0, Utils_1.unixTimestampSeconds)().toString();
651
+ const result = await query({
652
+ tag: 'iq',
653
+ attrs: {
654
+ to: WABinary_1.S_WHATSAPP_NET,
655
+ type: 'set',
656
+ xmlns: 'privacy'
657
+ },
658
+ content: [
659
+ {
660
+ tag: 'tokens',
661
+ attrs: {},
662
+ content: jids.map(jid => ({
663
+ tag: 'token',
664
+ attrs: {
665
+ jid: (0, WABinary_1.jidNormalizedUser)(jid),
666
+ t,
667
+ type: 'trusted_contact'
668
+ }
669
+ }))
670
+ }
671
+ ]
672
+ });
673
+ return result;
674
+ };
675
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
676
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
677
+ return {
678
+ ...sock,
679
+ getPrivacyTokens,
680
+ assertSessions,
681
+ relayMessage,
682
+ sendReceipt,
683
+ sendReceipts,
684
+ readMessages,
685
+ refreshMediaConn,
686
+ waUploadToServer,
687
+ fetchPrivacySettings,
688
+ getUSyncDevices,
689
+ createParticipantNodes,
690
+ sendPeerDataOperationMessage,
691
+ updateMediaMessage: async (message) => {
692
+ const content = (0, Utils_1.assertMediaContent)(message.message);
693
+ const mediaKey = content.mediaKey;
694
+ const meId = authState.creds.me.id;
695
+ const node = await (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
696
+ let error = undefined;
697
+ await Promise.all([
698
+ sendNode(node),
699
+ waitForMsgMediaUpdate(async (update) => {
700
+ const result = update.find(c => c.key.id === message.key.id);
701
+ if (result) {
702
+ if (result.error) {
703
+ error = result.error;
704
+ }
705
+ else {
706
+ try {
707
+ const media = await (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
708
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
709
+ const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
710
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
711
+ }
712
+ content.directPath = media.directPath;
713
+ content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
714
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
715
+ }
716
+ catch (err) {
717
+ error = err;
718
+ }
719
+ }
720
+ return true;
721
+ }
722
+ })
723
+ ]);
724
+ if (error) {
725
+ throw error;
726
+ }
727
+ ev.emit('messages.update', [
728
+ { key: message.key, update: { message: message.message } }
729
+ ]);
730
+ return message;
731
+ },
732
+ sendMessage: async (jid, content, options = {}) => {
733
+ var _a, _b, _c;
734
+ const userJid = authState.creds.me.id;
735
+ if (!options.ephemeralExpiration) {
736
+ if ((0, WABinary_1.isJidGroup)(jid)) {
737
+ const groups = await sock.groupQuery(jid, 'get', [{
738
+ tag: 'query',
739
+ attrs: {
740
+ request: 'interactive'
741
+ }
742
+ }]);
743
+ const metadata = (0, WABinary_1.getBinaryNodeChild)(groups, 'group');
744
+ const expiration = ((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(metadata, 'ephemeral')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.expiration) || 0;
745
+ options.ephemeralExpiration = expiration;
746
+ }
747
+ }
748
+ if (typeof content === 'object' &&
749
+ 'disappearingMessagesInChat' in content &&
750
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
751
+ (0, WABinary_1.isJidGroup)(jid)) {
752
+ const { disappearingMessagesInChat } = content;
753
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
754
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
755
+ disappearingMessagesInChat;
756
+ await groupToggleEphemeral(jid, value);
757
+ }
758
+ if (typeof content === 'object' && 'album' in content && content.album) {
759
+ const { album, caption } = content;
760
+ if (caption && !album[0].caption) {
761
+ album[0].caption = caption;
762
+ }
763
+ let mediaHandle;
764
+ let mediaMsg;
765
+ const albumMsg = (0, Utils_1.generateWAMessageFromContent)(jid, {
766
+ albumMessage: {
767
+ expectedImageCount: album.filter(item => 'image' in item).length,
768
+ expectedVideoCount: album.filter(item => 'video' in item).length
769
+ }
770
+ }, { userJid, ...options });
771
+ await relayMessage(jid, albumMsg.message, {
772
+ messageId: albumMsg.key.id
773
+ });
774
+ for (const i in album) {
775
+ const media = album[i];
776
+ if ('image' in media) {
777
+ mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
778
+ image: media.image,
779
+ ...(media.caption ? { caption: media.caption } : {}),
780
+ ...options
781
+ }, {
782
+ userJid,
783
+ upload: async (readStream, opts) => {
784
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
785
+ mediaHandle = up.handle;
786
+ return up;
787
+ },
788
+ ...options,
789
+ });
790
+ }
791
+ else if ('video' in media) {
792
+ mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
793
+ video: media.video,
794
+ ...(media.caption ? { caption: media.caption } : {}),
795
+ ...(media.gifPlayback !== undefined ? { gifPlayback: media.gifPlayback } : {}),
796
+ ...options
797
+ }, {
798
+ userJid,
799
+ upload: async (readStream, opts) => {
800
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
801
+ mediaHandle = up.handle;
802
+ return up;
803
+ },
804
+ ...options,
805
+ });
806
+ }
807
+ if (mediaMsg) {
808
+ mediaMsg.message.messageContextInfo = {
809
+ messageSecret: (0, crypto_1.randomBytes)(32),
810
+ messageAssociation: {
811
+ associationType: 1,
812
+ parentMessageKey: albumMsg.key
813
+ }
814
+ };
815
+ }
816
+ await relayMessage(jid, mediaMsg.message, {
817
+ messageId: mediaMsg.key.id
818
+ });
819
+ if (albumMessageItemDelayMs > 0) {
820
+ await new Promise(resolve => setTimeout(resolve, albumMessageItemDelayMs));
821
+ }
822
+ }
823
+ return albumMsg;
824
+ }
825
+ else {
826
+ let mediaHandle;
827
+ const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
828
+ logger,
829
+ userJid,
830
+ getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
831
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
832
+ fetchOpts: {
833
+ timeout: 3000,
834
+ ...axiosOptions || {}
835
+ },
836
+ logger,
837
+ uploadImage: generateHighQualityLinkPreview
838
+ ? waUploadToServer
839
+ : undefined
840
+ }),
841
+ getProfilePicUrl: sock.profilePictureUrl,
842
+ upload: async (readStream, opts) => {
843
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
844
+ mediaHandle = up.handle;
845
+ return up;
846
+ },
847
+ mediaCache: config.mediaCache,
848
+ options: config.options,
849
+ messageId: (0, Utils_1.generateMessageIDV2)((_c = sock.user) === null || _c === void 0 ? void 0 : _c.id),
850
+ ...options,
851
+ });
852
+ const isDeleteMsg = 'delete' in content && !!content.delete;
853
+ const isEditMsg = 'edit' in content && !!content.edit;
854
+ const isPinMsg = 'pin' in content && !!content.pin;
855
+ const isKeepMsg = 'keep' in content && content.keep;
856
+ const isPollMessage = 'poll' in content && !!content.poll;
857
+ const isAiMsg = 'ai' in content && !!content.ai;
858
+ const additionalAttributes = {};
859
+ const additionalNodes = [];
860
+ // required for delete
861
+ if (isDeleteMsg) {
862
+ // if the chat is a group, and I am not the author, then delete the message as an admin
863
+ if (((0, WABinary_1.isJidGroup)(content.delete.remoteJid) && !content.delete.fromMe) || (0, WABinary_1.isJidNewsletter)(jid)) {
864
+ additionalAttributes.edit = '8';
865
+ }
866
+ else {
867
+ additionalAttributes.edit = '7';
868
+ }
869
+ // required for edit message
870
+ }
871
+ else if (isEditMsg) {
872
+ additionalAttributes.edit = (0, WABinary_1.isJidNewsletter)(jid) ? '3' : '1';
873
+ // required for pin message
874
+ }
875
+ else if (isPinMsg) {
876
+ additionalAttributes.edit = '2';
877
+ // required for keep message
878
+ }
879
+ else if (isKeepMsg) {
880
+ additionalAttributes.edit = '6';
881
+ // required for polling message
882
+ }
883
+ else if (isPollMessage) {
884
+ additionalNodes.push({
885
+ tag: 'meta',
886
+ attrs: {
887
+ polltype: 'creation'
888
+ },
889
+ });
890
+ // required to display AI icon on message
891
+ }
892
+ else if (isAiMsg) {
893
+ additionalNodes.push({
894
+ attrs: {
895
+ biz_bot: '1'
896
+ },
897
+ tag: "bot"
898
+ });
899
+ }
900
+ if (mediaHandle) {
901
+ additionalAttributes['media_id'] = mediaHandle;
902
+ }
903
+ if ('cachedGroupMetadata' in options) {
904
+ console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
905
+ }
906
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, statusJidList: options.statusJidList });
907
+ if (typeof content === 'object' && content.richMessage && content.richMessage.editrich) {
908
+ const editedContent = {
909
+ richMessage: content.richMessage.editrich
910
+ };
911
+ const editedMsg = await (0, Utils_1.generateWAMessage)(jid, editedContent, {
912
+ userJid,
913
+ logger,
914
+ ...options
915
+ });
916
+ await relayMessage(jid, {
917
+ botForwardedMessage: {
918
+ message: {
919
+ protocolMessage: {
920
+ key: {
921
+ remoteJid: jid,
922
+ fromMe: true,
923
+ id: fullMsg.key.id
924
+ },
925
+ type: 14,
926
+ editedMessage: editedMsg.message
927
+ }
928
+ }
929
+ }
930
+ }, {
931
+ messageId: (0, crypto_1.randomUUID)()
932
+ });
933
+ }
934
+ if (config.emitOwnEvents) {
935
+ process.nextTick(() => {
936
+ processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
937
+ });
938
+ }
939
+ return fullMsg;
940
+ }
941
+ }
942
+ };
943
+ };
944
+ exports.makeMessagesSocket = makeMessagesSocket;