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