@codexverified/baileys 2.7.5

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