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