@sgintokic/baileys 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of @sgintokic/baileys might be problematic. Click here for more details.

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