@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,1832 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { randomBytes } from 'crypto';
3
+ import { zip } from 'fflate';
4
+ import { promises as fs } from 'fs';
5
+ import {} from 'stream';
6
+ import { proto } from '../../WAProto/index.js';
7
+ import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, DONATE_URL, LIBRARY_NAME, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
8
+ import { AssociationType, ButtonHeaderType, ButtonType, CarouselCardType, ListType, ProtocolType, WAMessageStatus, WAProto } from '../Types/index.js';
9
+ import { isPnUser, isLidUser, isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
10
+ import { sha256 } from './crypto.js';
11
+ import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
12
+ import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, getImageProcessingLibrary, getRawMediaUploadData, getStream, toBuffer } from './messages-media.js';
13
+ import { shouldIncludeReportingToken } from './reporting-utils.js';
14
+ const MIMETYPE_MAP = {
15
+ image: 'image/jpeg',
16
+ video: 'video/mp4',
17
+ document: 'application/pdf',
18
+ audio: 'audio/ogg; codecs=opus',
19
+ sticker: 'image/webp',
20
+ 'product-catalog-image': 'image/jpeg'
21
+ };
22
+ const MessageTypeProto = {
23
+ image: WAProto.Message.ImageMessage,
24
+ video: WAProto.Message.VideoMessage,
25
+ audio: WAProto.Message.AudioMessage,
26
+ sticker: WAProto.Message.StickerMessage,
27
+ document: WAProto.Message.DocumentMessage
28
+ };
29
+ const mediaAnnotation = [{
30
+ polygonVertices: [{
31
+ x: 60.71664810180664,
32
+ y: -36.39784622192383
33
+ }, {
34
+ x: -16.710189819335938,
35
+ y: 49.263675689697266
36
+ }, {
37
+ x: -56.585853576660156,
38
+ y: 37.85963439941406
39
+ }, {
40
+ x: 20.840980529785156,
41
+ y: -47.80188751220703
42
+ }],
43
+ newsletter: {
44
+ // Lia@Note 03-02-26 --- You can change jid, message id, and name via .env (⁠≧⁠▽⁠≦⁠)
45
+ newsletterJid: process.env.NEWSLETTER_ID ||
46
+ Buffer.from('313230333633343034303036363434313339406e6577736c6574746572', 'hex').toString(),
47
+ serverMessageId: process.env.NEWSLETTER_MESSAGE_ID ||
48
+ Buffer.from('313033', 'hex').toString(),
49
+ newsletterName: process.env.NEWSLETTER_NAME ||
50
+ Buffer.from('f09d96b2f09d978df09d96baf09d978bf09d96bff09d96baf09d9785f09d9785', 'hex').toString(),
51
+ contentType: proto.ContextInfo.ForwardedNewsletterMessageInfo.ContentType.UPDATE,
52
+ accessibilityText: ''
53
+ }
54
+ }];
55
+ /**
56
+ * Uses a regex to test whether the string contains a URL, and returns the URL if it does.
57
+ * @param text eg. hello https://google.com
58
+ * @returns the URL, eg. https://google.com
59
+ */
60
+ export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
61
+ export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
62
+ const url = extractUrlFromText(text);
63
+ if (!!getUrlInfo && url) {
64
+ try {
65
+ const urlInfo = await getUrlInfo(url);
66
+ return urlInfo;
67
+ }
68
+ catch (error) {
69
+ // ignore if fails
70
+ logger?.warn({ trace: error.stack }, 'url generation failed');
71
+ }
72
+ }
73
+ };
74
+ const assertColor = async (color) => {
75
+ let assertedColor;
76
+ if (typeof color === 'number') {
77
+ assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1;
78
+ }
79
+ else {
80
+ let hex = color.trim().replace('#', '');
81
+ if (hex.length <= 6) {
82
+ hex = 'FF' + hex.padStart(6, '0');
83
+ }
84
+ assertedColor = parseInt(hex, 16);
85
+ return assertedColor;
86
+ }
87
+ };
88
+ export const prepareWAMessageMedia = async (message, options) => {
89
+ const logger = options.logger;
90
+ let mediaType;
91
+ for (const key of MEDIA_KEYS) {
92
+ if (key in message) {
93
+ mediaType = key;
94
+ }
95
+ }
96
+ if (!mediaType) {
97
+ throw new Boom('Invalid media type', { statusCode: 400 });
98
+ }
99
+ const uploadData = {
100
+ ...message,
101
+ media: message[mediaType]
102
+ };
103
+ if (uploadData.image || uploadData.video) {
104
+ uploadData.annotations = mediaAnnotation;
105
+ }
106
+ delete uploadData[mediaType];
107
+ // check if cacheable + generate cache key
108
+ const cacheableKey = typeof uploadData.media === 'object' &&
109
+ 'url' in uploadData.media &&
110
+ !!uploadData.media.url &&
111
+ !!options.mediaCache &&
112
+ mediaType + ':' + uploadData.media.url;
113
+ if (mediaType === 'document' && !uploadData.fileName) {
114
+ uploadData.fileName = LIBRARY_NAME;
115
+ }
116
+ if (!uploadData.mimetype) {
117
+ uploadData.mimetype = MIMETYPE_MAP[mediaType];
118
+ }
119
+ if (cacheableKey) {
120
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
121
+ if (mediaBuff) {
122
+ logger?.debug({ cacheableKey }, 'got media cache hit');
123
+ const obj = proto.Message.decode(mediaBuff);
124
+ const key = `${mediaType}Message`;
125
+ Object.assign(obj[key], { ...uploadData, media: undefined });
126
+ return obj;
127
+ }
128
+ }
129
+ const isNewsletter = !!options.jid && isJidNewsletter(options.jid);
130
+ const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
131
+ const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined';
132
+ const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true;
133
+ const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
134
+ const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation || requiresWaveformProcessing;
135
+ // Lia@Changes 06-02-26 --- Add few support for sending media to newsletter (⁠≧⁠▽⁠≦⁠)
136
+ if (isNewsletter) {
137
+ logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter');
138
+ const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger);
139
+ const fileSha256B64 = fileSha256.toString('base64');
140
+ const [{ mediaUrl, directPath }] = await Promise.all([
141
+ (async () => {
142
+ const result = options.upload(filePath, {
143
+ fileEncSha256B64: fileSha256B64,
144
+ mediaType,
145
+ timeoutMs: options.mediaUploadTimeoutMs,
146
+ newsletter: isNewsletter
147
+ });
148
+ logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
149
+ return result;
150
+ })(),
151
+ (async () => {
152
+ try {
153
+ if (requiresThumbnailComputation) {
154
+ const { thumbnail } = await generateThumbnail(filePath, mediaType, options);
155
+ uploadData.jpegThumbnail = thumbnail;
156
+ logger?.debug('generated thumbnail');
157
+ }
158
+ if (requiresDurationComputation) {
159
+ uploadData.seconds = await getAudioDuration(filePath);
160
+ logger?.debug('computed audio duration');
161
+ }
162
+ }
163
+ catch (error) {
164
+ logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
165
+ }
166
+ })()
167
+ ]).finally(async () => {
168
+ try {
169
+ await fs.unlink(filePath);
170
+ logger?.debug('removed tmp files');
171
+ }
172
+ catch (error) {
173
+ logger?.warn('failed to remove tmp file');
174
+ }
175
+ });
176
+ delete uploadData.media;
177
+ const obj = proto.Message.create({
178
+ // todo: add more support here
179
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
180
+ url: mediaUrl,
181
+ directPath,
182
+ fileSha256,
183
+ fileLength,
184
+ ...uploadData
185
+ })
186
+ });
187
+ if (uploadData.ptv) {
188
+ obj.ptvMessage = obj.videoMessage;
189
+ delete obj.videoMessage;
190
+ }
191
+ if (obj.stickerMessage) {
192
+ obj.stickerMessage.stickerSentTs = Date.now();
193
+ }
194
+ if (cacheableKey) {
195
+ logger?.debug({ cacheableKey }, 'set cache');
196
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
197
+ }
198
+ return obj;
199
+ }
200
+ const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
201
+ logger,
202
+ saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
203
+ opts: options.options
204
+ });
205
+ const fileEncSha256B64 = fileEncSha256.toString('base64');
206
+ const [{ mediaUrl, directPath }] = await Promise.all([
207
+ (async () => {
208
+ const result = await options.upload(encFilePath, {
209
+ fileEncSha256B64,
210
+ mediaType,
211
+ timeoutMs: options.mediaUploadTimeoutMs
212
+ });
213
+ logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
214
+ return result;
215
+ })(),
216
+ (async () => {
217
+ try {
218
+ if (requiresThumbnailComputation) {
219
+ const { thumbnail, originalImageDimensions } = await generateThumbnail(originalFilePath, mediaType, options);
220
+ uploadData.jpegThumbnail = thumbnail;
221
+ if (!uploadData.width && originalImageDimensions) {
222
+ uploadData.width = originalImageDimensions.width;
223
+ uploadData.height = originalImageDimensions.height;
224
+ logger?.debug('set dimensions');
225
+ }
226
+ logger?.debug('generated thumbnail');
227
+ }
228
+ if (requiresDurationComputation) {
229
+ uploadData.seconds = await getAudioDuration(originalFilePath);
230
+ logger?.debug('computed audio duration');
231
+ }
232
+ if (requiresWaveformProcessing) {
233
+ uploadData.waveform = await getAudioWaveform(originalFilePath, logger);
234
+ logger?.debug('processed waveform');
235
+ }
236
+ if (requiresAudioBackground) {
237
+ uploadData.backgroundArgb = await assertColor(options.backgroundColor);
238
+ logger?.debug('computed backgroundColor audio status');
239
+ }
240
+ }
241
+ catch (error) {
242
+ logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
243
+ }
244
+ })()
245
+ ]).finally(async () => {
246
+ try {
247
+ await fs.unlink(encFilePath);
248
+ if (originalFilePath) {
249
+ await fs.unlink(originalFilePath);
250
+ }
251
+ logger?.debug('removed tmp files');
252
+ }
253
+ catch (error) {
254
+ logger?.warn('failed to remove tmp file');
255
+ }
256
+ });
257
+ delete uploadData.media;
258
+ const obj = proto.Message.create({
259
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
260
+ url: mediaUrl,
261
+ directPath,
262
+ mediaKey,
263
+ fileEncSha256,
264
+ fileSha256,
265
+ fileLength,
266
+ mediaKeyTimestamp: unixTimestampSeconds(),
267
+ ...uploadData
268
+ })
269
+ });
270
+ if (uploadData.ptv) {
271
+ obj.ptvMessage = obj.videoMessage;
272
+ delete obj.videoMessage;
273
+ }
274
+ if (obj.stickerMessage) {
275
+ obj.stickerMessage.stickerSentTs = Date.now();
276
+ }
277
+ if (cacheableKey) {
278
+ logger?.debug({ cacheableKey }, 'set cache');
279
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
280
+ }
281
+ return obj;
282
+ };
283
+ export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
284
+ ephemeralExpiration = ephemeralExpiration || 0;
285
+ const content = {
286
+ ephemeralMessage: {
287
+ message: {
288
+ protocolMessage: {
289
+ type: ProtocolType.EPHEMERAL_SETTING,
290
+ ephemeralExpiration
291
+ }
292
+ }
293
+ }
294
+ };
295
+ return content;
296
+ };
297
+ // Lia@Changes 31-01-26 --- Extract product message into a standalone function so it can also be reused as the header for interactive messages
298
+ const prepareProductMessage = async (message, options) => {
299
+ if (!message.businessOwnerJid) {
300
+ throw new Boom('"businessOwnerJid" is missing from the content', { statusCode: 400 });
301
+ }
302
+ const { imageMessage } = await prepareWAMessageMedia({ image: message.image || message.product.productImage }, options);
303
+ // Lia@Changes 01-02-26 --- Add product message default value
304
+ const content = {
305
+ ...message,
306
+ product: {
307
+ currencyCode: 'IDR',
308
+ priceAmount1000: 1000,
309
+ title: LIBRARY_NAME,
310
+ ...message.product,
311
+ productImage: imageMessage
312
+ }
313
+ };
314
+ delete content.image;
315
+ return content;
316
+ };
317
+ /**
318
+ * Lia@Note 30-01-26
319
+ * ---
320
+ * Credits: Work on ensuring stickerPackMessage fields are valid by @jlucaso1 (https://github.com/jlucaso1).
321
+ * based on https://github.com/WhiskeySockets/Baileys/pull/1561
322
+ */
323
+ const prepareStickerPackMessage = async (message, options) => {
324
+ const { cover, stickers = [], name = '📦 Sticker Pack', publisher = 'GitHub: itsliaaa', description = '🏷️ itsliaaa/baileys' } = message;
325
+ if (stickers.length > 60) {
326
+ throw new Boom('Sticker pack exceeds the maximum limit of 60 stickers', { statusCode: 400 });
327
+ }
328
+ if (stickers.length === 0) {
329
+ throw new Boom('Sticker pack must contain at least one sticker', { statusCode: 400 });
330
+ }
331
+ if (!cover) {
332
+ throw new Boom('Sticker pack must contain a cover', { statusCode: 400 });
333
+ }
334
+ // Lia@Changes 01-02-26 --- Add caching for sticker pack (similiar to prepareWAMessageMedia)
335
+ const cacheableKey = Array.isArray(stickers) &&
336
+ stickers.length &&
337
+ !!options.mediaCache &&
338
+ 'sticker:' + stickers
339
+ .reduce((acc, x) => {
340
+ const url = typeof x.data === 'object' &&
341
+ 'url' in x.data &&
342
+ !!x.data.url &&
343
+ x.data.url;
344
+ if (url) acc.push(url);
345
+ return acc;
346
+ }, [])
347
+ .join('@');
348
+ if (cacheableKey) {
349
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
350
+ if (mediaBuff) {
351
+ options.logger?.debug({ cacheableKey }, 'got media cache hit');
352
+ return proto.Message.StickerPackMessage.decode(mediaBuff);
353
+ }
354
+ }
355
+ const lib = await getImageProcessingLibrary();
356
+ const stickerPackIdValue = generateMessageIDV2();
357
+ const stickerData = {};
358
+ const stickerPromises = stickers.map(async (sticker, i) => {
359
+ const { stream } = await getStream(sticker.data);
360
+ const buffer = await toBuffer(stream);
361
+ let webpBuffer,
362
+ isAnimated = false;
363
+ const isWebP = isWebPBuffer(buffer);
364
+ if (isWebP) {
365
+ // Already WebP - preserve original to keep exif metadata and animation
366
+ webpBuffer = buffer;
367
+ isAnimated = isAnimatedWebP(buffer);
368
+ }
369
+ else if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
370
+ // Convert to WebP, preserving metadata
371
+ webpBuffer = await lib
372
+ .sharp
373
+ .default(buffer)
374
+ .resize(512, 512, { fit: 'inside' })
375
+ .webp({ quality: 80 })
376
+ .toBuffer();
377
+ // Non-WebP inputs converted to WebP are not animated
378
+ isAnimated = false;
379
+ }
380
+ else {
381
+ throw new Boom('No image processing library (sharp) available for converting sticker to WebP. Either install sharp or provide stickers in WebP format.');
382
+ }
383
+ if (webpBuffer.length > 1024 * 1024) {
384
+ throw new Boom(`Sticker at index ${i} exceeds the 1MB size limit`, { statusCode: 400 });
385
+ }
386
+ const hash = sha256(webpBuffer).toString('base64').replace(/\//g, '-');
387
+ const fileName = hash + '.webp';
388
+ stickerData[fileName] = [new Uint8Array(webpBuffer), { level: 0 }];
389
+ return {
390
+ fileName,
391
+ mimetype: 'image/webp',
392
+ isAnimated,
393
+ emojis: sticker.emojis || ['✨'],
394
+ accessibilityLabel: sticker.accessibilityLabel || '‎'
395
+ };
396
+ });
397
+ const stickerMetadata = await Promise.all(stickerPromises);
398
+ // Process and add cover/tray icon to the ZIP
399
+ const trayIconFileName = stickerPackIdValue + '.webp';
400
+ const { stream: coverStream } = await getStream(cover);
401
+ const coverBuffer = await toBuffer(coverStream);
402
+ let coverWebpBuffer;
403
+ const isCoverWebP = isWebPBuffer(coverBuffer);
404
+ if (isCoverWebP) {
405
+ // Already WebP - preserve original to keep exif metadata
406
+ coverWebpBuffer = coverBuffer;
407
+ }
408
+ else if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
409
+ coverWebpBuffer = await lib
410
+ .sharp
411
+ .default(coverBuffer)
412
+ .resize(512, 512, { fit: 'inside' })
413
+ .webp({ quality: 80 })
414
+ .toBuffer();
415
+ }
416
+ else {
417
+ throw new Boom('No image processing library (sharp) available for converting cover to WebP. Either install sharp or provide cover in WebP format.');
418
+ }
419
+ // Add cover to ZIP data
420
+ stickerData[trayIconFileName] = [new Uint8Array(coverWebpBuffer), { level: 0 }];
421
+ const zipBuffer = await new Promise((resolve, reject) => {
422
+ zip(stickerData, (error, data) => {
423
+ if (error) {
424
+ reject(error);
425
+ } else {
426
+ resolve(Buffer.from(data));
427
+ }
428
+ });
429
+ });
430
+ const stickerPackSize = zipBuffer.length;
431
+ const stickerPackUpload = await encryptedStream(zipBuffer, 'sticker-pack', {
432
+ logger: options.logger,
433
+ opts: options.options
434
+ });
435
+ const stickerPackUploadResult = await options.upload(stickerPackUpload.encFilePath, {
436
+ fileEncSha256B64: stickerPackUpload.fileEncSha256.toString('base64'),
437
+ mediaType: 'sticker-pack',
438
+ timeoutMs: options.mediaUploadTimeoutMs
439
+ });
440
+ await fs.unlink(stickerPackUpload.encFilePath);
441
+ const obj = {
442
+ name: name,
443
+ publisher: publisher,
444
+ stickerPackId: stickerPackIdValue,
445
+ packDescription: description,
446
+ stickerPackOrigin: proto.Message.StickerPackMessage.StickerPackOrigin.USER_CREATED,
447
+ stickerPackSize: stickerPackSize,
448
+ stickers: stickerMetadata,
449
+ fileSha256: stickerPackUpload.fileSha256,
450
+ fileEncSha256: stickerPackUpload.fileEncSha256,
451
+ mediaKey: stickerPackUpload.mediaKey,
452
+ directPath: stickerPackUploadResult.directPath,
453
+ fileLength: stickerPackUpload.fileLength,
454
+ mediaKeyTimestamp: unixTimestampSeconds(),
455
+ trayIconFileName: trayIconFileName
456
+ };
457
+ try {
458
+ // Reuse the cover buffer we already processed for thumbnail generation
459
+ let thumbnailBuffer;
460
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
461
+ thumbnailBuffer = await lib
462
+ .sharp
463
+ .default(coverBuffer)
464
+ .resize(252, 252)
465
+ .jpeg()
466
+ .toBuffer();
467
+ }
468
+ else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'function') {
469
+ const jimpImage = await lib.jimp.Jimp.read(coverBuffer);
470
+ thumbnailBuffer = await jimpImage
471
+ .resize({ w: 252, h: 252 })
472
+ .getBuffer('image/jpeg');
473
+ }
474
+ else {
475
+ throw new Error('No image processing library available for thumbnail generation');
476
+ }
477
+ if (!thumbnailBuffer || thumbnailBuffer.length === 0) {
478
+ throw new Error('Failed to generate thumbnail buffer');
479
+ }
480
+ const thumbUpload = await encryptedStream(thumbnailBuffer, 'thumbnail-sticker-pack', {
481
+ logger: options.logger,
482
+ opts: options.options,
483
+ mediaKey: stickerPackUpload.mediaKey // Use same mediaKey as the sticker pack ZIP
484
+ });
485
+ const thumbUploadResult = await options.upload(thumbUpload.encFilePath, {
486
+ fileEncSha256B64: thumbUpload.fileEncSha256.toString('base64'),
487
+ mediaType: 'thumbnail-sticker-pack',
488
+ timeoutMs: options.mediaUploadTimeoutMs
489
+ });
490
+ await fs.unlink(thumbUpload.encFilePath);
491
+ Object.assign(obj, {
492
+ thumbnailDirectPath: thumbUploadResult.directPath,
493
+ thumbnailSha256: thumbUpload.fileSha256,
494
+ thumbnailEncSha256: thumbUpload.fileEncSha256,
495
+ thumbnailHeight: 252,
496
+ thumbnailWidth: 252,
497
+ imageDataHash: sha256(thumbnailBuffer).toString('base64')
498
+ });
499
+ }
500
+ catch (error) {
501
+ options.logger?.warn?.(`Thumbnail generation failed: ${error}`);
502
+ }
503
+ const content = obj;
504
+ if (cacheableKey) {
505
+ options.logger?.debug({ cacheableKey }, 'set cache');
506
+ await options.mediaCache.set(cacheableKey, WAProto.Message.StickerPackMessage.encode(content).finish());
507
+ }
508
+ return WAProto.Message.StickerPackMessage.fromObject(content);
509
+ };
510
+ // Lia@Changes 30-01-26 --- Add native flow button helper for interactive message
511
+ const prepareNativeFlowButtons = (message) => {
512
+ const buttons = message.nativeFlow
513
+ const isButtonsFieldArray = Array.isArray(buttons);
514
+ const correctedField = isButtonsFieldArray ? buttons : buttons.buttons;
515
+ const messageParamsJson = {};
516
+ // Lia@Changes 31-01-26 --- Add coupon and options inside interactive message
517
+ if (hasOptionalProperty(message, 'couponCode') && !!message.couponCode) {
518
+ Object.assign(messageParamsJson, {
519
+ limited_time_offer: {
520
+ text: message.couponText || LIBRARY_NAME,
521
+ url: message.couponUrl || DONATE_URL, // Lia@Note 02-02-26 --- Apologies if this feels cheeky, just a fallback
522
+ copy_code: message.couponCode,
523
+ expiration_time: Date.now() * 2
524
+ }
525
+ });
526
+ }
527
+ if (hasOptionalProperty(message, 'optionText') && !!message.optionText) {
528
+ Object.assign(messageParamsJson, {
529
+ bottom_sheet: {
530
+ in_thread_buttons_limit: 1,
531
+ divide_indices: [],
532
+ list_title: message.optionTitle || '📄 Select Options',
533
+ button_title: message.optionText
534
+ }
535
+ });
536
+ }
537
+ return {
538
+ buttons: correctedField.map(button => {
539
+ if (hasOptionalProperty(button, 'id') && !!button.id) {
540
+ return {
541
+ name: 'quick_reply',
542
+ buttonParamsJson: JSON.stringify({
543
+ display_text: button.text || button.buttonText || '👉🏻 Click',
544
+ id: button.id
545
+ })
546
+ };
547
+ }
548
+ else if (hasOptionalProperty(button, 'copy') && !!button.copy) {
549
+ return {
550
+ name: 'cta_copy',
551
+ buttonParamsJson: JSON.stringify({
552
+ display_text: button.text || button.buttonText || '📋 Copy',
553
+ copy_code: button.copy
554
+ })
555
+ };
556
+ }
557
+ else if (hasOptionalProperty(button, 'url') && !!button.url) {
558
+ return {
559
+ name: 'cta_url',
560
+ buttonParamsJson: JSON.stringify({
561
+ display_text: button.text || button.buttonText || '🌐 Visit',
562
+ url: button.url,
563
+ merchant_url: button.url
564
+ })
565
+ };
566
+ }
567
+ else if (hasOptionalProperty(button, 'call') && !!button.call) {
568
+ return {
569
+ name: 'cta_call',
570
+ buttonParamsJson: JSON.stringify({
571
+ display_text: button.text || button.buttonText || '📞 Call',
572
+ phone_number: button.call
573
+ })
574
+ };
575
+ }
576
+ return button;
577
+ }),
578
+ messageParamsJson: JSON.stringify(messageParamsJson),
579
+ messageVersion: 1
580
+ };
581
+ };
582
+ /**
583
+ * Generate forwarded message content like WA does
584
+ * @param message the message to forward
585
+ * @param options.forceForward will show the message as forwarded even if it is from you
586
+ */
587
+ export const generateForwardMessageContent = (message, forceForward) => {
588
+ let content = message.message || message;
589
+ if (!content) {
590
+ throw new Boom('no content in message', { statusCode: 400 });
591
+ }
592
+ // hacky copy
593
+ content = normalizeMessageContent(content);
594
+ content = proto.Message.decode(proto.Message.encode(content).finish());
595
+ let key = Object.keys(content)[0];
596
+ let score = content?.[key]?.contextInfo?.forwardingScore || 0;
597
+ score += message.key.fromMe && !forceForward ? 0 : 1;
598
+ if (key === 'conversation') {
599
+ content.extendedTextMessage = { text: content[key] };
600
+ delete content.conversation;
601
+ key = 'extendedTextMessage';
602
+ }
603
+ const key_ = content?.[key];
604
+ const contextInfo = {};
605
+ if (score > 0) {
606
+ contextInfo.forwardingScore = score;
607
+ contextInfo.isForwarded = true;
608
+ }
609
+ // when forwarding a newsletter/channel message, add the newsletter context
610
+ // so the server knows where to find the original media
611
+ const remoteJid = message.key?.remoteJid;
612
+ if (remoteJid && isJidNewsletter(remoteJid)) {
613
+ contextInfo.forwardedNewsletterMessageInfo = {
614
+ newsletterJid: remoteJid,
615
+ serverMessageId: message.key?.server_id ? parseInt(message.key.server_id) : null,
616
+ newsletterName: null
617
+ };
618
+ // strip messageContextInfo (contains messageSecret etc.) as WA Web does
619
+ delete content.messageContextInfo;
620
+ }
621
+ key_.contextInfo = contextInfo;
622
+ return content;
623
+ };
624
+ export const hasNonNullishProperty = (message, key) => {
625
+ return (typeof message === 'object' &&
626
+ message !== null &&
627
+ key in message &&
628
+ message[key] !== null &&
629
+ message[key] !== undefined);
630
+ };
631
+ export const hasOptionalProperty = (obj, key) => {
632
+ return typeof obj === 'object' &&
633
+ obj !== null &&
634
+ key in obj &&
635
+ obj[key] !== null;
636
+ };
637
+ // Lia@Changes 06-02-26 --- Validate album message media to avoid bug 👀
638
+ export const hasValidAlbumMedia = (message) => {
639
+ return Boolean(message.imageMessage ||
640
+ message.videoMessage);
641
+ };
642
+ export const hasValidInteractiveHeader = (message) => {
643
+ return Boolean(message.imageMessage ||
644
+ message.videoMessage ||
645
+ message.documentMessage ||
646
+ message.productMessage ||
647
+ message.locationMessage);
648
+ };
649
+ // Lia@Changes 30-01-26 --- Validate carousel cards header to avoid bug 👀
650
+ export const hasValidCarouselHeader = (message) => {
651
+ return Boolean(message.imageMessage ||
652
+ message.videoMessage ||
653
+ message.productMessage);
654
+ };
655
+ export const generateWAMessageContent = async (message, options) => {
656
+ var _a, _b;
657
+ let m = {};
658
+ if (hasNonNullishProperty(message, 'text')) {
659
+ const extContent = { text: message.text };
660
+ let urlInfo = message.linkPreview;
661
+ if (typeof urlInfo === 'undefined') {
662
+ urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
663
+ }
664
+ if (urlInfo) {
665
+ extContent.matchedText = urlInfo['matched-text'];
666
+ extContent.jpegThumbnail = urlInfo.jpegThumbnail;
667
+ extContent.description = urlInfo.description;
668
+ extContent.title = urlInfo.title;
669
+ extContent.previewType = 0;
670
+ const img = urlInfo.highQualityThumbnail;
671
+ if (img) {
672
+ extContent.thumbnailDirectPath = img.directPath;
673
+ extContent.mediaKey = img.mediaKey;
674
+ extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
675
+ extContent.thumbnailWidth = img.width;
676
+ extContent.thumbnailHeight = img.height;
677
+ extContent.thumbnailSha256 = img.fileSha256;
678
+ extContent.thumbnailEncSha256 = img.fileEncSha256;
679
+ }
680
+ }
681
+ if (options.backgroundColor) {
682
+ extContent.backgroundArgb = await assertColor(options.backgroundColor);
683
+ }
684
+ if (options.font) {
685
+ extContent.font = options.font;
686
+ }
687
+ m.extendedTextMessage = extContent;
688
+ }
689
+ else if (hasNonNullishProperty(message, 'contacts')) {
690
+ const { contacts } = message; // Lia@Changes 04-02-26 --- Destructured for readability & cleaner access (⁠✷⁠‿⁠✷⁠)
691
+ const contactLen = contacts.contacts.length;
692
+ if (!contactLen) {
693
+ throw new Boom('require atleast 1 contact', { statusCode: 400 });
694
+ }
695
+ if (contactLen === 1) {
696
+ m.contactMessage = contacts.contacts[0];
697
+ }
698
+ else {
699
+ m.contactsArrayMessage = contacts;
700
+ }
701
+ }
702
+ else if (hasNonNullishProperty(message, 'location')) {
703
+ m.locationMessage = message.location;
704
+ }
705
+ else if (hasNonNullishProperty(message, 'react')) {
706
+ const { react } = message; // Lia@Changes 04-02-26 --- Destructured for readability & cleaner access (⁠✷⁠‿⁠✷⁠)
707
+ if (!react.senderTimestampMs) {
708
+ react.senderTimestampMs = Date.now();
709
+ }
710
+ m.reactionMessage = react;
711
+ }
712
+ else if (hasNonNullishProperty(message, 'delete')) {
713
+ m.protocolMessage = {
714
+ key: message.delete,
715
+ type: ProtocolType.REVOKE
716
+ };
717
+ }
718
+ else if (hasNonNullishProperty(message, 'forward')) {
719
+ m = generateForwardMessageContent(message.forward, message.force);
720
+ }
721
+ else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
722
+ const { disappearingMessagesInChat } = message; // Lia@Changes 04-02-26 --- Destructured for readability & cleaner access (⁠✷⁠‿⁠✷⁠)
723
+ const exp = typeof disappearingMessagesInChat === 'boolean'
724
+ ? disappearingMessagesInChat
725
+ ? WA_DEFAULT_EPHEMERAL
726
+ : 0
727
+ : disappearingMessagesInChat;
728
+ m = prepareDisappearingMessageSettingContent(exp);
729
+ }
730
+ else if (hasNonNullishProperty(message, 'groupInvite')) {
731
+ const { groupInvite } = message; // Lia@Changes 04-02-26 --- Destructured for readability & cleaner access (⁠✷⁠‿⁠✷⁠)
732
+ m.groupInviteMessage = {};
733
+ m.groupInviteMessage.inviteCode = groupInvite.inviteCode;
734
+ m.groupInviteMessage.inviteExpiration = groupInvite.inviteExpiration;
735
+ m.groupInviteMessage.caption = groupInvite.text;
736
+ m.groupInviteMessage.groupJid = groupInvite.jid;
737
+ m.groupInviteMessage.groupName = groupInvite.subject;
738
+ //TODO: use built-in interface and get disappearing mode info etc.
739
+ //TODO: cache / use store!?
740
+ if (options.getProfilePicUrl) {
741
+ const pfpUrl = await options.getProfilePicUrl(groupInvite.jid, 'preview');
742
+ if (pfpUrl) {
743
+ const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
744
+ if (resp.ok) {
745
+ const buf = Buffer.from(await resp.arrayBuffer());
746
+ m.groupInviteMessage.jpegThumbnail = buf;
747
+ }
748
+ }
749
+ }
750
+ }
751
+ else if (hasNonNullishProperty(message, 'stickers')) {
752
+ m.stickerPackMessage = await prepareStickerPackMessage(message, options);
753
+ }
754
+ else if (hasNonNullishProperty(message, 'pin')) {
755
+ m.pinInChatMessage = {};
756
+ m.messageContextInfo = {};
757
+ m.pinInChatMessage.key = message.pin;
758
+ m.pinInChatMessage.type = message.type;
759
+ m.pinInChatMessage.senderTimestampMs = Date.now();
760
+ m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
761
+ }
762
+ else if (hasNonNullishProperty(message, 'keep')) {
763
+ m.keepInChatMessage = {};
764
+ m.keepInChatMessage.key = message.keep;
765
+ m.keepInChatMessage.keepType = message.type;
766
+ m.keepInChatMessage.timestampMs = Date.now();
767
+ }
768
+ else if (hasNonNullishProperty(message, 'flowReply')) {
769
+ const { flowReply } = message; // Lia@Changes 04-02-26 --- Destructured for readability & cleaner access (⁠✷⁠‿⁠✷⁠)
770
+ m.interactiveResponseMessage = {
771
+ body: {
772
+ format: flowReply.format || proto.Message.InteractiveResponseMessage.Body.Format.DEFAULT,
773
+ text: flowReply.text
774
+ },
775
+ nativeFlowResponseMessage: {
776
+ name: flowReply.name,
777
+ paramsJson: flowReply.paramsJson || '{}',
778
+ version: flowReply.version || 1
779
+ }
780
+ };
781
+ }
782
+ else if (hasNonNullishProperty(message, 'buttonReply')) {
783
+ const { buttonReply } = message; // Lia@Changes 04-02-26 --- Destructured for readability & cleaner access (⁠✷⁠‿⁠✷⁠)
784
+ switch (message.type) {
785
+ case 'template':
786
+ m.templateButtonReplyMessage = {
787
+ selectedDisplayText: buttonReply.displayText,
788
+ selectedId: buttonReply.id,
789
+ selectedIndex: buttonReply.index
790
+ };
791
+ break;
792
+ case 'plain':
793
+ m.buttonsResponseMessage = {
794
+ selectedButtonId: buttonReply.id,
795
+ selectedDisplayText: buttonReply.displayText,
796
+ type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
797
+ };
798
+ break;
799
+ }
800
+ }
801
+ else if (hasNonNullishProperty(message, 'listReply')) {
802
+ const { listReply } = message; // Lia@Changes 04-02-26 --- Destructured for readability & cleaner access (⁠✷⁠‿⁠✷⁠)
803
+ m.listResponseMessage = {
804
+ description: listReply.description,
805
+ listType: proto.Message.ListResponseMessage.ListType.SINGLE_SELECT,
806
+ singleSelectReply: {
807
+ selectedRowId: listReply.id
808
+ },
809
+ title: listReply.title
810
+ };
811
+ }
812
+ else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
813
+ const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options);
814
+ m.ptvMessage = videoMessage;
815
+ }
816
+ else if (hasNonNullishProperty(message, 'product')) {
817
+ m.productMessage = await prepareProductMessage(message, options);
818
+ }
819
+ else if (hasNonNullishProperty(message, 'event')) {
820
+ const { event } = message; // Lia@Changes 04-02-26 --- Destructured for readability & cleaner access (⁠✷⁠‿⁠✷⁠)
821
+ m.eventMessage = {};
822
+ const startTime = Math.floor(event.startDate.getTime() / 1000);
823
+ if (event.call && options.getCallLink) {
824
+ const token = await options.getCallLink(event.call, { startTime });
825
+ m.eventMessage.joinLink = (event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
826
+ }
827
+ m.messageContextInfo = {
828
+ // encKey
829
+ messageSecret: event.messageSecret || randomBytes(32)
830
+ };
831
+ m.eventMessage.name = event.name;
832
+ m.eventMessage.description = event.description;
833
+ m.eventMessage.startTime = startTime;
834
+ m.eventMessage.endTime = event.endDate ? event.endDate.getTime() / 1000 : undefined;
835
+ m.eventMessage.isCanceled = event.isCancelled ?? false;
836
+ m.eventMessage.extraGuestsAllowed = event.extraGuestsAllowed;
837
+ m.eventMessage.isScheduleCall = event.isScheduleCall ?? false;
838
+ m.eventMessage.location = event.location;
839
+ }
840
+ else if (hasNonNullishProperty(message, 'poll')) {
841
+ const { poll } = message; // Lia@Changes 04-02-26 --- Destructured for readability & cleaner access (⁠✷⁠‿⁠✷⁠)
842
+ (_a = poll).selectableCount || (_a.selectableCount = 0);
843
+ (_b = poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
844
+ if (!Array.isArray(poll.values)) {
845
+ throw new Boom('Invalid poll values', { statusCode: 400 });
846
+ }
847
+ if (poll.selectableCount < 0 || poll.selectableCount > poll.values.length) {
848
+ throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${poll.values.length}`, {
849
+ statusCode: 400
850
+ });
851
+ }
852
+ m.messageContextInfo = {
853
+ // encKey
854
+ messageSecret: poll.messageSecret || randomBytes(32)
855
+ };
856
+ const pollCreationMessage = {
857
+ name: poll.name,
858
+ selectableOptionsCount: poll.selectableCount,
859
+ options: poll.values.map(optionName => ({ optionName }))
860
+ };
861
+ if (poll.toAnnouncementGroup) {
862
+ // poll v2 is for community announcement groups (single select and multiple)
863
+ m.pollCreationMessageV2 = pollCreationMessage;
864
+ }
865
+ else {
866
+ // Lia@Changes 08-02-26 --- Add quiz message support
867
+ if (poll.pollType === 1) {
868
+ if (!poll.correctAnswer) {
869
+ throw new Boom('No "correctAnswer" provided for quiz', { statusCode: 400 });
870
+ }
871
+ m.pollCreationMessageV5 = {
872
+ // Lia@Note 08-02-26 --- quiz for newsletter only
873
+ ...pollCreationMessage,
874
+ correctAnswer: {
875
+ optionName: poll.correctAnswer.toString()
876
+ },
877
+ pollType: poll.pollType,
878
+ selectableOptionsCount: 1
879
+ };
880
+ }
881
+ else if (poll.selectableCount === 1) {
882
+ //poll v3 is for single select polls
883
+ m.pollCreationMessageV3 = pollCreationMessage;
884
+ }
885
+ else {
886
+ // poll for multiple choice polls
887
+ m.pollCreationMessage = pollCreationMessage;
888
+ }
889
+ }
890
+ }
891
+ // Lia@Changes 08-02-26 --- Add poll result snapshot message
892
+ else if (hasNonNullishProperty(message, 'pollResult')) {
893
+ const { pollResult } = message;
894
+ const pollResultSnapshotMessage = {
895
+ name: pollResult.name,
896
+ pollVotes: pollResult.votes.map(vote => ({
897
+ optionName: vote.name,
898
+ optionVoteCount: parseInt(vote.voteCount)
899
+ }))
900
+ };
901
+ if (pollResult.pollType === 1) {
902
+ pollResultSnapshotMessage.pollType = proto.Message.PollType.QUIZ;
903
+ m.pollResultSnapshotMessageV3 = pollResultSnapshotMessage;
904
+ }
905
+ else {
906
+ pollResultSnapshotMessage.pollType = proto.Message.PollType.POLL;
907
+ m.pollResultSnapshotMessage = pollResultSnapshotMessage;
908
+ }
909
+ }
910
+ // Lia@Changes 08-02-26 --- Add poll update message
911
+ else if (hasNonNullishProperty(message, 'pollUpdate')) {
912
+ const { pollUpdate } = message;
913
+ if (!pollUpdate.key) {
914
+ throw new Boom('Message key is required', { statusCode: 400 });
915
+ }
916
+ if (!pollUpdate.vote) {
917
+ throw new Boom('Encrypted vote payload is required', { statusCode: 400 });
918
+ }
919
+ m.pollUpdateMessage = {
920
+ metadata: pollUpdate.metadata,
921
+ pollCreationMessageKey: pollUpdate.key,
922
+ senderTimestampMs: Date.now(),
923
+ vote: pollUpdate.vote
924
+ };
925
+ }
926
+ else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
927
+ m.protocolMessage = {
928
+ type: ProtocolType.SHARE_PHONE_NUMBER
929
+ };
930
+ }
931
+ else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
932
+ m.requestPhoneNumberMessage = {};
933
+ }
934
+ else if (hasNonNullishProperty(message, 'limitSharing')) {
935
+ m.protocolMessage = {
936
+ type: ProtocolType.LIMIT_SHARING,
937
+ limitSharing: {
938
+ sharingLimited: message.limitSharing === true,
939
+ trigger: 1,
940
+ limitSharingSettingTimestamp: Date.now(),
941
+ initiatedByMe: true
942
+ }
943
+ };
944
+ }
945
+ // Lia@Changes 01-02-26 --- Add payment invite message
946
+ else if (hasNonNullishProperty(message, 'paymentInviteServiceType')) {
947
+ m.paymentInviteMessage = {
948
+ expiryTimestamp: Date.now(),
949
+ serviceType: message.paymentInviteServiceType
950
+ };
951
+ }
952
+ // Lia@Changes 01-02-26 --- Add order message
953
+ else if (hasNonNullishProperty(message, 'orderText')) {
954
+ if (!Buffer.isBuffer(message.thumbnail)) {
955
+ throw new Boom('Must provide thumbnail buffer in order message', { statusCode: 400 });
956
+ }
957
+ m.orderMessage = {
958
+ itemCount: 1,
959
+ messageVersion: 1,
960
+ orderTitle: LIBRARY_NAME,
961
+ status: proto.Message.OrderMessage.OrderStatus.INQUIRY,
962
+ surface: proto.Message.OrderMessage.OrderSurface.CATALOG,
963
+ token: generateMessageIDV2(),
964
+ totalAmount1000: 1000,
965
+ totalCurrencyCode: 'IDR',
966
+ ...message,
967
+ message: message.orderText
968
+ };
969
+ delete m.orderMessage.orderText;
970
+ }
971
+ // Lia@Changes 31-01-26 --- Add support for album messages
972
+ else if (hasNonNullishProperty(message, 'album')) {
973
+ const { album } = message;
974
+ if (!Array.isArray(album)) {
975
+ throw new Boom('Invalid album type. Expected an array.', { statusCode: 400 });
976
+ }
977
+ let videoCount = 0;
978
+ for (let i = 0; i < album.length; i++) {
979
+ if (album[i].video) videoCount++;
980
+ };
981
+ let imageCount = 0;
982
+ for (let i = 0; i < album.length; i++) {
983
+ if (album[i].image) imageCount++;
984
+ };
985
+ if ((videoCount + imageCount) < 2) {
986
+ throw new Boom('Minimum provide 2 media to upload album message', { statusCode: 400 });
987
+ }
988
+ m.albumMessage = {
989
+ expectedImageCount: imageCount,
990
+ expectedVideoCount: videoCount
991
+ };
992
+ }
993
+ // Lia@Changes 30-01-26 --- Add "raw" boolean to send raw messages directly via generateWAMessage()
994
+ else if (hasNonNullishProperty(message, 'raw')) {
995
+ delete message.raw;
996
+ return proto.Message.create(message);
997
+ }
998
+ else {
999
+ m = await prepareWAMessageMedia(message, options);
1000
+ }
1001
+ // Lia@Changes 30-01-26 --- Add interactive messages (buttonsMessage, listMessage, interactiveMessage, templateMessage, and carouselMessage)
1002
+ if (hasNonNullishProperty(message, 'buttons')) {
1003
+ const buttonsMessage = {
1004
+ buttons: message.buttons.map(button => {
1005
+ if (hasOptionalProperty(button, 'name')) {
1006
+ return {
1007
+ nativeFlowInfo: {
1008
+ name: button.name,
1009
+ paramsJson: button.paramsJson
1010
+ },
1011
+ type: ButtonType.NATIVE_FLOW
1012
+ };
1013
+ }
1014
+ const buttonText = button.text || button.buttonText
1015
+ return {
1016
+ buttonId: button.id || button.buttonId,
1017
+ buttonText: typeof buttonText === 'string' ? { displayText: buttonText } : buttonText,
1018
+ type: button.type || ButtonType.RESPONSE
1019
+ };
1020
+ })
1021
+ };
1022
+ if (hasOptionalProperty(message, 'text')) {
1023
+ buttonsMessage.contentText = message.text;
1024
+ buttonsMessage.headerType = ButtonHeaderType.EMPTY;
1025
+ }
1026
+ else {
1027
+ if (hasOptionalProperty(message, 'caption')) {
1028
+ buttonsMessage.contentText = message.caption;
1029
+ }
1030
+ const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
1031
+ buttonsMessage.headerType = ButtonHeaderType[type];
1032
+ Object.assign(buttonsMessage, m);
1033
+ }
1034
+ if (hasOptionalProperty(message, 'footer')) {
1035
+ buttonsMessage.footerText = message.footer;
1036
+ }
1037
+ m = { buttonsMessage };
1038
+ }
1039
+ else if (hasNonNullishProperty(message, 'sections')) {
1040
+ const listMessage = {
1041
+ sections: message.sections,
1042
+ buttonText: message.buttonText,
1043
+ title: message.title,
1044
+ footerText: message.footer,
1045
+ description: message.text,
1046
+ listType: ListType.SINGLE_SELECT
1047
+ };
1048
+ m = { listMessage };
1049
+ }
1050
+ // Lia@Note 03-02-26 --- This message type is shown on WhatsApp Web/Desktop and iOS (I guess 。⁠◕⁠‿⁠◕⁠。). On Android, it only appears in newsletter (so far ಥ⁠‿⁠ಥ)
1051
+ else if (hasNonNullishProperty(message, 'templateButtons')) {
1052
+ const hydratedTemplate = {
1053
+ hydratedButtons: message.templateButtons.map((button, i) => {
1054
+ if (hasOptionalProperty(button, 'id')) {
1055
+ return {
1056
+ index: i,
1057
+ quickReplyButton: {
1058
+ displayText: button.text || button.buttonText || '👉🏻 Click',
1059
+ id: button.id
1060
+ }
1061
+ };
1062
+ }
1063
+ else if (hasOptionalProperty(button, 'url')) {
1064
+ return {
1065
+ index: i,
1066
+ urlButton: {
1067
+ displayText: button.text || button.buttonText || '🌐 Visit',
1068
+ url: button.url
1069
+ }
1070
+ };
1071
+ }
1072
+ else if (hasOptionalProperty(button, 'call')) {
1073
+ return {
1074
+ index: i,
1075
+ callButton: {
1076
+ displayText: button.text || button.buttonText || '📞 Call',
1077
+ phoneNumber: button.call
1078
+ }
1079
+ };
1080
+ }
1081
+ button.index = button.index || i;
1082
+ return button;
1083
+ })
1084
+ };
1085
+ if (hasOptionalProperty(message, 'text')) {
1086
+ hydratedTemplate.hydratedContentText = message.text;
1087
+ }
1088
+ else {
1089
+ if (hasOptionalProperty(message, 'caption')) {
1090
+ hydratedTemplate.hydratedTitleText = message.title;
1091
+ hydratedTemplate.hydratedContentText = message.caption;
1092
+ };
1093
+ Object.assign(hydratedTemplate, m);
1094
+ }
1095
+ if (hasOptionalProperty(message, 'footer')) {
1096
+ hydratedTemplate.hydratedFooterText = message.footer;
1097
+ }
1098
+ hydratedTemplate.templateId = message.id || 'template-' + Date.now(); // Lia@Note 04-02-26 --- Minimal templateId to satisfy WhatsApp (⁠ ⁠ꈍ⁠ᴗ⁠ꈍ⁠)
1099
+ m = {
1100
+ templateMessage: {
1101
+ hydratedFourRowTemplate: hydratedTemplate,
1102
+ hydratedTemplate: hydratedTemplate
1103
+ }
1104
+ }
1105
+ }
1106
+ else if (hasNonNullishProperty(message, 'nativeFlow')) {
1107
+ const interactiveMessage = {
1108
+ nativeFlowMessage: prepareNativeFlowButtons(message)
1109
+ };
1110
+ if (hasOptionalProperty(message, 'bizJid')) {
1111
+ interactiveMessage.collectionMessage = {
1112
+ bizJid: message.bizJid,
1113
+ id: message.id,
1114
+ messageVersion: 1
1115
+ };
1116
+ }
1117
+ else if (hasOptionalProperty(message, 'shopSurface')) {
1118
+ interactiveMessage.shopStorefrontMessage = {
1119
+ surface: message.shopSurface,
1120
+ id: message.id,
1121
+ messageVersion: 1
1122
+ };
1123
+ }
1124
+ if (hasOptionalProperty(message, 'text')) {
1125
+ interactiveMessage.body = { text: message.text };
1126
+ }
1127
+ else {
1128
+ if (hasOptionalProperty(message, 'caption')) {
1129
+ const isValidHeader = hasValidInteractiveHeader(m)
1130
+ if (!isValidHeader) {
1131
+ throw new Boom('Invalid media type for interactive message header', { statusCode: 400 });
1132
+ }
1133
+ interactiveMessage.header = {
1134
+ title: message.title || '',
1135
+ subtitle: message.subtitle || '',
1136
+ hasMediaAttachment: isValidHeader
1137
+ };
1138
+ interactiveMessage.body = { text: message.caption };
1139
+ }
1140
+ if (hasOptionalProperty(message, 'thumbnail') && !!message.thumbnail) {
1141
+ interactiveMessage.jpegThumbnail = message.thumbnail;
1142
+ }
1143
+ Object.assign(interactiveMessage.header, m);
1144
+ }
1145
+ if (hasOptionalProperty(message, 'audioFooter')) {
1146
+ const parseFooter = await prepareWAMessageMedia({
1147
+ audio: message.audioFooter
1148
+ }, options);
1149
+ interactiveMessage.footer = {
1150
+ audioMessage: parseFooter.audioMessage,
1151
+ hasMediaAttachment: true
1152
+ };
1153
+ }
1154
+ else if (hasOptionalProperty(message, 'footer')) {
1155
+ interactiveMessage.footer = { text: message.footer };
1156
+ }
1157
+ m = { interactiveMessage };
1158
+ }
1159
+ else if (hasNonNullishProperty(message, 'cards')) {
1160
+ const interactiveMessage = {
1161
+ carouselMessage: {
1162
+ cards: await Promise.all(message.cards.map(async card => {
1163
+ let carouselHeader = {};
1164
+ if (hasNonNullishProperty(card, 'product')) {
1165
+ carouselHeader.productMessage = await prepareProductMessage(card, options);
1166
+ }
1167
+ else {
1168
+ carouselHeader = await prepareWAMessageMedia(card, options).catch(() => ({ }));
1169
+ }
1170
+ const isValidHeader = hasValidCarouselHeader(carouselHeader)
1171
+ if (!isValidHeader) {
1172
+ throw new Boom('Invalid media type for carousel card', { statusCode: 400 });
1173
+ }
1174
+ const carouselCard = {
1175
+ nativeFlowMessage: prepareNativeFlowButtons(card.nativeFlow ? card : [])
1176
+ };
1177
+ if (hasOptionalProperty(card, 'text')) {
1178
+ carouselCard.body = { text: card.text };
1179
+ }
1180
+ else {
1181
+ if (hasOptionalProperty(card, 'caption')) {
1182
+ carouselCard.header = {
1183
+ title: card.title || '',
1184
+ subtitle: card.subtitle || '',
1185
+ hasMediaAttachment: isValidHeader
1186
+ };
1187
+ carouselCard.body = { text: card.caption };
1188
+ }
1189
+ if (hasOptionalProperty(card, 'thumbnail') && !!card.thumbnail) {
1190
+ carouselCard.jpegThumbnail = card.thumbnail;
1191
+ }
1192
+ Object.assign(carouselCard.header, carouselHeader);
1193
+ }
1194
+ if (hasOptionalProperty(card, 'audioFooter')) {
1195
+ const parseFooter = await prepareWAMessageMedia({
1196
+ audio: card.audioFooter
1197
+ }, options);
1198
+ carouselCard.footer = {
1199
+ audioMessage: parseFooter.audioMessage,
1200
+ hasMediaAttachment: true
1201
+ };
1202
+ }
1203
+ else if (hasOptionalProperty(card, 'footer')) {
1204
+ carouselCard.footer = { text: card.footer };
1205
+ }
1206
+ return carouselCard
1207
+ })),
1208
+ carouselCardType: CarouselCardType.UNKNOWN,
1209
+ messageVersion: 1
1210
+ }
1211
+ };
1212
+ if (hasOptionalProperty(message, 'text')) {
1213
+ interactiveMessage.body = { text: message.text };
1214
+ }
1215
+ if (hasOptionalProperty(message, 'footer')) {
1216
+ interactiveMessage.footer = { text: message.footer };
1217
+ }
1218
+ m = { interactiveMessage };
1219
+ }
1220
+ // Lia@Changes 01-02-26 --- Add request payment message
1221
+ else if (hasNonNullishProperty(message, 'requestPaymentFrom')) {
1222
+ const requestPaymentMessage = {
1223
+ amount: {
1224
+ currencyCode: 'IDR',
1225
+ offset: 1000,
1226
+ value: 1000
1227
+ },
1228
+ amount1000: 1000,
1229
+ currencyCodeIso4217: 'IDR',
1230
+ expiryTimestamp: Date.now(),
1231
+ noteMessage: m,
1232
+ requestFrom: message.requestPaymentFrom,
1233
+ ...message
1234
+ };
1235
+ delete requestPaymentMessage.requestPaymentFrom;
1236
+ if (hasNonNullishProperty(m, 'extendedTextMessage') || hasNonNullishProperty(m, 'stickerMessage')) {
1237
+ Object.assign(requestPaymentMessage.noteMessage, m);
1238
+ }
1239
+ else {
1240
+ throw new Boom('Invalid message type for request payment note message', { statusCode: 400 });
1241
+ }
1242
+ m = { requestPaymentMessage };
1243
+ }
1244
+ // Lia@Changes 01-02-26 --- Add invoice message
1245
+ else if (hasNonNullishProperty(message, 'invoiceNote')) {
1246
+ const attachment = m.imageMessage || m.documentMessage;
1247
+ const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
1248
+ const invoiceMessage = {
1249
+ attachmentType: proto.Message.InvoiceMessage.AttachmentType[type === 'DOCUMENT' ? 'PDF' : 'IMAGE'],
1250
+ note: message.invoiceNote
1251
+ };
1252
+ if (attachment) {
1253
+ const { directPath, fileEncSha256, fileSha256, jpegThumbnail = undefined, mediaKey, mediaKeyTimestamp, mimetype } = attachment;
1254
+ Object.assign(invoiceMessage, {
1255
+ attachmentDirectPath: directPath,
1256
+ attachmentFileEncSha256: fileEncSha256,
1257
+ attachmentFileSha256: fileSha256,
1258
+ attachmentJpegThumbnail: jpegThumbnail,
1259
+ attachmentMediaKey: mediaKey,
1260
+ attachmentMediaKeyTimestamp: mediaKeyTimestamp,
1261
+ attachmentMimetype: mimetype,
1262
+ token: generateMessageIDV2()
1263
+ });
1264
+ }
1265
+ else {
1266
+ throw new Boom('Invalid media type for invoice message', { statusCode: 400 });
1267
+ }
1268
+ m = { invoiceMessage };
1269
+ }
1270
+ // Lia@Changes 31-01-26 --- Add direct externalAdReply access (no need to create contextInfo first)
1271
+ if (hasOptionalProperty(message, 'externalAdReply') && !!message.externalAdReply) {
1272
+ const messageType = Object.keys(m)[0];
1273
+ const key = m[messageType];
1274
+ const content = message.externalAdReply;
1275
+ if ('thumbnail' in content && !Buffer.isBuffer(content.thumbnail)) {
1276
+ throw new Boom('Thumbnail must in buffer type', { statusCode: 400 });
1277
+ }
1278
+ if (!content.url || typeof content.url !== 'string') {
1279
+ content.url = DONATE_URL; // Lia@Note 02-02-26 --- Apologies if this feels cheeky, just a fallback
1280
+ }
1281
+ const externalAdReply = {
1282
+ ...content,
1283
+ body: content.body,
1284
+ mediaType: content.mediaType || 1,
1285
+ mediaUrl: content.url + '?update=' + Date.now(),
1286
+ renderLargerThumbnail: content.largeThumbnail,
1287
+ thumbnail: content.thumbnail,
1288
+ thumbnailUrl: content.url,
1289
+ title: content.title || LIBRARY_NAME
1290
+ };
1291
+ delete externalAdReply.subTitle;
1292
+ delete externalAdReply.largeThumbnail;
1293
+ delete externalAdReply.url;
1294
+ if ('contextInfo' in key && !!key.contextInfo) {
1295
+ key.contextInfo.externalAdReply = { ...key.contextInfo.externalAdReply, ...externalAdReply };
1296
+ }
1297
+ else if (key) {
1298
+ key.contextInfo = { externalAdReply };
1299
+ }
1300
+ }
1301
+ if (hasOptionalProperty(message, 'mentions') && message.mentions?.length) {
1302
+ const messageType = Object.keys(m)[0];
1303
+ const key = m[messageType];
1304
+ if ('contextInfo' in key && !!key.contextInfo) {
1305
+ key.contextInfo.mentionedJid = message.mentions;
1306
+ }
1307
+ else if (key) {
1308
+ key.contextInfo = {
1309
+ mentionedJid: message.mentions
1310
+ }
1311
+ }
1312
+ }
1313
+ if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
1314
+ const messageType = Object.keys(m)[0];
1315
+ const key = m[messageType];
1316
+ if ('contextInfo' in key && !!key.contextInfo) {
1317
+ key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
1318
+ }
1319
+ else if (key) {
1320
+ key.contextInfo = message.contextInfo;
1321
+ }
1322
+ }
1323
+ // Lia@Changes 31-01-26 --- Add "groupStatus" boolean to set contextInfo.isGroupStatus and wrap message into groupStatusMessageV2
1324
+ if (hasOptionalProperty(message, 'groupStatus') && !!message.groupStatus) {
1325
+ const messageType = Object.keys(m)[0];
1326
+ const key = m[messageType];
1327
+ if ('contextInfo' in key && !!key.contextInfo) {
1328
+ key.contextInfo.isGroupStatus = message.groupStatus;
1329
+ }
1330
+ else if (key) {
1331
+ key.contextInfo = {
1332
+ isGroupStatus: message.groupStatus
1333
+ }
1334
+ }
1335
+ m = { groupStatusMessageV2: { message: m } };
1336
+ delete message.groupStatus;
1337
+ }
1338
+ // Lia@Changes 02-02-26 --- Add "interactiveAsTemplate" boolean to wrap interactiveMessage into templateMessage
1339
+ else if (hasOptionalProperty(message, 'interactiveAsTemplate') && !!message.interactiveAsTemplate) {
1340
+ if (!m.interactiveMessage) {
1341
+ throw new Boom('Invalid message type for template', { statusCode: 400 }); // Lia@Note 02-02-26 --- To avoid bug 👀
1342
+ }
1343
+ m = {
1344
+ templateMessage: {
1345
+ interactiveMessageTemplate: m.interactiveMessage,
1346
+ templateId: message.id || 'template-' + Date.now() // Lia@Note 04-02-26 --- Minimal templateId to satisfy WhatsApp (⁠ ⁠ꈍ⁠ᴗ⁠ꈍ⁠)
1347
+ }
1348
+ };
1349
+ delete message.interactiveAsTemplate;
1350
+ }
1351
+ // Lia@Changes 30-01-26 --- Add "ephemeral" boolean to wrap message into ephemeralMessage like "viewOnce"
1352
+ if (hasOptionalProperty(message, 'ephemeral') && !!message.ephemeral) {
1353
+ m = { ephemeralMessage: { message: m } };
1354
+ delete message.ephemeral;
1355
+ }
1356
+ else if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
1357
+ m = { viewOnceMessage: { message: m } };
1358
+ }
1359
+ // Lia@Changes 03-02-26 --- Add "viewOnceV2" boolean to wrap message into viewOnceMessageV2 like "viewOnce"
1360
+ else if (hasOptionalProperty(message, 'viewOnceV2') && !!message.viewOnceV2) {
1361
+ m = { viewOnceMessageV2: { message: m } };
1362
+ delete message.viewOnceV2;
1363
+ }
1364
+ // Lia@Changes 03-02-26 --- Add "viewOnceV2Extension" boolean to wrap message into viewOnceMessageV2Extension like "viewOnce"
1365
+ else if (hasOptionalProperty(message, 'viewOnceV2Extension') && !!message.viewOnceV2Extension) {
1366
+ m = { viewOnceMessageV2Extension: { message: m } };
1367
+ delete message.viewOnceV2Extension;
1368
+ }
1369
+ if (hasOptionalProperty(message, 'edit')) {
1370
+ m = {
1371
+ protocolMessage: {
1372
+ key: message.edit,
1373
+ editedMessage: m,
1374
+ timestampMs: Date.now(),
1375
+ type: ProtocolType.MESSAGE_EDIT
1376
+ }
1377
+ }
1378
+ }
1379
+ if (shouldIncludeReportingToken(m)) {
1380
+ m.messageContextInfo = m.messageContextInfo || {};
1381
+ if (!m.messageContextInfo.messageSecret) {
1382
+ m.messageContextInfo.messageSecret = randomBytes(32);
1383
+ }
1384
+ }
1385
+ return proto.Message.create(m);
1386
+ };
1387
+ export const generateWAMessageFromContent = (jid, message, options) => {
1388
+ // set timestamp to now
1389
+ // if not specified
1390
+ if (!options.timestamp) {
1391
+ options.timestamp = Date.now();
1392
+ }
1393
+ const messageContextInfo = message.messageContextInfo
1394
+ const innerMessage = normalizeMessageContent(message);
1395
+ const key = getContentType(innerMessage);
1396
+ const timestamp = unixTimestampSeconds(options.timestamp);
1397
+ const isNewsletter = isJidNewsletter(jid);
1398
+ const { quoted, userJid } = options;
1399
+ if (quoted && !isNewsletter) {
1400
+ const participant = quoted.key.fromMe
1401
+ ? userJid // TODO: Add support for LIDs
1402
+ : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
1403
+ let quotedMsg = normalizeMessageContent(quoted.message);
1404
+ const msgType = getContentType(quotedMsg);
1405
+ // strip any redundant properties
1406
+ quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
1407
+ const quotedContent = quotedMsg[msgType];
1408
+ if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
1409
+ delete quotedContent.contextInfo;
1410
+ }
1411
+ const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {};
1412
+ contextInfo.participant = jidNormalizedUser(participant);
1413
+ contextInfo.stanzaId = quoted.key.id;
1414
+ contextInfo.quotedMessage = quotedMsg;
1415
+ // if a participant is quoted, then it must be a group
1416
+ // hence, remoteJid of group must also be entered
1417
+ if (jid !== quoted.key.remoteJid) {
1418
+ contextInfo.remoteJid = quoted.key.remoteJid;
1419
+ }
1420
+ if (contextInfo && innerMessage[key]) {
1421
+ /* @ts-ignore */
1422
+ innerMessage[key].contextInfo = contextInfo;
1423
+ }
1424
+ }
1425
+ if (
1426
+ // if we want to send a disappearing message
1427
+ !!options?.ephemeralExpiration &&
1428
+ // and it's not a protocol message -- delete, toggle disappear message
1429
+ key !== 'protocolMessage' &&
1430
+ // already not converted to disappearing message
1431
+ key !== 'ephemeralMessage' &&
1432
+ // newsletters don't support ephemeral messages
1433
+ !isNewsletter) {
1434
+ /* @ts-ignore */
1435
+ innerMessage[key].contextInfo = {
1436
+ ...(innerMessage[key].contextInfo || {}),
1437
+ expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
1438
+ //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
1439
+ };
1440
+ }
1441
+ // Lia@Changes 30-01-26 --- Add deviceListMetadata inside messageContextInfo for private chat
1442
+ else if (messageContextInfo?.messageSecret && (isPnUser(jid) || isLidUser(jid))) {
1443
+ messageContextInfo.deviceListMetadata = {
1444
+ recipientKeyHash: randomBytes(10),
1445
+ recipientTimestamp: unixTimestampSeconds()
1446
+ };
1447
+ messageContextInfo.deviceListMetadataVersion = 2
1448
+ }
1449
+ message = proto.Message.create(message);
1450
+ const messageJSON = {
1451
+ key: {
1452
+ remoteJid: jid,
1453
+ fromMe: true,
1454
+ id: options?.messageId || generateMessageIDV2()
1455
+ },
1456
+ message: message,
1457
+ messageTimestamp: timestamp,
1458
+ messageStubParameters: [],
1459
+ participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
1460
+ status: WAMessageStatus.PENDING
1461
+ };
1462
+ return WAProto.WebMessageInfo.fromObject(messageJSON);
1463
+ };
1464
+ export const generateWAMessage = async (jid, content, options = {}) => {
1465
+ // ensure msg ID is with every log
1466
+ options.logger = options?.logger?.child({ msgId: options.messageId });
1467
+ // Pass jid in the options to generateWAMessageContent
1468
+ if (jid && typeof options === 'object') {
1469
+ options.jid = jid;
1470
+ }
1471
+ return generateWAMessageFromContent(jid, await generateWAMessageContent(content, options), options);
1472
+ };
1473
+ /** Get the key to access the true type of content */
1474
+ export const getContentType = (content) => {
1475
+ if (content) {
1476
+ const keys = Object.keys(content);
1477
+ const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
1478
+ return key;
1479
+ }
1480
+ };
1481
+ /**
1482
+ * Normalizes ephemeral, view once messages to regular message content
1483
+ * Eg. image messages in ephemeral messages, in view once messages etc.
1484
+ * @param content
1485
+ * @returns
1486
+ */
1487
+ export const normalizeMessageContent = (content) => {
1488
+ if (!content) {
1489
+ return undefined;
1490
+ }
1491
+ // set max iterations to prevent an infinite loop
1492
+ for (let i = 0; i < 5; i++) {
1493
+ const inner = getFutureProofMessage(content);
1494
+ if (!inner) {
1495
+ break;
1496
+ }
1497
+ content = inner.message;
1498
+ }
1499
+ return content;
1500
+ // Lia@Changes 03-02-26 --- Add all futureProofMessage into getFutureProofMessage()
1501
+ function getFutureProofMessage(message) {
1502
+ return (
1503
+ message?.associatedChildMessage ||
1504
+ message?.botForwardedMessage ||
1505
+ message?.botInvokeMessage ||
1506
+ message?.botTaskMessage ||
1507
+ message?.documentWithCaptionMessage ||
1508
+ message?.editedMessage ||
1509
+ message?.ephemeralMessage ||
1510
+ message?.eventCoverImage ||
1511
+ message?.groupMentionedMessage ||
1512
+ message?.groupStatusMentionMessage ||
1513
+ message?.groupStatusMessage ||
1514
+ message?.groupStatusMessageV2 ||
1515
+ message?.limitSharingMessage ||
1516
+ message?.lottieStickerMessage ||
1517
+ message?.pollCreationMessageV4 ||
1518
+ message?.pollCreationOptionImageMessage ||
1519
+ message?.questionMessage ||
1520
+ message?.questionReplyMessage ||
1521
+ message?.statusAddYours ||
1522
+ message?.statusMentionMessage ||
1523
+ message?.viewOnceMessage ||
1524
+ message?.viewOnceMessageV2 ||
1525
+ message?.viewOnceMessageV2Extension
1526
+ );
1527
+ }
1528
+ };
1529
+ /**
1530
+ * Extract the true message content from a message
1531
+ * Eg. extracts the inner message from a disappearing message/view once message
1532
+ */
1533
+ export const extractMessageContent = (content) => {
1534
+ const extractFromTemplateMessage = (msg) => {
1535
+ if (msg.imageMessage) {
1536
+ return { imageMessage: msg.imageMessage };
1537
+ }
1538
+ else if (msg.documentMessage) {
1539
+ return { documentMessage: msg.documentMessage };
1540
+ }
1541
+ else if (msg.videoMessage) {
1542
+ return { videoMessage: msg.videoMessage };
1543
+ }
1544
+ else if (msg.locationMessage) {
1545
+ return { locationMessage: msg.locationMessage };
1546
+ }
1547
+ else {
1548
+ return {
1549
+ conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
1550
+ };
1551
+ }
1552
+ };
1553
+ content = normalizeMessageContent(content);
1554
+ if (content?.buttonsMessage) {
1555
+ return extractFromTemplateMessage(content.buttonsMessage);
1556
+ }
1557
+ if (content?.templateMessage?.hydratedFourRowTemplate) {
1558
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
1559
+ }
1560
+ if (content?.templateMessage?.hydratedTemplate) {
1561
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
1562
+ }
1563
+ if (content?.templateMessage?.fourRowTemplate) {
1564
+ return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
1565
+ }
1566
+ return content;
1567
+ };
1568
+ /**
1569
+ * Returns the device predicted by message ID
1570
+ */
1571
+ export const getDevice = (id) => /^3A.{18}$/.test(id)
1572
+ ? 'ios'
1573
+ : /^3E.{20}$/.test(id)
1574
+ ? 'web'
1575
+ : /^(.{21}|.{32})$/.test(id)
1576
+ ? 'android'
1577
+ : /^(3F|.{18}$)/.test(id)
1578
+ ? 'desktop'
1579
+ : 'unknown';
1580
+ /** Upserts a receipt in the message */
1581
+ export const updateMessageWithReceipt = (msg, receipt) => {
1582
+ msg.userReceipt = msg.userReceipt || [];
1583
+ const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
1584
+ if (recp) {
1585
+ Object.assign(recp, receipt);
1586
+ }
1587
+ else {
1588
+ msg.userReceipt.push(receipt);
1589
+ }
1590
+ };
1591
+ /** Update the message with a new reaction */
1592
+ export const updateMessageWithReaction = (msg, reaction) => {
1593
+ const authorID = getKeyAuthor(reaction.key);
1594
+ const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID);
1595
+ reaction.text = reaction.text || '';
1596
+ reactions.push(reaction);
1597
+ msg.reactions = reactions;
1598
+ };
1599
+ /** Update the message with a new poll update */
1600
+ export const updateMessageWithPollUpdate = (msg, update) => {
1601
+ const authorID = getKeyAuthor(update.pollUpdateMessageKey);
1602
+ const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID);
1603
+ if (update.vote?.selectedOptions?.length) {
1604
+ reactions.push(update);
1605
+ }
1606
+ msg.pollUpdates = reactions;
1607
+ };
1608
+ /** Update the message with a new event response */
1609
+ export const updateMessageWithEventResponse = (msg, update) => {
1610
+ const authorID = getKeyAuthor(update.eventResponseMessageKey);
1611
+ const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID);
1612
+ responses.push(update);
1613
+ msg.eventResponses = responses;
1614
+ };
1615
+ /**
1616
+ * Aggregates all poll updates in a poll.
1617
+ * @param msg the poll creation message
1618
+ * @param meId your jid
1619
+ * @returns A list of options & their voters
1620
+ */
1621
+ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
1622
+ const opts = message?.pollCreationMessage?.options ||
1623
+ message?.pollCreationMessageV2?.options ||
1624
+ message?.pollCreationMessageV3?.options ||
1625
+ [];
1626
+ const voteHashMap = opts.reduce((acc, opt) => {
1627
+ const hash = sha256(Buffer.from(opt.optionName || '')).toString();
1628
+ acc[hash] = {
1629
+ name: opt.optionName || '',
1630
+ voters: []
1631
+ };
1632
+ return acc;
1633
+ }, {});
1634
+ for (const update of pollUpdates || []) {
1635
+ const { vote } = update;
1636
+ if (!vote) {
1637
+ continue;
1638
+ }
1639
+ for (const option of vote.selectedOptions || []) {
1640
+ const hash = option.toString();
1641
+ let data = voteHashMap[hash];
1642
+ if (!data) {
1643
+ voteHashMap[hash] = {
1644
+ name: 'Unknown',
1645
+ voters: []
1646
+ };
1647
+ data = voteHashMap[hash];
1648
+ }
1649
+ voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId));
1650
+ }
1651
+ }
1652
+ return Object.values(voteHashMap);
1653
+ }
1654
+ /**
1655
+ * Aggregates all event responses in an event message.
1656
+ * @param msg the event creation message
1657
+ * @param meId your jid
1658
+ * @returns A list of response types & their responders
1659
+ */
1660
+ export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
1661
+ const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE'];
1662
+ const responseMap = {};
1663
+ for (const type of responseTypes) {
1664
+ responseMap[type] = {
1665
+ response: type,
1666
+ responders: []
1667
+ };
1668
+ }
1669
+ for (const update of eventResponses || []) {
1670
+ const responseType = update.eventResponse || 'UNKNOWN';
1671
+ if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
1672
+ responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId));
1673
+ }
1674
+ }
1675
+ return Object.values(responseMap);
1676
+ }
1677
+ /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
1678
+ export const aggregateMessageKeysNotFromMe = (keys) => {
1679
+ const keyMap = {};
1680
+ for (const { remoteJid, id, participant, fromMe } of keys) {
1681
+ if (!fromMe) {
1682
+ const uqKey = `${remoteJid}:${participant || ''}`;
1683
+ if (!keyMap[uqKey]) {
1684
+ keyMap[uqKey] = {
1685
+ jid: remoteJid,
1686
+ participant: participant,
1687
+ messageIds: []
1688
+ };
1689
+ }
1690
+ keyMap[uqKey].messageIds.push(id);
1691
+ }
1692
+ }
1693
+ return Object.values(keyMap);
1694
+ };
1695
+ const REUPLOAD_REQUIRED_STATUS = [410, 404];
1696
+ /**
1697
+ * Downloads the given message. Throws an error if it's not a media message
1698
+ */
1699
+ export const downloadMediaMessage = async (message, type, options, ctx) => {
1700
+ const result = await downloadMsg().catch(async (error) => {
1701
+ if (ctx &&
1702
+ typeof error?.status === 'number' && // treat errors with status as HTTP failures requiring reupload
1703
+ REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
1704
+ ctx.logger.info({ key: message.key }, 'sending reupload media request...');
1705
+ // request reupload
1706
+ message = await ctx.reuploadRequest(message);
1707
+ const result = await downloadMsg();
1708
+ return result;
1709
+ }
1710
+ throw error;
1711
+ });
1712
+ return result;
1713
+ async function downloadMsg() {
1714
+ const mContent = extractMessageContent(message.message);
1715
+ if (!mContent) {
1716
+ throw new Boom('No message present', { statusCode: 400, data: message });
1717
+ }
1718
+ const contentType = getContentType(mContent);
1719
+ let mediaType = contentType?.replace('Message', '');
1720
+ const media = mContent[contentType];
1721
+ if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
1722
+ throw new Boom(`"${contentType}" message is not a media message`);
1723
+ }
1724
+ let download;
1725
+ if ('thumbnailDirectPath' in media && !('url' in media)) {
1726
+ download = {
1727
+ directPath: media.thumbnailDirectPath,
1728
+ mediaKey: media.mediaKey
1729
+ };
1730
+ mediaType = 'thumbnail-link';
1731
+ }
1732
+ else {
1733
+ download = media;
1734
+ }
1735
+ const stream = await downloadContentFromMessage(download, mediaType, options);
1736
+ if (type === 'buffer') {
1737
+ const bufferArray = [];
1738
+ for await (const chunk of stream) {
1739
+ bufferArray.push(chunk);
1740
+ }
1741
+ return Buffer.concat(bufferArray);
1742
+ }
1743
+ return stream;
1744
+ }
1745
+ };
1746
+ /** Checks whether the given message is a media message; if it is returns the inner content */
1747
+ export const assertMediaContent = (content) => {
1748
+ content = extractMessageContent(content);
1749
+ const mediaContent = content?.documentMessage ||
1750
+ content?.imageMessage ||
1751
+ content?.videoMessage ||
1752
+ content?.audioMessage ||
1753
+ content?.stickerMessage;
1754
+ if (!mediaContent) {
1755
+ throw new Boom('given message is not a media message', { statusCode: 400, data: content });
1756
+ }
1757
+ return mediaContent;
1758
+ };
1759
+ /**
1760
+ * Checks if a WebP buffer is animated by looking for VP8X chunk with animation flag
1761
+ * or ANIM/ANMF chunks
1762
+ */
1763
+ const isAnimatedWebP = (buffer) => {
1764
+ // WebP must start with RIFF....WEBP
1765
+ if (
1766
+ buffer.length < 12 ||
1767
+ buffer[0] !== 0x52 ||
1768
+ buffer[1] !== 0x49 ||
1769
+ buffer[2] !== 0x46 ||
1770
+ buffer[3] !== 0x46 ||
1771
+ buffer[8] !== 0x57 ||
1772
+ buffer[9] !== 0x45 ||
1773
+ buffer[10] !== 0x42 ||
1774
+ buffer[11] !== 0x50
1775
+ ) {
1776
+ return false;
1777
+ };
1778
+ // Parse chunks starting after RIFF header (12 bytes)
1779
+ let offset = 12;
1780
+ while (offset < buffer.length - 8) {
1781
+ const chunkFourCC = buffer.toString('ascii', offset, offset + 4);
1782
+ const chunkSize = buffer.readUInt32LE(offset + 4);
1783
+ if (chunkFourCC === 'VP8X') {
1784
+ // VP8X extended header, check animation flag (bit 1 at offset+8)
1785
+ const flagsOffset = offset + 8;
1786
+ if (flagsOffset < buffer.length) {
1787
+ const flags = buffer[flagsOffset];
1788
+ if (flags & 0x02) {
1789
+ return true;
1790
+ };
1791
+ };
1792
+ } else if (chunkFourCC === 'ANIM' || chunkFourCC === 'ANMF') {
1793
+ // ANIM or ANMF chunks indicate animation
1794
+ return true;
1795
+ };
1796
+ // Move to next chunk (chunk size + 8 bytes header, padded to even)
1797
+ offset += 8 + chunkSize + (chunkSize % 2);
1798
+ };
1799
+ return false;
1800
+ };
1801
+ /**
1802
+ * Checks if a buffer is a WebP file
1803
+ */
1804
+ const isWebPBuffer = (buffer) => {
1805
+ return (
1806
+ buffer.length >= 12 &&
1807
+ buffer[0] === 0x52 &&
1808
+ buffer[1] === 0x49 &&
1809
+ buffer[2] === 0x46 &&
1810
+ buffer[3] === 0x46 &&
1811
+ buffer[8] === 0x57 &&
1812
+ buffer[9] === 0x45 &&
1813
+ buffer[10] === 0x42 &&
1814
+ buffer[11] === 0x50
1815
+ );
1816
+ };
1817
+ /**
1818
+ * Lia@Changes 30-01-26
1819
+ * ---
1820
+ * Determines whether a message should include a Biz Binary Node.
1821
+ * A Biz Binary Node is added only for interactive messages
1822
+ * such as buttons or other supported interactive types.
1823
+ */
1824
+ export const shouldIncludeBizBinaryNode = (message) => {
1825
+ const messageType = getContentType(message);
1826
+ return (
1827
+ messageType === 'buttonsMessage' ||
1828
+ messageType === 'interactiveMessage' ||
1829
+ messageType === 'listMessage' ||
1830
+ messageType === 'templateMessage'
1831
+ );
1832
+ };