@mihiranga_mihiranga/mezuka-baileys 1.0.2

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 (114) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +651 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +4775 -0
  5. package/WAProto/index.js +169661 -0
  6. package/WAProto//342/235/244/357/270/217 +1 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/baileys-version.json +3 -0
  9. package/lib/Defaults/index.js +112 -0
  10. package/lib/Defaults/phonenumber-mcc.json +223 -0
  11. package/lib/Defaults//360/237/222/226 +1 -0
  12. package/lib/Signal/Group/ciphertext-message.js +15 -0
  13. package/lib/Signal/Group/group-session-builder.js +64 -0
  14. package/lib/Signal/Group/group_cipher.js +96 -0
  15. package/lib/Signal/Group/index.js +57 -0
  16. package/lib/Signal/Group/keyhelper.js +55 -0
  17. package/lib/Signal/Group/queue-job.js +57 -0
  18. package/lib/Signal/Group/sender-chain-key.js +34 -0
  19. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  20. package/lib/Signal/Group/sender-key-message.js +69 -0
  21. package/lib/Signal/Group/sender-key-name.js +51 -0
  22. package/lib/Signal/Group/sender-key-record.js +53 -0
  23. package/lib/Signal/Group/sender-key-state.js +99 -0
  24. package/lib/Signal/Group/sender-message-key.js +29 -0
  25. package/lib/Signal/Group//342/235/244/357/270/217 +1 -0
  26. package/lib/Signal/libsignal.js +174 -0
  27. package/lib/Signal//360/237/222/226 +1 -0
  28. package/lib/Socket/Client/index.js +18 -0
  29. package/lib/Socket/Client/types.js +13 -0
  30. package/lib/Socket/Client/websocket.js +72 -0
  31. package/lib/Socket/Client//342/235/244/357/270/217 +1 -0
  32. package/lib/Socket/business.js +260 -0
  33. package/lib/Socket/chats.js +890 -0
  34. package/lib/Socket/groups.js +332 -0
  35. package/lib/Socket/index.js +10 -0
  36. package/lib/Socket/messages-recv.js +1142 -0
  37. package/lib/Socket/messages-send.js +1068 -0
  38. package/lib/Socket/newsletter.js +250 -0
  39. package/lib/Socket/socket.js +654 -0
  40. package/lib/Socket/usync.js +70 -0
  41. package/lib/Socket//360/237/222/236 +1 -0
  42. package/lib/Store/index.js +8 -0
  43. package/lib/Store/make-in-memory-store.js +429 -0
  44. package/lib/Store/make-ordered-dictionary.js +81 -0
  45. package/lib/Store/object-repository.js +27 -0
  46. package/lib/Store//342/235/244/357/270/217 +1 -0
  47. package/lib/Types/Auth.js +2 -0
  48. package/lib/Types/Call.js +2 -0
  49. package/lib/Types/Chat.js +4 -0
  50. package/lib/Types/Contact.js +2 -0
  51. package/lib/Types/Events.js +2 -0
  52. package/lib/Types/GroupMetadata.js +2 -0
  53. package/lib/Types/Label.js +27 -0
  54. package/lib/Types/LabelAssociation.js +9 -0
  55. package/lib/Types/Message.js +7 -0
  56. package/lib/Types/Newsletter.js +18 -0
  57. package/lib/Types/Product.js +2 -0
  58. package/lib/Types/Signal.js +2 -0
  59. package/lib/Types/Socket.js +2 -0
  60. package/lib/Types/State.js +2 -0
  61. package/lib/Types/USync.js +2 -0
  62. package/lib/Types/index.js +42 -0
  63. package/lib/Types//360/237/222/236 +1 -0
  64. package/lib/Utils/auth-utils.js +199 -0
  65. package/lib/Utils/baileys-event-stream.js +63 -0
  66. package/lib/Utils/browser-utils.js +35 -0
  67. package/lib/Utils/business.js +234 -0
  68. package/lib/Utils/chat-utils.js +730 -0
  69. package/lib/Utils/crypto.js +193 -0
  70. package/lib/Utils/decode-wa-message.js +207 -0
  71. package/lib/Utils/event-buffer.js +518 -0
  72. package/lib/Utils/generics.js +473 -0
  73. package/lib/Utils/history.js +95 -0
  74. package/lib/Utils/index.js +33 -0
  75. package/lib/Utils/link-preview.js +126 -0
  76. package/lib/Utils/logger.js +7 -0
  77. package/lib/Utils/lt-hash.js +51 -0
  78. package/lib/Utils/make-mutex.js +43 -0
  79. package/lib/Utils/messages-media.js +880 -0
  80. package/lib/Utils/messages.js +1154 -0
  81. package/lib/Utils/noise-handler.js +150 -0
  82. package/lib/Utils/process-message.js +372 -0
  83. package/lib/Utils/signal.js +153 -0
  84. package/lib/Utils/use-multi-file-auth-state.js +125 -0
  85. package/lib/Utils/validate-connection.js +199 -0
  86. package/lib/Utils//342/235/244/357/270/217 +1 -0
  87. package/lib/WABinary/constants.js +1303 -0
  88. package/lib/WABinary/decode.js +265 -0
  89. package/lib/WABinary/encode.js +250 -0
  90. package/lib/WABinary/generic-utils.js +130 -0
  91. package/lib/WABinary/index.js +21 -0
  92. package/lib/WABinary/jid-utils.js +83 -0
  93. package/lib/WABinary/types.js +2 -0
  94. package/lib/WABinary//360/237/222/226 +1 -0
  95. package/lib/WAM/BinaryInfo.js +13 -0
  96. package/lib/WAM/constants.js +15350 -0
  97. package/lib/WAM/encode.js +155 -0
  98. package/lib/WAM/index.js +19 -0
  99. package/lib/WAM//360/237/222/226 +1 -0
  100. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  101. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  102. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  103. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  104. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  105. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  106. package/lib/WAUSync/Protocols/index.js +20 -0
  107. package/lib/WAUSync/Protocols//342/235/244/357/270/217 +1 -0
  108. package/lib/WAUSync/USyncQuery.js +89 -0
  109. package/lib/WAUSync/USyncUser.js +26 -0
  110. package/lib/WAUSync/index.js +19 -0
  111. package/lib/WAUSync//360/237/222/226 +1 -0
  112. package/lib/index.js +45 -0
  113. package/lib//360/237/222/226 +1 -0
  114. package/package.json +121 -0
@@ -0,0 +1,1068 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeMessagesSocket = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
+ const crypto_1 = require("crypto");
10
+ const WAProto_1 = require("../../WAProto");
11
+ const Defaults_1 = require("../Defaults");
12
+ const Utils_1 = require("../Utils");
13
+ const link_preview_1 = require("../Utils/link-preview");
14
+ const WABinary_1 = require("../WABinary");
15
+ const WAUSync_1 = require("../WAUSync");
16
+ const newsletter_1 = require("./newsletter");
17
+ const makeMessagesSocket = (config) => {
18
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, } = 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, AI = true }) => {
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
+ const isPrivate = server === 's.whatsapp.net';
273
+ msgId = msgId || (0, Utils_1.generateMessageIDV2)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id);
274
+ useUserDevicesCache = useUserDevicesCache !== false;
275
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
276
+ const participants = [];
277
+ const destinationJid = (!isStatus) ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
278
+ const binaryNodeContent = [];
279
+ const devices = [];
280
+ const meMsg = {
281
+ deviceSentMessage: {
282
+ destinationJid,
283
+ message
284
+ },
285
+ messageContextInfo: message.messageContextInfo
286
+ };
287
+ const extraAttrs = {};
288
+ if (participant) {
289
+ // when the retry request is not for a group
290
+ // only send to the specific device that asked for a retry
291
+ // otherwise the message is sent out to every device that should be a recipient
292
+ if (!isGroup && !isStatus) {
293
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
294
+ }
295
+ const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
296
+ devices.push({ user, device });
297
+ }
298
+ await authState.keys.transaction(async () => {
299
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
300
+ const mediaType = getMediaType(message);
301
+ if (mediaType) {
302
+ extraAttrs['mediatype'] = mediaType;
303
+ }
304
+ if ((_a = (0, Utils_1.normalizeMessageContent)(message)) === null || _a === void 0 ? void 0 : _a.pinInChatMessage) {
305
+ extraAttrs['decrypt-fail'] = 'hide';
306
+ }
307
+ if (isGroup || isStatus) {
308
+ const [groupData, senderKeyMap] = await Promise.all([
309
+ (async () => {
310
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
311
+ if (groupData && Array.isArray(groupData === null || groupData === void 0 ? void 0 : groupData.participants)) {
312
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
313
+ }
314
+ else if (!isStatus) {
315
+ groupData = await groupMetadata(jid);
316
+ }
317
+ return groupData;
318
+ })(),
319
+ (async () => {
320
+ if (!participant && !isStatus) {
321
+ const result = await authState.keys.get('sender-key-memory', [jid]);
322
+ return result[jid] || {};
323
+ }
324
+ return {};
325
+ })()
326
+ ]);
327
+ if (!participant) {
328
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
329
+ if (isStatus && statusJidList) {
330
+ participantsList.push(...statusJidList);
331
+ }
332
+ if (!isStatus) {
333
+ additionalAttributes = {
334
+ ...additionalAttributes,
335
+ // eslint-disable-next-line camelcase
336
+ addressing_mode: (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) || 'pn'
337
+ };
338
+ }
339
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
340
+ devices.push(...additionalDevices);
341
+ }
342
+ const patched = await patchMessageBeforeSending(message);
343
+ if (Array.isArray(patched)) {
344
+ throw new boom_1.Boom('Per-jid patching is not supported in groups');
345
+ }
346
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
347
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
348
+ group: destinationJid,
349
+ data: bytes,
350
+ meId,
351
+ });
352
+ const senderKeyJids = [];
353
+ // ensure a connection is established with every device
354
+ for (const { user, device } of devices) {
355
+ const jid = (0, WABinary_1.jidEncode)(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
356
+ if (!senderKeyMap[jid] || !!participant) {
357
+ senderKeyJids.push(jid);
358
+ // store that this person has had the sender keys sent to them
359
+ senderKeyMap[jid] = true;
360
+ }
361
+ }
362
+ // if there are some participants with whom the session has not been established
363
+ // if there are, we re-send the senderkey
364
+ if (senderKeyJids.length) {
365
+ logger.debug({ senderKeyJids }, 'sending new sender key');
366
+ const senderKeyMsg = {
367
+ senderKeyDistributionMessage: {
368
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
369
+ groupId: destinationJid
370
+ }
371
+ };
372
+ await assertSessions(senderKeyJids, false);
373
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs);
374
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
375
+ participants.push(...result.nodes);
376
+ }
377
+ binaryNodeContent.push({
378
+ tag: 'enc',
379
+ attrs: { v: '2', type: 'skmsg' },
380
+ content: ciphertext
381
+ });
382
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
383
+ }
384
+ else if (isNewsletter) {
385
+ // Message edit
386
+ if ((_b = message.protocolMessage) === null || _b === void 0 ? void 0 : _b.editedMessage) {
387
+ msgId = (_c = message.protocolMessage.key) === null || _c === void 0 ? void 0 : _c.id;
388
+ message = message.protocolMessage.editedMessage;
389
+ }
390
+ // Message delete
391
+ if (((_d = message.protocolMessage) === null || _d === void 0 ? void 0 : _d.type) === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
392
+ msgId = (_e = message.protocolMessage.key) === null || _e === void 0 ? void 0 : _e.id;
393
+ message = {};
394
+ }
395
+ const patched = await patchMessageBeforeSending(message, []);
396
+ if (Array.isArray(patched)) {
397
+ throw new boom_1.Boom('Per-jid patching is not supported in channel');
398
+ }
399
+ const bytes = (0, Utils_1.encodeNewsletterMessage)(patched);
400
+ binaryNodeContent.push({
401
+ tag: 'plaintext',
402
+ attrs: mediaType ? { mediatype: mediaType } : {},
403
+ content: bytes
404
+ });
405
+ }
406
+ else {
407
+ const { user: meUser } = (0, WABinary_1.jidDecode)(meId);
408
+ if (!participant) {
409
+ devices.push({ user });
410
+ if (user !== meUser) {
411
+ devices.push({ user: meUser });
412
+ }
413
+ if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) !== 'peer') {
414
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
415
+ devices.push(...additionalDevices);
416
+ }
417
+ }
418
+ const allJids = [];
419
+ const meJids = [];
420
+ const otherJids = [];
421
+ for (const { user, device } of devices) {
422
+ const isMe = user === meUser;
423
+ 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);
424
+ if (isMe) {
425
+ meJids.push(jid);
426
+ }
427
+ else {
428
+ otherJids.push(jid);
429
+ }
430
+ allJids.push(jid);
431
+ }
432
+ await assertSessions(allJids, false);
433
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
434
+ createParticipantNodes(meJids, meMsg, extraAttrs),
435
+ createParticipantNodes(otherJids, message, extraAttrs)
436
+ ]);
437
+ participants.push(...meNodes);
438
+ participants.push(...otherNodes);
439
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
440
+ }
441
+ if (participants.length) {
442
+ if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer') {
443
+ const peerNode = (_j = (_h = participants[0]) === null || _h === void 0 ? void 0 : _h.content) === null || _j === void 0 ? void 0 : _j[0];
444
+ if (peerNode) {
445
+ binaryNodeContent.push(peerNode); // push only enc
446
+ }
447
+ }
448
+ else {
449
+ binaryNodeContent.push({
450
+ tag: 'participants',
451
+ attrs: {},
452
+ content: participants
453
+ });
454
+ }
455
+ }
456
+ const stanza = {
457
+ tag: 'message',
458
+ attrs: {
459
+ id: msgId,
460
+ type: isNewsletter ? getTypeMessage(message) : 'text',
461
+ ...(additionalAttributes || {})
462
+ },
463
+ content: binaryNodeContent
464
+ };
465
+ // if the participant to send to is explicitly specified (generally retry recp)
466
+ // ensure the message is only sent to that person
467
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
468
+ if (participant) {
469
+ if ((0, WABinary_1.isJidGroup)(destinationJid)) {
470
+ stanza.attrs.to = destinationJid;
471
+ stanza.attrs.participant = participant.jid;
472
+ }
473
+ else if ((0, WABinary_1.areJidsSameUser)(participant.jid, meId)) {
474
+ stanza.attrs.to = participant.jid;
475
+ stanza.attrs.recipient = destinationJid;
476
+ }
477
+ else {
478
+ stanza.attrs.to = participant.jid;
479
+ }
480
+ }
481
+ else {
482
+ stanza.attrs.to = destinationJid;
483
+ }
484
+ if (shouldIncludeDeviceIdentity) {
485
+ stanza.content.push({
486
+ tag: 'device-identity',
487
+ attrs: {},
488
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
489
+ });
490
+ logger.debug({ jid }, 'adding device identity');
491
+ }
492
+
493
+ if (AI && isPrivate) {
494
+ const botNode = {
495
+ tag: 'bot',
496
+ attrs: {
497
+ biz_bot: '1'
498
+ }
499
+ }
500
+
501
+ const filteredBizBot = WABinary_1.getBinaryNodeFilter(additionalNodes ? additionalNodes : [])
502
+
503
+ if (filteredBizBot) {
504
+ stanza.content.push(...additionalNodes)
505
+ didPushAdditional = true
506
+ }
507
+
508
+ else {
509
+ stanza.content.push(botNode)
510
+ }
511
+ }
512
+ if (additionalNodes && additionalNodes.length > 0) {
513
+ stanza.content.push(...additionalNodes);
514
+ }
515
+ const content = (0, Utils_1.normalizeMessageContent)(message);
516
+ const contentType = (0, Utils_1.getContentType)(content);
517
+ if (((0, WABinary_1.isJidGroup)(jid) || (0, WABinary_1.isJidUser)(jid)) && (contentType === 'interactiveMessage' ||
518
+ contentType === 'buttonsMessage' ||
519
+ contentType === 'listMessage')) {
520
+ const bizNode = { tag: 'biz', attrs: {} };
521
+ 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))) {
522
+ bizNode.content = [{
523
+ tag: 'interactive',
524
+ attrs: {
525
+ type: 'native_flow',
526
+ v: '1'
527
+ },
528
+ content: [{
529
+ tag: 'native_flow',
530
+ attrs: { v: '9', name: 'mixed' }
531
+ }]
532
+ }];
533
+ }
534
+ else if (message === null || message === void 0 ? void 0 : message.listMessage) {
535
+ // list message only support in private chat
536
+ bizNode.content = [{
537
+ tag: 'list',
538
+ attrs: {
539
+ type: 'product_list',
540
+ v: '2'
541
+ }
542
+ }];
543
+ }
544
+ stanza.content.push(bizNode);
545
+ }
546
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
547
+ await sendNode(stanza);
548
+ });
549
+ return msgId;
550
+ };
551
+ const getTypeMessage = (msg) => {
552
+ if (msg.viewOnceMessage) {
553
+ return getTypeMessage(msg.viewOnceMessage.message);
554
+ }
555
+ else if (msg.viewOnceMessageV2) {
556
+ return getTypeMessage(msg.viewOnceMessageV2.message);
557
+ }
558
+ else if (msg.viewOnceMessageV2Extension) {
559
+ return getTypeMessage(msg.viewOnceMessageV2Extension.message);
560
+ }
561
+ else if (msg.ephemeralMessage) {
562
+ return getTypeMessage(msg.ephemeralMessage.message);
563
+ }
564
+ else if (msg.documentWithCaptionMessage) {
565
+ return getTypeMessage(msg.documentWithCaptionMessage.message);
566
+ }
567
+ else if (msg.reactionMessage) {
568
+ return 'reaction';
569
+ }
570
+ else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
571
+ return 'poll';
572
+ }
573
+ else if (msg.eventMessage) {
574
+ return 'event';
575
+ }
576
+ else if (getMediaType(msg)) {
577
+ return 'media';
578
+ }
579
+ else {
580
+ return 'text';
581
+ }
582
+ };
583
+ const getMediaType = (message) => {
584
+ if (message.imageMessage) {
585
+ return 'image';
586
+ }
587
+ else if (message.videoMessage) {
588
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
589
+ }
590
+ else if (message.audioMessage) {
591
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
592
+ }
593
+ else if (message.ptvMessage) {
594
+ return 'ptv';
595
+ }
596
+ else if (message.albumMessage) {
597
+ return 'collection';
598
+ }
599
+ else if (message.contactMessage) {
600
+ return 'vcard';
601
+ }
602
+ else if (message.documentMessage) {
603
+ return 'document';
604
+ }
605
+ else if (message.contactsArrayMessage) {
606
+ return 'contact_array';
607
+ }
608
+ else if (message.locationMessage) {
609
+ return 'location';
610
+ }
611
+ else if (message.liveLocationMessage) {
612
+ return 'livelocation';
613
+ }
614
+ else if (message.stickerMessage) {
615
+ return 'sticker';
616
+ }
617
+ else if (message.listMessage) {
618
+ return 'list';
619
+ }
620
+ else if (message.listResponseMessage) {
621
+ return 'list_response';
622
+ }
623
+ else if (message.buttonsResponseMessage) {
624
+ return 'buttons_response';
625
+ }
626
+ else if (message.orderMessage) {
627
+ return 'order';
628
+ }
629
+ else if (message.productMessage) {
630
+ return 'product';
631
+ }
632
+ else if (message.interactiveResponseMessage) {
633
+ return 'native_flow_response';
634
+ }
635
+ else if (/https:\/\/wa\.me\/c\/\d+/.test(message.extendedTextMessage?.text)) {
636
+ return 'cataloglink'
637
+ }
638
+ else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
639
+ return 'productlink'
640
+ }
641
+ else if (message.groupInviteMessage) {
642
+ return 'url';
643
+ }
644
+ };
645
+ const getButtonType = (message) => {
646
+ if (message.listMessage) {
647
+ return 'list'
648
+ }
649
+ else if (message.buttonsMessage) {
650
+ return 'buttons'
651
+ }
652
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
653
+ return 'review_and_pay'
654
+ }
655
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
656
+ return 'review_order'
657
+ }
658
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
659
+ return 'payment_info'
660
+ }
661
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
662
+ return 'payment_status'
663
+ }
664
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
665
+ return 'payment_method'
666
+ }
667
+ else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
668
+ return 'interactive'
669
+ }
670
+ else if (message.interactiveMessage?.nativeFlowMessage) {
671
+ return 'native_flow'
672
+ }
673
+ }
674
+ const getPrivacyTokens = async (jids) => {
675
+ const t = (0, Utils_1.unixTimestampSeconds)().toString();
676
+ const result = await query({
677
+ tag: 'iq',
678
+ attrs: {
679
+ to: WABinary_1.S_WHATSAPP_NET,
680
+ type: 'set',
681
+ xmlns: 'privacy'
682
+ },
683
+ content: [
684
+ {
685
+ tag: 'tokens',
686
+ attrs: {},
687
+ content: jids.map(jid => ({
688
+ tag: 'token',
689
+ attrs: {
690
+ jid: (0, WABinary_1.jidNormalizedUser)(jid),
691
+ t,
692
+ type: 'trusted_contact'
693
+ }
694
+ }))
695
+ }
696
+ ]
697
+ });
698
+ return result;
699
+ };
700
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
701
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
702
+ return {
703
+ ...sock,
704
+ getPrivacyTokens,
705
+ assertSessions,
706
+ relayMessage,
707
+ sendReceipt,
708
+ sendReceipts,
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
+ groupStatusMessage: async (jid, content) => {
758
+ const normalizedJid = WABinary_1.jidNormalizedUser(jid);
759
+
760
+ let waMsgContent;
761
+ if (content.message) {
762
+ waMsgContent = content;
763
+ } else {
764
+ waMsgContent = await Utils_1.generateWAMessageContent(content, {
765
+ upload: waUploadToServer
766
+ });
767
+ }
768
+
769
+ const groupStoryContent = {
770
+ groupStatusMessageV2: {
771
+ message: waMsgContent.message || waMsgContent
772
+ }
773
+ };
774
+
775
+ const msg = await Utils_1.generateWAMessageFromContent(
776
+ normalizedJid,
777
+ groupStoryContent,
778
+ {
779
+ userJid: authState.creds.me.id
780
+ }
781
+ );
782
+
783
+ await relayMessage(normalizedJid, msg.message, {
784
+ messageId: msg.key.id
785
+ });
786
+
787
+ return msg;
788
+ },
789
+ sendStatusMentions: async (content, jids = []) => {
790
+ const userJid = WABinary_1.jidNormalizedUser(authState.creds.me.id);
791
+ let allUsers = new Set();
792
+ allUsers.add(userJid);
793
+
794
+ for (const id of jids) {
795
+ const isGroup = WABinary_1.isJidGroup(id);
796
+ const isPrivate = WABinary_1.isJidUser(id);
797
+
798
+ if (isGroup) {
799
+ try {
800
+ const metadata = await (cachedGroupMetadata ? cachedGroupMetadata(id) : groupMetadata(id)) || await groupMetadata(id);
801
+ const participants = metadata.participants.map(p => WABinary_1.jidNormalizedUser(p.jid));
802
+ participants.forEach(jid => allUsers.add(jid));
803
+ } catch (error) {
804
+ logger.error(`Error getting metadata for group ${id}: ${error}`);
805
+ }
806
+ } else if (isPrivate) {
807
+ allUsers.add(WABinary_1.jidNormalizedUser(id));
808
+ }
809
+ }
810
+
811
+ const uniqueUsers = Array.from(allUsers);
812
+ const getRandomHexColor = () => "#" + Math.floor(Math.random() * 16777215).toString(16).padStart(6, "0");
813
+
814
+ const isMedia = content.image || content.video || content.audio;
815
+ const isAudio = !!content.audio;
816
+
817
+ const messageContent = { ...content };
818
+
819
+ if (isMedia && !isAudio) {
820
+ if (messageContent.text) {
821
+ messageContent.caption = messageContent.text;
822
+ delete messageContent.text;
823
+ }
824
+ delete messageContent.ptt;
825
+ delete messageContent.font;
826
+ delete messageContent.backgroundColor;
827
+ delete messageContent.textColor;
828
+ }
829
+
830
+ if (isAudio) {
831
+ delete messageContent.text;
832
+ delete messageContent.caption;
833
+ delete messageContent.font;
834
+ delete messageContent.textColor;
835
+ }
836
+
837
+ const font = !isMedia ? (content.font || Math.floor(Math.random() * 9)) : undefined;
838
+ const textColor = !isMedia ? (content.textColor || getRandomHexColor()) : undefined;
839
+ const backgroundColor = (!isMedia || isAudio) ? (content.backgroundColor || getRandomHexColor()) : undefined;
840
+ const ptt = isAudio ? (typeof content.ptt === 'boolean' ? content.ptt : true) : undefined;
841
+
842
+ let msg;
843
+ let mediaHandle;
844
+ try {
845
+ msg = await Utils_1.generateWAMessage(WABinary_1.STORIES_JID, messageContent, {
846
+ logger,
847
+ userJid,
848
+ getUrlInfo: text => link_preview_1.getUrlInfo(text, {
849
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
850
+ fetchOpts: { timeout: 3000, ...axiosOptions || {} },
851
+ logger,
852
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
853
+ }),
854
+ upload: async (encFilePath, opts) => {
855
+ const up = await waUploadToServer(encFilePath, { ...opts });
856
+ mediaHandle = up.handle;
857
+ return up;
858
+ },
859
+ mediaCache: config.mediaCache,
860
+ options: config.options,
861
+ font,
862
+ textColor,
863
+ backgroundColor,
864
+ ptt
865
+ });
866
+ } catch (error) {
867
+ logger.error(`Error generating message: ${error}`);
868
+ throw error;
869
+ }
870
+
871
+ await relayMessage(WABinary_1.STORIES_JID, msg.message, {
872
+ messageId: msg.key.id,
873
+ statusJidList: uniqueUsers,
874
+ additionalNodes: [
875
+ {
876
+ tag: 'meta',
877
+ attrs: {},
878
+ content: [
879
+ {
880
+ tag: 'mentioned_users',
881
+ attrs: {},
882
+ content: jids.map(jid => ({
883
+ tag: 'to',
884
+ attrs: { jid: WABinary_1.jidNormalizedUser(jid) }
885
+ }))
886
+ }]
887
+ }]
888
+ });
889
+
890
+ for (const id of jids) {
891
+ try {
892
+ const normalizedId = WABinary_1.jidNormalizedUser(id);
893
+ const isPrivate = WABinary_1.isJidUser(normalizedId);
894
+ const type = isPrivate ? 'statusMentionMessage' : 'groupStatusMentionMessage';
895
+
896
+ const protocolMessage = {
897
+ [type]: {
898
+ message: {
899
+ protocolMessage: {
900
+ key: msg.key,
901
+ type: 25
902
+ }
903
+ }
904
+ },
905
+ messageContextInfo: {
906
+ messageSecret: (0, crypto_1.randomBytes)(32)
907
+ }
908
+ };
909
+
910
+ const statusMsg = await Utils_1.generateWAMessageFromContent(normalizedId,
911
+ protocolMessage,
912
+ {}
913
+ );
914
+
915
+ await relayMessage(
916
+ normalizedId,
917
+ statusMsg.message,
918
+ {
919
+ additionalNodes: [{
920
+ tag: 'meta',
921
+ attrs: isPrivate ?
922
+ { is_status_mention: 'true' } :
923
+ { is_group_status_mention: 'true' }
924
+ }]
925
+ }
926
+ );
927
+
928
+ await (0, Utils_1.delay)(2000);
929
+ } catch (error) {
930
+ logger.error(`Error sending to ${id}: ${error}`);
931
+ }
932
+ }
933
+
934
+ return msg;
935
+ },
936
+ sendMessage: async (jid, content, options = {}) => {
937
+ var _a, _b, _c;
938
+ const userJid = authState.creds.me.id;
939
+ const additionalAttributes = {};
940
+ if (!options.ephemeralExpiration) {
941
+ if ((0, WABinary_1.isJidGroup)(jid)) {
942
+ const groups = await sock.groupQuery(jid, 'get', [{
943
+ tag: 'query',
944
+ attrs: {
945
+ request: 'interactive'
946
+ }
947
+ }]);
948
+ const metadata = (0, WABinary_1.getBinaryNodeChild)(groups, 'group');
949
+ 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;
950
+ options.ephemeralExpiration = expiration;
951
+ }
952
+ }
953
+ if (typeof content === 'object' &&
954
+ 'disappearingMessagesInChat' in content &&
955
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
956
+ (0, WABinary_1.isJidGroup)(jid)) {
957
+ const { disappearingMessagesInChat } = content;
958
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
959
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
960
+ disappearingMessagesInChat;
961
+ await groupToggleEphemeral(jid, value);
962
+ }
963
+ else if (typeof content === 'object' && 'album' in content && content.album) {
964
+ const albumMsg = await Utils_1.prepareAlbumMessageContent(jid, content.album, {
965
+ sock: {
966
+ relayMessage,
967
+ waUploadToServer
968
+ },
969
+ userJid: userJid,
970
+ quoted: options.quoted,
971
+ ephemeralExpiration: options.ephemeralExpiration,
972
+ ...options
973
+ });
974
+ return albumMsg;
975
+ }
976
+ else {
977
+ let mediaHandle;
978
+ const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
979
+ logger,
980
+ userJid,
981
+ getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
982
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
983
+ fetchOpts: {
984
+ timeout: 3000,
985
+ ...axiosOptions || {}
986
+ },
987
+ logger,
988
+ uploadImage: generateHighQualityLinkPreview
989
+ ? waUploadToServer
990
+ : undefined
991
+ }),
992
+ getProfilePicUrl: sock.profilePictureUrl,
993
+ getCallLink: sock.createCallLink,
994
+ upload: async (readStream, opts) => {
995
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
996
+ mediaHandle = up.handle;
997
+ return up;
998
+ },
999
+ mediaCache: config.mediaCache,
1000
+ options: config.options,
1001
+ messageId: (0, Utils_1.generateMessageIDV2)((_c = sock.user) === null || _c === void 0 ? void 0 : _c.id),
1002
+ ...options,
1003
+ });
1004
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1005
+ const isEditMsg = 'edit' in content && !!content.edit;
1006
+ const isPinMsg = 'pin' in content && !!content.pin;
1007
+ const isKeepMsg = 'keep' in content && content.keep;
1008
+ const isPollMessage = 'poll' in content && !!content.poll;
1009
+ const isAiMsg = 'ai' in content && !!content.ai;
1010
+ const additionalNodes = [];
1011
+ // required for delete
1012
+ if (isDeleteMsg) {
1013
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1014
+ if (((0, WABinary_1.isJidGroup)(content.delete.remoteJid) && !content.delete.fromMe) || (0, WABinary_1.isJidNewsletter)(jid)) {
1015
+ additionalAttributes.edit = '8';
1016
+ }
1017
+ else {
1018
+ additionalAttributes.edit = '7';
1019
+ }
1020
+ // required for edit message
1021
+ }
1022
+ else if (isEditMsg) {
1023
+ additionalAttributes.edit = (0, WABinary_1.isJidNewsletter)(jid) ? '3' : '1';
1024
+ // required for pin message
1025
+ }
1026
+ else if (isPinMsg) {
1027
+ additionalAttributes.edit = '2';
1028
+ // required for keep message
1029
+ }
1030
+ else if (isKeepMsg) {
1031
+ additionalAttributes.edit = '6';
1032
+ // required for polling message
1033
+ }
1034
+ else if (isPollMessage) {
1035
+ additionalNodes.push({
1036
+ tag: 'meta',
1037
+ attrs: {
1038
+ polltype: 'creation'
1039
+ },
1040
+ });
1041
+ // required to display AI icon on message
1042
+ }
1043
+ else if (isAiMsg) {
1044
+ additionalNodes.push({
1045
+ attrs: {
1046
+ biz_bot: '1'
1047
+ },
1048
+ tag: "bot"
1049
+ });
1050
+ }
1051
+ if (mediaHandle) {
1052
+ additionalAttributes['media_id'] = mediaHandle;
1053
+ }
1054
+ if ('cachedGroupMetadata' in options) {
1055
+ console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
1056
+ }
1057
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, statusJidList: options.statusJidList });
1058
+ if (config.emitOwnEvents) {
1059
+ process.nextTick(() => {
1060
+ processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
1061
+ });
1062
+ }
1063
+ return fullMsg;
1064
+ }
1065
+ }
1066
+ };
1067
+ };
1068
+ exports.makeMessagesSocket = makeMessagesSocket;