@itsliaaa/baileys 0.1.0

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