@boruto_vk7/baileys 1.0.0 → 1.0.2

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