@crysnovax/baileys 2.6.3 → 2.6.5

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