@devpeacemaker/baileys 2.0.1

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