@baileys-md/baileys 10.0.7

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 (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2 -0
  3. package/WAProto/index.js +155693 -0
  4. package/WASignalGroup/GroupProtocol.js +1697 -0
  5. package/WASignalGroup/ciphertext_message.js +16 -0
  6. package/WASignalGroup/group_cipher.js +120 -0
  7. package/WASignalGroup/group_session_builder.js +46 -0
  8. package/WASignalGroup/index.js +5 -0
  9. package/WASignalGroup/keyhelper.js +21 -0
  10. package/WASignalGroup/protobufs.js +3 -0
  11. package/WASignalGroup/queue_job.js +69 -0
  12. package/WASignalGroup/sender_chain_key.js +50 -0
  13. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  14. package/WASignalGroup/sender_key_message.js +92 -0
  15. package/WASignalGroup/sender_key_name.js +70 -0
  16. package/WASignalGroup/sender_key_record.js +56 -0
  17. package/WASignalGroup/sender_key_state.js +129 -0
  18. package/WASignalGroup/sender_message_key.js +39 -0
  19. package/lib/Defaults/baileys-version.json +3 -0
  20. package/lib/Defaults/index.js +122 -0
  21. package/lib/Defaults/phonenumber-mcc.json +223 -0
  22. package/lib/Signal/libsignal.js +161 -0
  23. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  24. package/lib/Socket/Client/index.js +19 -0
  25. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  26. package/lib/Socket/Client/web-socket-client.js +62 -0
  27. package/lib/Socket/business.js +260 -0
  28. package/lib/Socket/chats.js +882 -0
  29. package/lib/Socket/groups.js +327 -0
  30. package/lib/Socket/index.js +10 -0
  31. package/lib/Socket/messages-recv.js +1043 -0
  32. package/lib/Socket/messages-send.js +836 -0
  33. package/lib/Socket/newsletter.js +248 -0
  34. package/lib/Socket/registration.js +166 -0
  35. package/lib/Socket/socket.js +640 -0
  36. package/lib/Socket/usync.js +70 -0
  37. package/lib/Store/index.js +8 -0
  38. package/lib/Store/make-cache-manager-store.js +83 -0
  39. package/lib/Store/make-in-memory-store.js +431 -0
  40. package/lib/Store/make-mongo-store.js +567 -0
  41. package/lib/Store/make-ordered-dictionary.js +81 -0
  42. package/lib/Store/object-repository.js +27 -0
  43. package/lib/Types/Auth.js +2 -0
  44. package/lib/Types/Call.js +2 -0
  45. package/lib/Types/Chat.js +4 -0
  46. package/lib/Types/Contact.js +2 -0
  47. package/lib/Types/Events.js +2 -0
  48. package/lib/Types/GroupMetadata.js +2 -0
  49. package/lib/Types/Label.js +27 -0
  50. package/lib/Types/LabelAssociation.js +9 -0
  51. package/lib/Types/Message.js +7 -0
  52. package/lib/Types/Newsletter.js +18 -0
  53. package/lib/Types/Product.js +2 -0
  54. package/lib/Types/Signal.js +2 -0
  55. package/lib/Types/Socket.js +2 -0
  56. package/lib/Types/State.js +2 -0
  57. package/lib/Types/USync.js +2 -0
  58. package/lib/Types/index.js +42 -0
  59. package/lib/Utils/auth-utils.js +206 -0
  60. package/lib/Utils/baileys-event-stream.js +63 -0
  61. package/lib/Utils/business.js +234 -0
  62. package/lib/Utils/chat-utils.js +730 -0
  63. package/lib/Utils/crypto.js +151 -0
  64. package/lib/Utils/decode-wa-message.js +198 -0
  65. package/lib/Utils/event-buffer.js +520 -0
  66. package/lib/Utils/generics.js +445 -0
  67. package/lib/Utils/history.js +94 -0
  68. package/lib/Utils/index.js +33 -0
  69. package/lib/Utils/link-preview.js +126 -0
  70. package/lib/Utils/logger.js +7 -0
  71. package/lib/Utils/lt-hash.js +51 -0
  72. package/lib/Utils/make-mutex.js +43 -0
  73. package/lib/Utils/messages-media.js +724 -0
  74. package/lib/Utils/messages.js +1018 -0
  75. package/lib/Utils/noise-handler.js +155 -0
  76. package/lib/Utils/process-message.js +372 -0
  77. package/lib/Utils/signal.js +143 -0
  78. package/lib/Utils/use-multi-file-auth-state.js +93 -0
  79. package/lib/Utils/validate-connection.js +207 -0
  80. package/lib/WABinary/constants.js +40 -0
  81. package/lib/WABinary/decode.js +265 -0
  82. package/lib/WABinary/encode.js +250 -0
  83. package/lib/WABinary/generic-utils.js +110 -0
  84. package/lib/WABinary/index.js +21 -0
  85. package/lib/WABinary/jid-utils.js +69 -0
  86. package/lib/WABinary/types.js +2 -0
  87. package/lib/WAM/BinaryInfo.js +13 -0
  88. package/lib/WAM/constants.js +15350 -0
  89. package/lib/WAM/encode.js +155 -0
  90. package/lib/WAM/index.js +19 -0
  91. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  92. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  93. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  94. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  95. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  96. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  97. package/lib/WAUSync/Protocols/index.js +20 -0
  98. package/lib/WAUSync/USyncQuery.js +89 -0
  99. package/lib/WAUSync/USyncUser.js +26 -0
  100. package/lib/WAUSync/index.js +19 -0
  101. package/lib/index.js +33 -0
  102. package/package.json +84 -0
@@ -0,0 +1,836 @@
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 WAProto_1 = require("../../WAProto");
10
+ const Defaults_1 = require("../Defaults");
11
+ const Utils_1 = require("../Utils");
12
+ const link_preview_1 = require("../Utils/link-preview");
13
+ const WABinary_1 = require("../WABinary");
14
+ const WAUSync_1 = require("../WAUSync");
15
+ const newsletter_1 = require("./newsletter");
16
+ var ListType = WAProto_1.proto.Message.ListMessage.ListType;
17
+ const makeMessagesSocket = (config) => {
18
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, } = 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 (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
263
+ var _a;
264
+ const meId = authState.creds.me.id;
265
+ let shouldIncludeDeviceIdentity = false;
266
+ const { user, server } = (0, WABinary_1.jidDecode)(jid);
267
+ const statusJid = 'status@broadcast';
268
+ const isGroup = server === 'g.us';
269
+ const isNewsletter = server == 'newsletter';
270
+ const isStatus = jid === statusJid;
271
+ const isLid = server === 'lid';
272
+ msgId = msgId || (0, Utils_1.generateMessageIDV2)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id);
273
+ useUserDevicesCache = useUserDevicesCache !== false;
274
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
275
+ const participants = [];
276
+ const destinationJid = (!isStatus) ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
277
+ const binaryNodeContent = [];
278
+ const devices = [];
279
+ const meMsg = {
280
+ deviceSentMessage: {
281
+ destinationJid,
282
+ message
283
+ }
284
+ };
285
+ const extraAttrs = {};
286
+ if (participant) {
287
+ // when the retry request is not for a group
288
+ // only send to the specific device that asked for a retry
289
+ // otherwise the message is sent out to every device that should be a recipient
290
+ if (!isGroup && !isStatus) {
291
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
292
+ }
293
+ const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
294
+ devices.push({ user, device });
295
+ }
296
+ await authState.keys.transaction(async () => {
297
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
298
+ const mediaType = getMediaType(message);
299
+ if (mediaType) {
300
+ extraAttrs['mediatype'] = mediaType;
301
+ }
302
+ if ((_a = (0, Utils_1.normalizeMessageContent)(message)) === null || _a === void 0 ? void 0 : _a.pinInChatMessage) {
303
+ extraAttrs['decrypt-fail'] = 'hide';
304
+ }
305
+ if (isGroup || isStatus) {
306
+ const [groupData, senderKeyMap] = await Promise.all([
307
+ (async () => {
308
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
309
+ if (groupData && Array.isArray(groupData === null || groupData === void 0 ? void 0 : groupData.participants)) {
310
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
311
+ }
312
+ else if (!isStatus) {
313
+ groupData = await groupMetadata(jid);
314
+ }
315
+ return groupData;
316
+ })(),
317
+ (async () => {
318
+ if (!participant && !isStatus) {
319
+ const result = await authState.keys.get('sender-key-memory', [jid]);
320
+ return result[jid] || {};
321
+ }
322
+ return {};
323
+ })()
324
+ ]);
325
+ if (!participant) {
326
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
327
+ if (isStatus && statusJidList) {
328
+ participantsList.push(...statusJidList);
329
+ }
330
+ if (!isStatus) {
331
+ additionalAttributes = {
332
+ ...additionalAttributes,
333
+ // eslint-disable-next-line camelcase
334
+ addressing_mode: (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) || 'pn'
335
+ };
336
+ }
337
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
338
+ devices.push(...additionalDevices);
339
+ }
340
+ const patched = await patchMessageBeforeSending(message);
341
+ if (Array.isArray(patched)) {
342
+ throw new boom_1.Boom('Per-jid patching is not supported in groups');
343
+ }
344
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
345
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
346
+ group: destinationJid,
347
+ data: bytes,
348
+ meId,
349
+ });
350
+ const senderKeyJids = [];
351
+ // ensure a connection is established with every device
352
+ for (const { user, device } of devices) {
353
+ const jid = (0, WABinary_1.jidEncode)(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
354
+ if (!senderKeyMap[jid] || !!participant) {
355
+ senderKeyJids.push(jid);
356
+ // store that this person has had the sender keys sent to them
357
+ senderKeyMap[jid] = true;
358
+ }
359
+ }
360
+ // if there are some participants with whom the session has not been established
361
+ // if there are, we re-send the senderkey
362
+ if (senderKeyJids.length) {
363
+ logger.debug({ senderKeyJids }, 'sending new sender key');
364
+ const senderKeyMsg = {
365
+ senderKeyDistributionMessage: {
366
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
367
+ groupId: destinationJid
368
+ }
369
+ };
370
+ await assertSessions(senderKeyJids, false);
371
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs);
372
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
373
+ participants.push(...result.nodes);
374
+ }
375
+ binaryNodeContent.push({
376
+ tag: 'enc',
377
+ attrs: { v: '2', type: 'skmsg' },
378
+ content: ciphertext
379
+ });
380
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
381
+ }
382
+ else if (isNewsletter) {
383
+ // Message edit
384
+ if ((_b = message.protocolMessage) === null || _b === void 0 ? void 0 : _b.editedMessage) {
385
+ msgId = (_c = message.protocolMessage.key) === null || _c === void 0 ? void 0 : _c.id;
386
+ message = message.protocolMessage.editedMessage;
387
+ }
388
+ // Message delete
389
+ if (((_d = message.protocolMessage) === null || _d === void 0 ? void 0 : _d.type) === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
390
+ msgId = (_e = message.protocolMessage.key) === null || _e === void 0 ? void 0 : _e.id;
391
+ message = {};
392
+ }
393
+ const patched = await patchMessageBeforeSending(message, []);
394
+ if (Array.isArray(patched)) {
395
+ throw new boom_1.Boom('Per-jid patching is not supported in channel');
396
+ }
397
+ const bytes = (0, Utils_1.encodeNewsletterMessage)(patched);
398
+ binaryNodeContent.push({
399
+ tag: 'plaintext',
400
+ attrs: mediaType ? { mediatype: mediaType } : {},
401
+ content: bytes
402
+ });
403
+ }
404
+ else {
405
+ const { user: meUser, device: meDevice } = (0, WABinary_1.jidDecode)(meId);
406
+ if (!participant) {
407
+ devices.push({ user });
408
+ // do not send message to self if the device is 0 (mobile)
409
+ if (!((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer' && user === meUser)) {
410
+ if (meDevice !== undefined && meDevice !== 0) {
411
+ devices.push({ user: meUser });
412
+ }
413
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
414
+ devices.push(...additionalDevices);
415
+ }
416
+ }
417
+ const allJids = [];
418
+ const meJids = [];
419
+ const otherJids = [];
420
+ for (const { user, device } of devices) {
421
+ const isMe = user === meUser;
422
+ const jid = (0, WABinary_1.jidEncode)(isMe && isLid ? ((_g = (_f = authState.creds) === null || _f === void 0 ? void 0 : _f.me) === null || _g === void 0 ? void 0 : _g.lid.split(':')[0]) || user : user, isLid ? 'lid' : 's.whatsapp.net', device);
423
+ if (isMe) {
424
+ meJids.push(jid);
425
+ }
426
+ else {
427
+ otherJids.push(jid);
428
+ }
429
+ allJids.push(jid);
430
+ }
431
+ await assertSessions(allJids, false);
432
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
433
+ createParticipantNodes(meJids, meMsg, extraAttrs),
434
+ createParticipantNodes(otherJids, message, extraAttrs)
435
+ ]);
436
+ participants.push(...meNodes);
437
+ participants.push(...otherNodes);
438
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
439
+ }
440
+ if (participants.length) {
441
+ if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer') {
442
+ const peerNode = (_j = (_h = participants[0]) === null || _h === void 0 ? void 0 : _h.content) === null || _j === void 0 ? void 0 : _j[0];
443
+ if (peerNode) {
444
+ binaryNodeContent.push(peerNode); // push only enc
445
+ }
446
+ }
447
+ else {
448
+ binaryNodeContent.push({
449
+ tag: 'participants',
450
+ attrs: {},
451
+ content: participants
452
+ });
453
+ }
454
+ }
455
+ const stanza = {
456
+ tag: 'message',
457
+ attrs: {
458
+ id: msgId,
459
+ type: isNewsletter ? getTypeMessage(message) : 'text',//getTypeMessage(message),
460
+ ...(additionalAttributes || {})
461
+ },
462
+ content: binaryNodeContent
463
+ };
464
+ // if the participant to send to is explicitly specified (generally retry recp)
465
+ // ensure the message is only sent to that person
466
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
467
+ if (participant) {
468
+ if ((0, WABinary_1.isJidGroup)(destinationJid)) {
469
+ stanza.attrs.to = destinationJid;
470
+ stanza.attrs.participant = participant.jid;
471
+ }
472
+ else if ((0, WABinary_1.areJidsSameUser)(participant.jid, meId)) {
473
+ stanza.attrs.to = participant.jid;
474
+ stanza.attrs.recipient = destinationJid;
475
+ }
476
+ else {
477
+ stanza.attrs.to = participant.jid;
478
+ }
479
+ }
480
+ else {
481
+ stanza.attrs.to = destinationJid;
482
+ }
483
+ if (shouldIncludeDeviceIdentity) {
484
+ stanza.content.push({
485
+ tag: 'device-identity',
486
+ attrs: {},
487
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
488
+ });
489
+ logger.debug({ jid }, 'adding device identity');
490
+ }
491
+ const buttonType = getButtonType(message);
492
+ if (buttonType) {
493
+ stanza.content.push({
494
+ tag: 'biz',
495
+ attrs: {},
496
+ content: [
497
+ {
498
+ tag: buttonType,
499
+ attrs: getButtonArgs(message),
500
+ }
501
+ ]
502
+ });
503
+ logger.debug({ jid }, 'adding business node');
504
+ }
505
+ if (additionalNodes && additionalNodes.length > 0) {
506
+ stanza.content.push(...additionalNodes);
507
+ }
508
+ else {
509
+ if (((0, WABinary_1.isJidGroup)(jid) || (0, WABinary_1.isJidUser)(jid)) && (((_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))) {
510
+ stanza.content.push({
511
+ tag: 'biz',
512
+ attrs: {},
513
+ content: [{
514
+ tag: 'interactive',
515
+ attrs: {
516
+ type: 'native_flow',
517
+ v: '1'
518
+ },
519
+ content: [{
520
+ tag: 'native_flow',
521
+ attrs: { name: 'quick_reply' }
522
+ }]
523
+ }]
524
+ });
525
+ }
526
+ }
527
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
528
+ await sendNode(stanza);
529
+ });
530
+ return msgId;
531
+ };
532
+ /*const getMessageType = (message) => {
533
+ if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3 || message.pollUpdateMessage) {
534
+ return 'poll';
535
+ }
536
+ return 'text';
537
+ };*/
538
+ const getTypeMessage = (msg) => {
539
+ if (msg.viewOnceMessage) {
540
+ return getTypeMessage(msg.viewOnceMessage.message);
541
+ }
542
+ else if (msg.viewOnceMessageV2) {
543
+ return getTypeMessage(msg.viewOnceMessageV2.message);
544
+ }
545
+ else if (msg.viewOnceMessageV2Extension) {
546
+ return getTypeMessage(msg.viewOnceMessageV2Extension.message);
547
+ }
548
+ else if (msg.ephemeralMessage) {
549
+ return getTypeMessage(msg.ephemeralMessage.message);
550
+ }
551
+ else if (msg.documentWithCaptionMessage) {
552
+ return getTypeMessage(msg.documentWithCaptionMessage.message);
553
+ }
554
+ else if (msg.reactionMessage) {
555
+ return 'reaction';
556
+ }
557
+ else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
558
+ return 'reaction';
559
+ }
560
+ else if (getMediaType(msg)) {
561
+ return 'media';
562
+ }
563
+ else {
564
+ return 'text';
565
+ }
566
+ };
567
+ const getMediaType = (message) => {
568
+ if (message.imageMessage) {
569
+ return 'image';
570
+ }
571
+ else if (message.videoMessage) {
572
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
573
+ }
574
+ else if (message.audioMessage) {
575
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
576
+ }
577
+ else if (message.contactMessage) {
578
+ return 'vcard';
579
+ }
580
+ else if (message.documentMessage) {
581
+ return 'document';
582
+ }
583
+ else if (message.contactsArrayMessage) {
584
+ return 'contact_array';
585
+ }
586
+ else if (message.liveLocationMessage) {
587
+ return 'livelocation';
588
+ }
589
+ else if (message.stickerMessage) {
590
+ return 'sticker';
591
+ }
592
+ else if (message.listMessage) {
593
+ return 'list';
594
+ }
595
+ else if (message.listResponseMessage) {
596
+ return 'list_response';
597
+ }
598
+ else if (message.buttonsResponseMessage) {
599
+ return 'buttons_response';
600
+ }
601
+ else if (message.orderMessage) {
602
+ return 'order';
603
+ }
604
+ else if (message.productMessage) {
605
+ return 'product';
606
+ }
607
+ else if (message.interactiveResponseMessage) {
608
+ return 'native_flow_response';
609
+ }
610
+ else if (message.groupInviteMessage) {
611
+ return 'url';
612
+ }
613
+ };
614
+ const getButtonType = (message) => {
615
+ if (message.buttonsMessage) {
616
+ return 'buttons';
617
+ }
618
+ else if (message.buttonsResponseMessage) {
619
+ return 'buttons_response';
620
+ }
621
+ else if (message.interactiveResponseMessage) {
622
+ return 'interactive_response';
623
+ }
624
+ else if (message.listMessage) {
625
+ return 'list';
626
+ }
627
+ else if (message.listResponseMessage) {
628
+ return 'list_response';
629
+ }
630
+ };
631
+ const getButtonArgs = (message) => {
632
+ if (message.templateMessage) {
633
+ // TODO: Add attributes
634
+ return {};
635
+ }
636
+ else if (message.listMessage) {
637
+ const type = message.listMessage.listType;
638
+ if (!type) {
639
+ throw new boom_1.Boom('Expected list type inside message');
640
+ }
641
+ return { v: '2', type: ListType[type].toLowerCase() };
642
+ }
643
+ else {
644
+ return {};
645
+ }
646
+ };
647
+ const getPrivacyTokens = async (jids) => {
648
+ const t = (0, Utils_1.unixTimestampSeconds)().toString();
649
+ const result = await query({
650
+ tag: 'iq',
651
+ attrs: {
652
+ to: WABinary_1.S_WHATSAPP_NET,
653
+ type: 'set',
654
+ xmlns: 'privacy'
655
+ },
656
+ content: [
657
+ {
658
+ tag: 'tokens',
659
+ attrs: {},
660
+ content: jids.map(jid => ({
661
+ tag: 'token',
662
+ attrs: {
663
+ jid: (0, WABinary_1.jidNormalizedUser)(jid),
664
+ t,
665
+ type: 'trusted_contact'
666
+ }
667
+ }))
668
+ }
669
+ ]
670
+ });
671
+ return result;
672
+ };
673
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
674
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
675
+ return {
676
+ ...sock,
677
+ getPrivacyTokens,
678
+ assertSessions,
679
+ relayMessage,
680
+ sendReceipt,
681
+ sendReceipts,
682
+ getButtonArgs,
683
+ readMessages,
684
+ refreshMediaConn,
685
+ waUploadToServer,
686
+ fetchPrivacySettings,
687
+ getUSyncDevices,
688
+ createParticipantNodes,
689
+ sendPeerDataOperationMessage,
690
+ updateMediaMessage: async (message) => {
691
+ const content = (0, Utils_1.assertMediaContent)(message.message);
692
+ const mediaKey = content.mediaKey;
693
+ const meId = authState.creds.me.id;
694
+ const node = await (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
695
+ let error = undefined;
696
+ await Promise.all([
697
+ sendNode(node),
698
+ waitForMsgMediaUpdate(async (update) => {
699
+ const result = update.find(c => c.key.id === message.key.id);
700
+ if (result) {
701
+ if (result.error) {
702
+ error = result.error;
703
+ }
704
+ else {
705
+ try {
706
+ const media = await (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
707
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
708
+ const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
709
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
710
+ }
711
+ content.directPath = media.directPath;
712
+ content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
713
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
714
+ }
715
+ catch (err) {
716
+ error = err;
717
+ }
718
+ }
719
+ return true;
720
+ }
721
+ })
722
+ ]);
723
+ if (error) {
724
+ throw error;
725
+ }
726
+ ev.emit('messages.update', [
727
+ { key: message.key, update: { message: message.message } }
728
+ ]);
729
+ return message;
730
+ },
731
+ sendMessage: async (jid, content, options = {}) => {
732
+ var _a, _b, _c;
733
+ const userJid = authState.creds.me.id;
734
+ if (typeof content === 'object' &&
735
+ 'disappearingMessagesInChat' in content &&
736
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
737
+ (0, WABinary_1.isJidGroup)(jid)) {
738
+ const { disappearingMessagesInChat } = content;
739
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
740
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
741
+ disappearingMessagesInChat;
742
+ await groupToggleEphemeral(jid, value);
743
+ }
744
+ else {
745
+ let mediaHandle;
746
+ const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
747
+ logger,
748
+ userJid,
749
+ getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
750
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
751
+ fetchOpts: {
752
+ timeout: 3000,
753
+ ...axiosOptions || {}
754
+ },
755
+ logger,
756
+ uploadImage: generateHighQualityLinkPreview
757
+ ? waUploadToServer
758
+ : undefined
759
+ }),
760
+ getProfilePicUrl: sock.profilePictureUrl,
761
+ upload: async (readStream, opts) => {
762
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
763
+ mediaHandle = up.handle;
764
+ return up;
765
+ },
766
+ mediaCache: config.mediaCache,
767
+ options: config.options,
768
+ messageId: (0, Utils_1.generateMessageIDV2)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id),
769
+ ...options,
770
+ });
771
+ const isDeleteMsg = 'delete' in content && !!content.delete;
772
+ const isEditMsg = 'edit' in content && !!content.edit;
773
+ const isPinMsg = 'pin' in content && !!content.pin;
774
+ const isKeepMsg = 'keep' in content && content.keep;
775
+ const isPollMessage = 'poll' in content && !!content.poll;
776
+ const isAiMsg = 'ai' in content && !!content.ai;
777
+ const additionalAttributes = {};
778
+ const additionalNodes = [];
779
+ // required for delete
780
+ if (isDeleteMsg) {
781
+ // if the chat is a group, and I am not the author, then delete the message as an admin
782
+ if (((0, WABinary_1.isJidGroup)((_b = content.delete) === null || _b === void 0 ? void 0 : _b.remoteJid) && !((_c = content.delete) === null || _c === void 0 ? void 0 : _c.fromMe)) || (0, WABinary_1.isJidNewsletter)(jid)) {
783
+ additionalAttributes.edit = '8';
784
+ }
785
+ else {
786
+ additionalAttributes.edit = '7';
787
+ }
788
+ // required for edit message
789
+ }
790
+ else if (isEditMsg) {
791
+ additionalAttributes.edit = (0, WABinary_1.isJidNewsletter)(jid) ? '3' : '1';
792
+ // required for pin message
793
+ }
794
+ else if (isPinMsg) {
795
+ additionalAttributes.edit = '2';
796
+ // required for keep message
797
+ }
798
+ else if (isKeepMsg) {
799
+ additionalAttributes.edit = '6';
800
+ // required for polling message
801
+ }
802
+ else if (isPollMessage) {
803
+ additionalNodes.push({
804
+ tag: 'meta',
805
+ attrs: {
806
+ polltype: 'creation'
807
+ },
808
+ });
809
+ // required to display AI icon on message
810
+ }
811
+ else if (isAiMsg) {
812
+ additionalNodes.push({
813
+ attrs: {
814
+ biz_bot: '1'
815
+ },
816
+ tag: "bot"
817
+ });
818
+ }
819
+ if (mediaHandle) {
820
+ additionalAttributes['media_id'] = mediaHandle;
821
+ }
822
+ if ('cachedGroupMetadata' in options) {
823
+ console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
824
+ }
825
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, statusJidList: options.statusJidList });
826
+ if (config.emitOwnEvents) {
827
+ process.nextTick(() => {
828
+ processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
829
+ });
830
+ }
831
+ return fullMsg;
832
+ }
833
+ }
834
+ };
835
+ };
836
+ exports.makeMessagesSocket = makeMessagesSocket;