@vanzxy/baileys 1.0.1 → 1.0.3

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