@dnuzi/baileys 0.0.1

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