alisaaai-baileys 1.0.6

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