@elfhkry/baileys 8.0.11

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 (107) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +290 -0
  3. package/WAProto/WAProto.proto +5311 -0
  4. package/WAProto/index.js +94091 -0
  5. package/lib/Defaults/index.js +123 -0
  6. package/lib/KeyDB/BinarySearch.js +20 -0
  7. package/lib/KeyDB/KeyedDB.js +167 -0
  8. package/lib/KeyDB/index.js +4 -0
  9. package/lib/Signal/Group/ciphertext-message.js +13 -0
  10. package/lib/Signal/Group/group-session-builder.js +32 -0
  11. package/lib/Signal/Group/group_cipher.js +84 -0
  12. package/lib/Signal/Group/index.js +13 -0
  13. package/lib/Signal/Group/keyhelper.js +20 -0
  14. package/lib/Signal/Group/sender-chain-key.js +28 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +65 -0
  16. package/lib/Signal/Group/sender-key-message.js +68 -0
  17. package/lib/Signal/Group/sender-key-name.js +52 -0
  18. package/lib/Signal/Group/sender-key-record.js +43 -0
  19. package/lib/Signal/Group/sender-key-state.js +86 -0
  20. package/lib/Signal/Group/sender-message-key.js +28 -0
  21. package/lib/Signal/libsignal.js +324 -0
  22. package/lib/Signal/lid-mapping.js +155 -0
  23. package/lib/Socket/Client/index.js +4 -0
  24. package/lib/Socket/Client/types.js +13 -0
  25. package/lib/Socket/Client/websocket.js +52 -0
  26. package/lib/Socket/Client/websocket.js.bak +53 -0
  27. package/lib/Socket/business.js +377 -0
  28. package/lib/Socket/chats.js +922 -0
  29. package/lib/Socket/communities.js +413 -0
  30. package/lib/Socket/dugong.js +768 -0
  31. package/lib/Socket/groups.js +312 -0
  32. package/lib/Socket/index.js +16 -0
  33. package/lib/Socket/messages-recv.js +1163 -0
  34. package/lib/Socket/messages-send.js +1179 -0
  35. package/lib/Socket/mex.js +45 -0
  36. package/lib/Socket/newsletter.js +247 -0
  37. package/lib/Socket/socket.js +888 -0
  38. package/lib/Store/index.js +6 -0
  39. package/lib/Store/make-cache-manager-store.js +75 -0
  40. package/lib/Store/make-in-memory-store.js +290 -0
  41. package/lib/Store/make-ordered-dictionary.js +79 -0
  42. package/lib/Store/object-repository.js +25 -0
  43. package/lib/Types/Auth.js +3 -0
  44. package/lib/Types/Bussines.js +3 -0
  45. package/lib/Types/Call.js +3 -0
  46. package/lib/Types/Chat.js +9 -0
  47. package/lib/Types/Contact.js +3 -0
  48. package/lib/Types/Events.js +3 -0
  49. package/lib/Types/GroupMetadata.js +3 -0
  50. package/lib/Types/Label.js +25 -0
  51. package/lib/Types/LabelAssociation.js +7 -0
  52. package/lib/Types/Message.js +12 -0
  53. package/lib/Types/Newsletter.js +33 -0
  54. package/lib/Types/Newsletter.js.bak +33 -0
  55. package/lib/Types/Product.js +3 -0
  56. package/lib/Types/Signal.js +3 -0
  57. package/lib/Types/Socket.js +4 -0
  58. package/lib/Types/State.js +11 -0
  59. package/lib/Types/USync.js +3 -0
  60. package/lib/Types/index.js +28 -0
  61. package/lib/Utils/auth-utils.js +219 -0
  62. package/lib/Utils/baileys-event-stream.js +44 -0
  63. package/lib/Utils/browser-utils.js +25 -0
  64. package/lib/Utils/business.js +233 -0
  65. package/lib/Utils/chat-utils.js +752 -0
  66. package/lib/Utils/crypto.js +130 -0
  67. package/lib/Utils/decode-wa-message.js +267 -0
  68. package/lib/Utils/event-buffer.js +528 -0
  69. package/lib/Utils/generics.js +355 -0
  70. package/lib/Utils/history.js +87 -0
  71. package/lib/Utils/index.js +21 -0
  72. package/lib/Utils/link-preview.js +81 -0
  73. package/lib/Utils/logger.js +5 -0
  74. package/lib/Utils/lt-hash.js +45 -0
  75. package/lib/Utils/make-mutex.js +36 -0
  76. package/lib/Utils/message-retry-manager.js +113 -0
  77. package/lib/Utils/messages-media.js +644 -0
  78. package/lib/Utils/messages.js +909 -0
  79. package/lib/Utils/noise-handler.js +144 -0
  80. package/lib/Utils/pre-key-manager.js +85 -0
  81. package/lib/Utils/process-message.js +341 -0
  82. package/lib/Utils/signal.js +161 -0
  83. package/lib/Utils/use-multi-file-auth-state.js +111 -0
  84. package/lib/Utils/validate-connection.js +200 -0
  85. package/lib/WABinary/constants.js +1303 -0
  86. package/lib/WABinary/decode.js +240 -0
  87. package/lib/WABinary/encode.js +218 -0
  88. package/lib/WABinary/generic-utils.js +189 -0
  89. package/lib/WABinary/index.js +7 -0
  90. package/lib/WABinary/jid-utils.js +93 -0
  91. package/lib/WABinary/types.js +3 -0
  92. package/lib/WAM/BinaryInfo.js +11 -0
  93. package/lib/WAM/constants.js +22853 -0
  94. package/lib/WAM/encode.js +154 -0
  95. package/lib/WAM/index.js +5 -0
  96. package/lib/WAUSync/Protocols/USyncContactProtocol.js +30 -0
  97. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  98. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -0
  99. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  100. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  101. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +30 -0
  102. package/lib/WAUSync/Protocols/index.js +6 -0
  103. package/lib/WAUSync/USyncQuery.js +90 -0
  104. package/lib/WAUSync/USyncUser.js +24 -0
  105. package/lib/WAUSync/index.js +5 -0
  106. package/lib/index.js +21 -0
  107. package/package.json +103 -0
@@ -0,0 +1,1179 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { Dugong } from "./dugong.js";
5
+ import {
6
+ DEFAULT_CACHE_TTLS,
7
+ WA_DEFAULT_EPHEMERAL
8
+ } from '../Defaults/index.js';
9
+ import {
10
+ aggregateMessageKeysNotFromMe,
11
+ assertMediaContent,
12
+ bindWaitForEvent,
13
+ decryptMediaRetryData,
14
+ encodeNewsletterMessage,
15
+ encodeSignedDeviceIdentity,
16
+ encodeWAMessage,
17
+ encryptMediaRetryRequest,
18
+ extractDeviceJids,
19
+ generateMessageIDV2,
20
+ generateParticipantHashV2,
21
+ generateWAMessage,
22
+ getStatusCodeForMediaRetry,
23
+ getUrlFromDirectPath,
24
+ getWAUploadToServer,
25
+ MessageRetryManager,
26
+ normalizeMessageContent,
27
+ parseAndInjectE2ESessions,
28
+ unixTimestampSeconds
29
+ } from '../Utils/index.js';
30
+ import {
31
+ areJidsSameUser,
32
+ getBinaryNodeChild,
33
+ getBinaryNodeChildren,
34
+ getAdditionalNode,
35
+ getBinaryNodeFilter,
36
+ isHostedLidUser,
37
+ isHostedPnUser,
38
+ isJidGroup,
39
+ isLidUser,
40
+ isPnUser,
41
+ jidDecode,
42
+ jidEncode,
43
+ isJidNewsletter,
44
+ jidNormalizedUser,
45
+ S_WHATSAPP_NET
46
+ } from '../WABinary/index.js';
47
+ import { getUrlInfo } from '../Utils/link-preview.js';
48
+ import { makeKeyedMutex } from '../Utils/make-mutex.js';
49
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
50
+ import { makeNewsletterSocket } from './newsletter.js';
51
+ export const makeMessagesSocket = (config) => {
52
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
53
+ const sock = makeNewsletterSocket(config);
54
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
55
+ const userDevicesCache = config.userDevicesCache ||
56
+ new NodeCache({
57
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
58
+ useClones: false
59
+ });
60
+ const peerSessionsCache = new NodeCache({
61
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
62
+ useClones: false
63
+ });
64
+ // Initialize message retry manager if enabled
65
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
66
+ // Prevent race conditions in Signal session encryption by user
67
+ const encryptionMutex = makeKeyedMutex();
68
+ let mediaConn;
69
+ const refreshMediaConn = async (forceGet = false) => {
70
+ const media = await mediaConn;
71
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
72
+ mediaConn = (async () => {
73
+ const result = await query({
74
+ tag: 'iq',
75
+ attrs: {
76
+ type: 'set',
77
+ xmlns: 'w:m',
78
+ to: S_WHATSAPP_NET
79
+ },
80
+ content: [{ tag: 'media_conn', attrs: {} }]
81
+ });
82
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
83
+ // TODO: explore full length of data that whatsapp provides
84
+ const node = {
85
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
86
+ hostname: attrs.hostname,
87
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
88
+ })),
89
+ auth: mediaConnNode.attrs.auth,
90
+ ttl: +mediaConnNode.attrs.ttl,
91
+ fetchDate: new Date()
92
+ };
93
+ logger.debug('fetched media conn');
94
+ return node;
95
+ })();
96
+ }
97
+ return mediaConn;
98
+ };
99
+ /**
100
+ * generic send receipt function
101
+ * used for receipts of phone call, read, delivery etc.
102
+ * */
103
+ const sendReceipt = async (jid, participant, messageIds, type) => {
104
+ if (!messageIds || messageIds.length === 0) {
105
+ throw new Boom('missing ids in receipt');
106
+ }
107
+ const node = {
108
+ tag: 'receipt',
109
+ attrs: {
110
+ id: messageIds[0]
111
+ }
112
+ };
113
+ const isReadReceipt = type === 'read' || type === 'read-self';
114
+ if (isReadReceipt) {
115
+ node.attrs.t = unixTimestampSeconds().toString();
116
+ }
117
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
118
+ node.attrs.recipient = jid;
119
+ node.attrs.to = participant;
120
+ }
121
+ else {
122
+ node.attrs.to = jid;
123
+ if (participant) {
124
+ node.attrs.participant = participant;
125
+ }
126
+ }
127
+ if (type) {
128
+ node.attrs.type = type;
129
+ }
130
+ const remainingMessageIds = messageIds.slice(1);
131
+ if (remainingMessageIds.length) {
132
+ node.content = [
133
+ {
134
+ tag: 'list',
135
+ attrs: {},
136
+ content: remainingMessageIds.map(id => ({
137
+ tag: 'item',
138
+ attrs: { id }
139
+ }))
140
+ }
141
+ ];
142
+ }
143
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
144
+ await sendNode(node);
145
+ };
146
+ /** Correctly bulk send receipts to multiple chats, participants */
147
+ const sendReceipts = async (keys, type) => {
148
+ const recps = aggregateMessageKeysNotFromMe(keys);
149
+ for (const { jid, participant, messageIds } of recps) {
150
+ await sendReceipt(jid, participant, messageIds, type);
151
+ }
152
+ };
153
+ /** Bulk read messages. Keys can be from different chats & participants */
154
+ const readMessages = async (keys) => {
155
+ const privacySettings = await fetchPrivacySettings();
156
+ // based on privacy settings, we have to change the read type
157
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
158
+ await sendReceipts(keys, readType);
159
+ };
160
+ /** Fetch all the devices we've to send a message to */
161
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
162
+ const deviceResults = [];
163
+ if (!useCache) {
164
+ logger.debug('not using cache for devices');
165
+ }
166
+ const toFetch = [];
167
+ const jidsWithUser = jids
168
+ .map(jid => {
169
+ const decoded = jidDecode(jid);
170
+ const user = decoded?.user;
171
+ const device = decoded?.device;
172
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
173
+ if (isExplicitDevice && user) {
174
+ deviceResults.push({
175
+ user,
176
+ device,
177
+ jid
178
+ });
179
+ return null;
180
+ }
181
+ jid = jidNormalizedUser(jid);
182
+ return { jid, user };
183
+ })
184
+ .filter(jid => jid !== null);
185
+ let mgetDevices;
186
+ if (useCache && userDevicesCache.mget) {
187
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
188
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
189
+ }
190
+ for (const { jid, user } of jidsWithUser) {
191
+ if (useCache) {
192
+ const devices = mgetDevices?.[user] ||
193
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
194
+ if (devices) {
195
+ const devicesWithJid = devices.map(d => ({
196
+ ...d,
197
+ jid: jidEncode(d.user, d.server, d.device)
198
+ }));
199
+ deviceResults.push(...devicesWithJid);
200
+ logger.trace({ user }, 'using cache for devices');
201
+ }
202
+ else {
203
+ toFetch.push(jid);
204
+ }
205
+ }
206
+ else {
207
+ toFetch.push(jid);
208
+ }
209
+ }
210
+ if (!toFetch.length) {
211
+ return deviceResults;
212
+ }
213
+ const requestedLidUsers = new Set();
214
+ for (const jid of toFetch) {
215
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
216
+ const user = jidDecode(jid)?.user;
217
+ if (user)
218
+ requestedLidUsers.add(user);
219
+ }
220
+ }
221
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
222
+ for (const jid of toFetch) {
223
+ query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
224
+ }
225
+ const result = await sock.executeUSyncQuery(query);
226
+ if (result) {
227
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
228
+ const lidResults = result.list.filter(a => !!a.lid);
229
+ if (lidResults.length > 0) {
230
+ logger.trace('Storing LID maps from device call');
231
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
232
+ }
233
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
234
+ const deviceMap = {};
235
+ for (const item of extracted) {
236
+ deviceMap[item.user] = deviceMap[item.user] || [];
237
+ deviceMap[item.user]?.push(item);
238
+ }
239
+ // Process each user's devices as a group for bulk LID migration
240
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
241
+ const isLidUser = requestedLidUsers.has(user);
242
+ // Process all devices for this user
243
+ for (const item of userDevices) {
244
+ const finalJid = isLidUser
245
+ ? jidEncode(user, item.server, item.device)
246
+ : jidEncode(item.user, item.server, item.device);
247
+ deviceResults.push({
248
+ ...item,
249
+ jid: finalJid
250
+ });
251
+ logger.debug({
252
+ user: item.user,
253
+ device: item.device,
254
+ finalJid,
255
+ usedLid: isLidUser
256
+ }, 'Processed device with LID priority');
257
+ }
258
+ }
259
+ if (userDevicesCache.mset) {
260
+ // if the cache supports mset, we can set all devices in one go
261
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
262
+ }
263
+ else {
264
+ for (const key in deviceMap) {
265
+ if (deviceMap[key])
266
+ await userDevicesCache.set(key, deviceMap[key]);
267
+ }
268
+ }
269
+ const userDeviceUpdates = {};
270
+ for (const [userId, devices] of Object.entries(deviceMap)) {
271
+ if (devices && devices.length > 0) {
272
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
273
+ }
274
+ }
275
+ if (Object.keys(userDeviceUpdates).length > 0) {
276
+ try {
277
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
278
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
279
+ }
280
+ catch (error) {
281
+ logger.warn({ error }, 'failed to store user device lists');
282
+ }
283
+ }
284
+ }
285
+ return deviceResults;
286
+ };
287
+ const assertSessions = async (jids) => {
288
+ let didFetchNewSession = false;
289
+ const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
290
+ const jidsRequiringFetch = [];
291
+ logger.debug({ jids }, 'assertSessions call with jids');
292
+ // Check peerSessionsCache and validate sessions using libsignal loadSession
293
+ for (const jid of uniqueJids) {
294
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid);
295
+ const cachedSession = peerSessionsCache.get(signalId);
296
+ if (cachedSession !== undefined) {
297
+ if (cachedSession) {
298
+ continue; // Session exists in cache
299
+ }
300
+ }
301
+ else {
302
+ const sessionValidation = await signalRepository.validateSession(jid);
303
+ const hasSession = sessionValidation.exists;
304
+ peerSessionsCache.set(signalId, hasSession);
305
+ if (hasSession) {
306
+ continue;
307
+ }
308
+ }
309
+ jidsRequiringFetch.push(jid);
310
+ }
311
+ if (jidsRequiringFetch.length) {
312
+ // LID if mapped, otherwise original
313
+ const wireJids = [
314
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
315
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
316
+ ];
317
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
318
+ const result = await query({
319
+ tag: 'iq',
320
+ attrs: {
321
+ xmlns: 'encrypt',
322
+ type: 'get',
323
+ to: S_WHATSAPP_NET
324
+ },
325
+ content: [
326
+ {
327
+ tag: 'key',
328
+ attrs: {},
329
+ content: wireJids.map(jid => ({
330
+ tag: 'user',
331
+ attrs: { jid }
332
+ }))
333
+ }
334
+ ]
335
+ });
336
+ await parseAndInjectE2ESessions(result, signalRepository);
337
+ didFetchNewSession = true;
338
+ // Cache fetched sessions using wire JIDs
339
+ for (const wireJid of wireJids) {
340
+ const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
341
+ peerSessionsCache.set(signalId, true);
342
+ }
343
+ }
344
+ return didFetchNewSession;
345
+ };
346
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
347
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
348
+ if (!authState.creds.me?.id) {
349
+ throw new Boom('Not authenticated');
350
+ }
351
+ const protocolMessage = {
352
+ protocolMessage: {
353
+ peerDataOperationRequestMessage: pdoMessage,
354
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
355
+ }
356
+ };
357
+ const meJid = jidNormalizedUser(authState.creds.me.id);
358
+ const msgId = await relayMessage(meJid, protocolMessage, {
359
+ additionalAttributes: {
360
+ category: 'peer',
361
+ push_priority: 'high_force'
362
+ },
363
+ additionalNodes: [
364
+ {
365
+ tag: 'meta',
366
+ attrs: { appdata: 'default' }
367
+ }
368
+ ]
369
+ });
370
+ return msgId;
371
+ };
372
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
373
+ if (!recipientJids.length) {
374
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
375
+ }
376
+ const patched = await patchMessageBeforeSending(message, recipientJids);
377
+ const patchedMessages = Array.isArray(patched)
378
+ ? patched
379
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
380
+ let shouldIncludeDeviceIdentity = false;
381
+ const meId = authState.creds.me.id;
382
+ const meLid = authState.creds.me?.lid;
383
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
384
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
385
+ if (!jid)
386
+ return null;
387
+ let msgToEncrypt = patchedMessage;
388
+ if (dsmMessage) {
389
+ const { user: targetUser } = jidDecode(jid);
390
+ const { user: ownPnUser } = jidDecode(meId);
391
+ const ownLidUser = meLidUser;
392
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
393
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
394
+ if (isOwnUser && !isExactSenderDevice) {
395
+ msgToEncrypt = dsmMessage;
396
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
397
+ }
398
+ }
399
+ const bytes = encodeWAMessage(msgToEncrypt);
400
+ const mutexKey = jid;
401
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
402
+ const { type, ciphertext } = await signalRepository.encryptMessage({
403
+ jid,
404
+ data: bytes
405
+ });
406
+ if (type === 'pkmsg') {
407
+ shouldIncludeDeviceIdentity = true;
408
+ }
409
+ return {
410
+ tag: 'to',
411
+ attrs: { jid },
412
+ content: [
413
+ {
414
+ tag: 'enc',
415
+ attrs: {
416
+ v: '2',
417
+ type,
418
+ ...(extraAttrs || {})
419
+ },
420
+ content: ciphertext
421
+ }
422
+ ]
423
+ };
424
+ });
425
+ return node;
426
+ });
427
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
428
+ return { nodes, shouldIncludeDeviceIdentity };
429
+ };
430
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, AI = false }) => {
431
+ // let shouldIncludeDeviceIdentity = false;
432
+ let didPushAdditional = false
433
+ const meId = authState.creds.me.id;
434
+ const meLid = authState.creds.me?.lid;
435
+ const isRetryResend = Boolean(participant?.jid);
436
+ let shouldIncludeDeviceIdentity = isRetryResend;
437
+ const statusJid = 'status@broadcast';
438
+ const { user, server } = jidDecode(jid);
439
+ const isGroup = server === 'g.us';
440
+ const isStatus = jid === statusJid;
441
+ const isLid = server === 'lid';
442
+ const isNewsletter = server === 'newsletter';
443
+ const isPrivate = server === 's.whatsapp.net'
444
+ const finalJid = jid;
445
+ msgId = msgId || generateMessageIDV2(meId);
446
+ useUserDevicesCache = useUserDevicesCache !== false;
447
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
448
+ const participants = [];
449
+ const destinationJid = !isStatus ? finalJid : statusJid;
450
+ const binaryNodeContent = [];
451
+ const devices = [];
452
+ const meMsg = {
453
+ deviceSentMessage: {
454
+ destinationJid,
455
+ message
456
+ },
457
+ messageContextInfo: message.messageContextInfo
458
+ };
459
+ const extraAttrs = {};
460
+ const messages = normalizeMessageContent(message)
461
+ const buttonType = getButtonType(messages);
462
+ if (participant) {
463
+ if (!isGroup && !isStatus) {
464
+ additionalAttributes = {
465
+ ...additionalAttributes,
466
+ device_fanout: 'false'
467
+ };
468
+ }
469
+ const { user, device } = jidDecode(participant.jid);
470
+ devices.push({
471
+ user,
472
+ device,
473
+ jid: participant.jid
474
+ });
475
+ }
476
+ await authState.keys.transaction(async () => {
477
+ const mediaType = getMediaType(message);
478
+ if (mediaType) {
479
+ extraAttrs['mediatype'] = mediaType;
480
+ }
481
+
482
+ if (isNewsletter) {
483
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
484
+ const bytes = encodeNewsletterMessage(patched);
485
+ binaryNodeContent.push({
486
+ tag: "plaintext",
487
+ attrs: mediaType ? { mediatype: mediaType } : {},
488
+ content: bytes
489
+ });
490
+ const stanza = {
491
+ tag: "message",
492
+ attrs: {
493
+ to: jid,
494
+ id: msgId,
495
+ type: getTypeMessage(message),
496
+ ...(additionalAttributes || {})
497
+ },
498
+ content: binaryNodeContent
499
+ };
500
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
501
+ await sendNode(stanza);
502
+ return;
503
+ }
504
+
505
+ if (messages.pinInChatMessage || messages.keepInChatMessage || message.reactionMessage || message.protocolMessage?.editedMessage) {
506
+ extraAttrs['decrypt-fail'] = 'hide'
507
+ }
508
+
509
+ if (messages.interactiveResponseMessage?.nativeFlowResponseMessage) {
510
+ extraAttrs['native_flow_name'] = messages.interactiveResponseMessage?.nativeFlowResponseMessage.name
511
+ }
512
+
513
+ if (isGroup || isStatus) {
514
+ const [groupData, senderKeyMap] = await Promise.all([
515
+ (async () => {
516
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
517
+ if (groupData && Array.isArray(groupData?.participants)) {
518
+ logger.trace({
519
+ jid,
520
+ participants: groupData.participants.length
521
+ }, 'using cached group metadata');
522
+ }
523
+ else if (!isStatus) {
524
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
525
+ }
526
+ return groupData;
527
+ })(),
528
+ (async () => {
529
+ if (!participant && !isStatus) {
530
+ // what if sender memory is less accurate than the cached metadata
531
+ // on participant change in group, we should do sender memory manipulation
532
+ const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
533
+ return result[jid] || {};
534
+ }
535
+ return {};
536
+ })()
537
+ ]);
538
+ if (!participant) {
539
+ const participantsList = groupData && !isStatus ? groupData.participants.map(p => p.id) : [];
540
+ if (isStatus && statusJidList) {
541
+ participantsList.push(...statusJidList);
542
+ }
543
+ // if (!isStatus) {
544
+ // additionalAttributes = {
545
+ // ...additionalAttributes,
546
+ // addressing_mode: groupData?.addressingMode || 'pn'
547
+ // };
548
+ // }
549
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
550
+ devices.push(...additionalDevices);
551
+ }
552
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
553
+ additionalAttributes = {
554
+ ...additionalAttributes,
555
+ expiration: groupData.ephemeralDuration.toString()
556
+ };
557
+ }
558
+ const patched = await patchMessageBeforeSending(message);
559
+ if (Array.isArray(patched)) {
560
+ throw new Boom('Per-jid patching is not supported in groups');
561
+ }
562
+ const bytes = encodeWAMessage(patched);
563
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
564
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
565
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
566
+ group: destinationJid,
567
+ data: bytes,
568
+ meId: groupSenderIdentity
569
+ });
570
+ const senderKeyRecipients = [];
571
+ for (const device of devices) {
572
+ const deviceJid = device.jid;
573
+ const hasKey = !!senderKeyMap[deviceJid];
574
+ if ((!hasKey || !!participant) &&
575
+ !isHostedLidUser(deviceJid) &&
576
+ !isHostedPnUser(deviceJid) &&
577
+ device.device !== 99) {
578
+ //todo: revamp all this logic
579
+ // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
580
+ senderKeyRecipients.push(deviceJid);
581
+ senderKeyMap[deviceJid] = true;
582
+ }
583
+ }
584
+ if (senderKeyRecipients.length) {
585
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
586
+ const senderKeyMsg = {
587
+ senderKeyDistributionMessage: {
588
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
589
+ groupId: destinationJid
590
+ }
591
+ };
592
+ const senderKeySessionTargets = senderKeyRecipients;
593
+ await assertSessions(senderKeySessionTargets);
594
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
595
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
596
+ participants.push(...result.nodes);
597
+ }
598
+ if (isRetryResend) {
599
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
600
+ data: bytes,
601
+ jid: participant?.jid
602
+ });
603
+ binaryNodeContent.push({
604
+ tag: 'enc',
605
+ attrs: {
606
+ v: '2',
607
+ type,
608
+ count: participant.count.toString()
609
+ },
610
+ content: encryptedContent
611
+ });
612
+ }
613
+ else {
614
+ binaryNodeContent.push({
615
+ tag: 'enc',
616
+ attrs: {
617
+ v: '2',
618
+ type: 'skmsg',
619
+ ...extraAttrs
620
+ },
621
+ content: ciphertext
622
+ });
623
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
624
+ }
625
+ }
626
+ else {
627
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
628
+ // TODO: investigate if this is true
629
+ let ownId = meId;
630
+ if (isLid && meLid) {
631
+ ownId = meLid;
632
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
633
+ }
634
+ else {
635
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
636
+ }
637
+ const { user: ownUser } = jidDecode(ownId);
638
+ if (!participant) {
639
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
640
+ devices.push({
641
+ user,
642
+ device: 0,
643
+ jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
644
+ });
645
+ if (user !== ownUser) {
646
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
647
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
648
+ devices.push({
649
+ user: ownUserForAddressing,
650
+ device: 0,
651
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
652
+ });
653
+ }
654
+ if (additionalAttributes?.['category'] !== 'peer') {
655
+ // Clear placeholders and enumerate actual devices
656
+ devices.length = 0;
657
+ // Use conversation-appropriate sender identity
658
+ const senderIdentity = isLid && meLid
659
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
660
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
661
+ // Enumerate devices for sender and target with consistent addressing
662
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
663
+ devices.push(...sessionDevices);
664
+ logger.debug({
665
+ deviceCount: devices.length,
666
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
667
+ }, 'Device enumeration complete with unified addressing');
668
+ }
669
+ }
670
+ const allRecipients = [];
671
+ const meRecipients = [];
672
+ const otherRecipients = [];
673
+ const { user: mePnUser } = jidDecode(meId);
674
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
675
+ for (const { user, jid } of devices) {
676
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
677
+ if (isExactSenderDevice) {
678
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
679
+ continue;
680
+ }
681
+ // Check if this is our device (could match either PN or LID user)
682
+ const isMe = user === mePnUser || user === meLidUser;
683
+ if (isMe) {
684
+ meRecipients.push(jid);
685
+ }
686
+ else {
687
+ otherRecipients.push(jid);
688
+ }
689
+ allRecipients.push(jid);
690
+ }
691
+ await assertSessions(allRecipients);
692
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
693
+ // For own devices: use DSM if available (1:1 chats only)
694
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
695
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
696
+ ]);
697
+ participants.push(...meNodes);
698
+ participants.push(...otherNodes);
699
+ /* if (meRecipients.length > 0 || otherRecipients.length > 0) {
700
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
701
+ }*/
702
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
703
+ }
704
+ if (participants.length) {
705
+ if (additionalAttributes?.['category'] === 'peer') {
706
+ const peerNode = participants[0]?.content?.[0];
707
+ if (peerNode) {
708
+ binaryNodeContent.push(peerNode); // push only enc
709
+ }
710
+ }
711
+ else {
712
+ binaryNodeContent.push({
713
+ tag: 'participants',
714
+ attrs: {},
715
+ content: participants
716
+ });
717
+ }
718
+ }
719
+ const stanza = {
720
+ tag: 'message',
721
+ attrs: {
722
+ id: msgId,
723
+ to: destinationJid,
724
+ type: getTypeMessage(messages),
725
+ ...(additionalAttributes || {})
726
+ },
727
+ content: binaryNodeContent
728
+ };
729
+ // if the participant to send to is explicitly specified (generally retry recp)
730
+ // ensure the message is only sent to that person
731
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
732
+ if (participant) {
733
+ if (isJidGroup(destinationJid)) {
734
+ stanza.attrs.to = destinationJid;
735
+ stanza.attrs.participant = participant.jid;
736
+ }
737
+ else if (areJidsSameUser(participant.jid, meId)) {
738
+ stanza.attrs.to = participant.jid;
739
+ stanza.attrs.recipient = destinationJid;
740
+ }
741
+ else {
742
+ stanza.attrs.to = participant.jid;
743
+ }
744
+ }
745
+ else {
746
+ stanza.attrs.to = destinationJid;
747
+ }
748
+ if (shouldIncludeDeviceIdentity) {
749
+ ;
750
+ stanza.content.push({
751
+ tag: 'device-identity',
752
+ attrs: {},
753
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
754
+ });
755
+ logger.debug({ jid }, 'adding device identity');
756
+ }
757
+ if (AI && isPrivate) {
758
+ const botNode = {
759
+ tag: 'bot',
760
+ attrs: {
761
+ biz_bot: '1'
762
+ }
763
+ }
764
+
765
+ const filteredBizBot = getBinaryNodeFilter(additionalNodes ? additionalNodes : [])
766
+
767
+ if (filteredBizBot) {
768
+ stanza.content.push(...additionalNodes)
769
+ didPushAdditional = true
770
+ }
771
+
772
+ else {
773
+ stanza.content.push(botNode)
774
+ }
775
+ }
776
+
777
+ if(buttonType && !isStatus) {
778
+ const content = getAdditionalNode(buttonType)
779
+ const filteredNode = getBinaryNodeFilter(additionalNodes)
780
+
781
+ if (filteredNode) {
782
+ didPushAdditional = true
783
+ stanza.content.push(...additionalNodes)
784
+ }
785
+ else {
786
+ stanza.content.push(...content)
787
+ }
788
+ logger.debug({ jid }, 'adding business node')
789
+ }
790
+
791
+ if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
792
+ stanza.content.push(...additionalNodes);
793
+ }
794
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
795
+ await sendNode(stanza);
796
+ // Add message to retry cache if enabled
797
+ if (messageRetryManager && !participant) {
798
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
799
+ }
800
+ }, meId);
801
+ return msgId;
802
+ };
803
+ const getTypeMessage = (msg) => {
804
+ if (msg.viewOnceMessage) {
805
+ return getTypeMessage(msg.viewOnceMessage.message);
806
+ }
807
+ else if (msg.viewOnceMessageV2) {
808
+ return getTypeMessage(msg.viewOnceMessageV2.message);
809
+ }
810
+ else if (msg.viewOnceMessageV2Extension) {
811
+ return getTypeMessage(msg.viewOnceMessageV2Extension.message);
812
+ }
813
+ else if (msg.ephemeralMessage) {
814
+ return getTypeMessage(msg.ephemeralMessage.message);
815
+ }
816
+ else if (msg.documentWithCaptionMessage) {
817
+ return getTypeMessage(msg.documentWithCaptionMessage.message);
818
+ }
819
+ else if (msg.reactionMessage) {
820
+ return 'reaction';
821
+ }
822
+ else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
823
+ return 'poll';
824
+ }
825
+ else if (getMediaType(msg)) {
826
+ return 'media';
827
+ }
828
+ else {
829
+ return 'text';
830
+ }
831
+ };
832
+ const getMediaType = (message) => {
833
+ if (message.imageMessage) {
834
+ return 'image'
835
+ }
836
+ else if (message.videoMessage) {
837
+ return message.videoMessage.gifPlayback ? 'gif' : 'video'
838
+ }
839
+ else if (message.audioMessage) {
840
+ return message.audioMessage.ptt ? 'ptt' : 'audio'
841
+ }
842
+ else if (message.contactMessage) {
843
+ return 'vcard'
844
+ }
845
+ else if (message.documentMessage) {
846
+ return 'document'
847
+ }
848
+ else if (message.contactsArrayMessage) {
849
+ return 'contact_array'
850
+ }
851
+ else if (message.liveLocationMessage) {
852
+ return 'livelocation'
853
+ }
854
+ else if (message.stickerMessage) {
855
+ return 'sticker'
856
+ }
857
+ else if (message.listMessage) {
858
+ return 'list'
859
+ }
860
+ else if (message.listResponseMessage) {
861
+ return 'list_response'
862
+ }
863
+ else if (message.buttonsResponseMessage) {
864
+ return 'buttons_response'
865
+ }
866
+ else if (message.orderMessage) {
867
+ return 'order'
868
+ }
869
+ else if (message.productMessage) {
870
+ return 'product'
871
+ }
872
+ else if (message.interactiveResponseMessage) {
873
+ return 'native_flow_response'
874
+ }
875
+ else if (message.groupInviteMessage) {
876
+ return 'url'
877
+ }
878
+ else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
879
+ return 'productlink'
880
+ }
881
+ }
882
+ const getButtonType = (message) => {
883
+ if (message.listMessage) {
884
+ return 'list'
885
+ }
886
+ else if (message.buttonsMessage) {
887
+ return 'buttons'
888
+ }
889
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
890
+ return 'review_and_pay'
891
+ }
892
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
893
+ return 'review_order'
894
+ }
895
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
896
+ return 'payment_info'
897
+ }
898
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
899
+ return 'payment_status'
900
+ }
901
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
902
+ return 'payment_method'
903
+ }
904
+ else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
905
+ return 'interactive'
906
+ }
907
+ else if (message.interactiveMessage?.nativeFlowMessage) {
908
+ return 'native_flow'
909
+ }
910
+ }
911
+ const getPrivacyTokens = async (jids) => {
912
+ const t = unixTimestampSeconds().toString();
913
+ const result = await query({
914
+ tag: 'iq',
915
+ attrs: {
916
+ to: S_WHATSAPP_NET,
917
+ type: 'set',
918
+ xmlns: 'privacy'
919
+ },
920
+ content: [
921
+ {
922
+ tag: 'tokens',
923
+ attrs: {},
924
+ content: jids.map(jid => ({
925
+ tag: 'token',
926
+ attrs: {
927
+ jid: jidNormalizedUser(jid),
928
+ t,
929
+ type: 'trusted_contact'
930
+ }
931
+ }))
932
+ }
933
+ ]
934
+ });
935
+ return result;
936
+ };
937
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
938
+ const ourin = new Dugong(waUploadToServer, relayMessage, config, sock);
939
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
940
+ return {
941
+ ...sock,
942
+ getPrivacyTokens,
943
+ assertSessions,
944
+ relayMessage,
945
+ sendReceipt,
946
+ sendReceipts,
947
+ readMessages,
948
+ refreshMediaConn,
949
+ waUploadToServer,
950
+ fetchPrivacySettings,
951
+ sendPeerDataOperationMessage,
952
+ createParticipantNodes,
953
+ getUSyncDevices,
954
+ messageRetryManager,
955
+ updateMediaMessage: async (message) => {
956
+ const content = assertMediaContent(message.message);
957
+ const mediaKey = content.mediaKey;
958
+ const meId = authState.creds.me.id;
959
+ const node = await encryptMediaRetryRequest(message.key, mediaKey, meId);
960
+ let error = undefined;
961
+ await Promise.all([
962
+ sendNode(node),
963
+ waitForMsgMediaUpdate(async (update) => {
964
+ const result = update.find(c => c.key.id === message.key.id);
965
+ if (result) {
966
+ if (result.error) {
967
+ error = result.error;
968
+ }
969
+ else {
970
+ try {
971
+ const media = await decryptMediaRetryData(result.media, mediaKey, result.key.id);
972
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
973
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
974
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
975
+ data: media,
976
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
977
+ });
978
+ }
979
+ content.directPath = media.directPath;
980
+ content.url = getUrlFromDirectPath(content.directPath);
981
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
982
+ }
983
+ catch (err) {
984
+ error = err;
985
+ }
986
+ }
987
+ return true;
988
+ }
989
+ })
990
+ ]);
991
+ if (error) {
992
+ throw error;
993
+ }
994
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
995
+ return message;
996
+ },
997
+ sendMessage: async (jid, content, options = {}) => {
998
+ const userJid = authState.creds.me.id;
999
+ const { quoted } = options;
1000
+ const messageType = ourin.detectType(content);
1001
+ if (typeof content === 'object' &&
1002
+ 'disappearingMessagesInChat' in content &&
1003
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1004
+ isJidGroup(jid)) {
1005
+ const { disappearingMessagesInChat } = content;
1006
+ const value = typeof disappearingMessagesInChat === 'boolean'
1007
+ ? disappearingMessagesInChat
1008
+ ? WA_DEFAULT_EPHEMERAL
1009
+ : 0
1010
+ : disappearingMessagesInChat;
1011
+ await groupToggleEphemeral(jid, value);
1012
+ } else if (messageType) {
1013
+ switch (messageType) {
1014
+ case "PAYMENT": {
1015
+ const paymentContent = await ourin.handlePayment(content, quoted);
1016
+ return await relayMessage(jid, paymentContent, {
1017
+ messageId: generateMessageIDV2(userJid),
1018
+ });
1019
+ }
1020
+ case "PRODUCT": {
1021
+ const productContent = await ourin.handleProduct(
1022
+ content,
1023
+ jid,
1024
+ quoted,
1025
+ );
1026
+ const productMsg = await generateWAMessageFromContent(
1027
+ jid,
1028
+ productContent,
1029
+ { quoted, userJid },
1030
+ );
1031
+ return await relayMessage(jid, productMsg.message, {
1032
+ messageId: productMsg.key.id,
1033
+ });
1034
+ }
1035
+ case "CAROUSEL": {
1036
+ const carouselContent = await ourin.handleCarousel(
1037
+ content,
1038
+ jid,
1039
+ quoted,
1040
+ );
1041
+ const carouselMsg = await generateWAMessageFromContent(
1042
+ jid,
1043
+ carouselContent,
1044
+ { quoted, userJid },
1045
+ );
1046
+ return await relayMessage(jid, carouselMsg.message, {
1047
+ messageId: carouselMsg.key.id,
1048
+ });
1049
+ }
1050
+ case "INTERACTIVE": {
1051
+ const interactiveContent = await ourin.handleInteractive(
1052
+ content,
1053
+ jid,
1054
+ quoted,
1055
+ );
1056
+ const interactiveMsg = await generateWAMessageFromContent(
1057
+ jid,
1058
+ interactiveContent,
1059
+ { quoted, userJid },
1060
+ );
1061
+ return await relayMessage(jid, interactiveMsg.message, {
1062
+ messageId: interactiveMsg.key.id,
1063
+ });
1064
+ }
1065
+ case "INTERACTIVE_BUTTONS": {
1066
+ const ibContent = await ourin.handleInteractiveButtons(
1067
+ content,
1068
+ jid,
1069
+ quoted,
1070
+ );
1071
+ const ibMsg = await generateWAMessageFromContent(jid, ibContent, {
1072
+ quoted,
1073
+ userJid,
1074
+ });
1075
+ return await relayMessage(jid, ibMsg.message, {
1076
+ messageId: ibMsg.key.id,
1077
+ });
1078
+ }
1079
+ case "ALBUM":
1080
+ return await ourin.handleAlbum(content, jid, quoted);
1081
+ case "EVENT":
1082
+ return await ourin.handleEvent(content, jid, quoted);
1083
+ case "POLL_RESULT":
1084
+ return await ourin.handlePollResult(content, jid, quoted);
1085
+ case "GROUP_STORY":
1086
+ return await ourin.handleGroupStory(content, jid, quoted, options);
1087
+ }
1088
+ } else {
1089
+ const fullMsg = await generateWAMessage(jid, content, {
1090
+ logger,
1091
+ userJid,
1092
+ getUrlInfo: text => getUrlInfo(text, {
1093
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1094
+ fetchOpts: {
1095
+ timeout: 3000,
1096
+ ...(httpRequestOptions || {})
1097
+ },
1098
+ logger,
1099
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1100
+ }),
1101
+ //TODO: CACHE
1102
+ getProfilePicUrl: sock.profilePictureUrl,
1103
+ getCallLink: sock.createCallLink,
1104
+ upload: async (readStream, opts) => {
1105
+ const up = await waUploadToServer(readStream, {
1106
+ ...opts,
1107
+ newsletter: isJidNewsletter(jid)
1108
+ });
1109
+ return up;
1110
+ },
1111
+ mediaCache: config.mediaCache,
1112
+ options: config.options,
1113
+ messageId: generateMessageIDV2(sock.user?.id),
1114
+ ...options
1115
+ });
1116
+ const isAiMsg = 'ai' in content && !!content.ai;
1117
+ const isEventMsg = 'event' in content && !!content.event;
1118
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1119
+ const isEditMsg = 'edit' in content && !!content.edit;
1120
+ const isPinMsg = 'pin' in content && !!content.pin;
1121
+ const isPollMessage = 'poll' in content && !!content.poll;
1122
+ const additionalAttributes = {};
1123
+ const additionalNodes = [];
1124
+ // required for delete
1125
+ if (isDeleteMsg) {
1126
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1127
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1128
+ additionalAttributes.edit = '8';
1129
+ }
1130
+ else {
1131
+ additionalAttributes.edit = '7';
1132
+ }
1133
+ }
1134
+ else if (isEditMsg) {
1135
+ additionalAttributes.edit = '1';
1136
+ }
1137
+ else if (isAiMsg) {
1138
+ additionalNodes.push({
1139
+ attrs: {
1140
+ biz_bot: '1'
1141
+ }, tag: "bot"
1142
+ });
1143
+ }
1144
+ else if (isPinMsg) {
1145
+ additionalAttributes.edit = '2';
1146
+ }
1147
+ else if (isPollMessage) {
1148
+ additionalNodes.push({
1149
+ tag: 'meta',
1150
+ attrs: {
1151
+ polltype: 'creation'
1152
+ }
1153
+ });
1154
+ }
1155
+ else if (isEventMsg) {
1156
+ additionalNodes.push({
1157
+ tag: 'meta',
1158
+ attrs: {
1159
+ event_type: 'creation'
1160
+ }
1161
+ });
1162
+ }
1163
+ await relayMessage(jid, fullMsg.message, {
1164
+ messageId: fullMsg.key.id,
1165
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1166
+ additionalAttributes,
1167
+ statusJidList: options.statusJidList,
1168
+ additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes
1169
+ });
1170
+ if (config.emitOwnEvents) {
1171
+ process.nextTick(() => {
1172
+ processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1173
+ });
1174
+ }
1175
+ return fullMsg;
1176
+ }
1177
+ }
1178
+ };
1179
+ };