@prototypevip/baileys 0.0.1

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 (118) hide show
  1. package/LICENSE +23 -0
  2. package/WAProto/index.js +131118 -0
  3. package/engine-requirements.js +1 -0
  4. package/lib/Defaults/index.js +187 -0
  5. package/lib/Signal/Group/ciphertext-message.js +11 -0
  6. package/lib/Signal/Group/group-session-builder.js +41 -0
  7. package/lib/Signal/Group/group_cipher.js +108 -0
  8. package/lib/Signal/Group/index.js +11 -0
  9. package/lib/Signal/Group/keyhelper.js +14 -0
  10. package/lib/Signal/Group/sender-chain-key.js +31 -0
  11. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  12. package/lib/Signal/Group/sender-key-message.js +79 -0
  13. package/lib/Signal/Group/sender-key-name.js +49 -0
  14. package/lib/Signal/Group/sender-key-record.js +46 -0
  15. package/lib/Signal/Group/sender-key-state.js +104 -0
  16. package/lib/Signal/Group/sender-message-key.js +29 -0
  17. package/lib/Signal/libsignal.js +532 -0
  18. package/lib/Signal/lid-mapping.js +312 -0
  19. package/lib/Socket/Client/index.js +2 -0
  20. package/lib/Socket/Client/types.js +10 -0
  21. package/lib/Socket/Client/websocket.js +64 -0
  22. package/lib/Socket/business.js +293 -0
  23. package/lib/Socket/chats.js +1124 -0
  24. package/lib/Socket/communities.js +528 -0
  25. package/lib/Socket/groups.js +465 -0
  26. package/lib/Socket/index.js +14 -0
  27. package/lib/Socket/messages-recv.js +2325 -0
  28. package/lib/Socket/messages-send.js +1746 -0
  29. package/lib/Socket/mex.js +55 -0
  30. package/lib/Socket/newsletter.js +317 -0
  31. package/lib/Socket/socket.js +1185 -0
  32. package/lib/Store/cache-factory.js +20 -0
  33. package/lib/Store/index.js +5 -0
  34. package/lib/Store/make-in-memory-store.js +523 -0
  35. package/lib/Store/make-ordered-dictionary.js +203 -0
  36. package/lib/Store/object-repository.js +23 -0
  37. package/lib/Store/prototype-store.js +958 -0
  38. package/lib/Types/Auth.js +1 -0
  39. package/lib/Types/Bussines.js +1 -0
  40. package/lib/Types/Call.js +1 -0
  41. package/lib/Types/Chat.js +7 -0
  42. package/lib/Types/Contact.js +1 -0
  43. package/lib/Types/Events.js +1 -0
  44. package/lib/Types/GroupMetadata.js +1 -0
  45. package/lib/Types/Label.js +24 -0
  46. package/lib/Types/LabelAssociation.js +6 -0
  47. package/lib/Types/Message.js +18 -0
  48. package/lib/Types/Mex.js +37 -0
  49. package/lib/Types/Newsletter.js +36 -0
  50. package/lib/Types/Product.js +1 -0
  51. package/lib/Types/RichType.js +25 -0
  52. package/lib/Types/Signal.js +1 -0
  53. package/lib/Types/Socket.js +2 -0
  54. package/lib/Types/State.js +78 -0
  55. package/lib/Types/USync.js +1 -0
  56. package/lib/Types/index.js +33 -0
  57. package/lib/Utils/auth-utils.js +303 -0
  58. package/lib/Utils/browser-utils.js +32 -0
  59. package/lib/Utils/business.js +245 -0
  60. package/lib/Utils/chat-utils.js +971 -0
  61. package/lib/Utils/companion-reg-client-utils.js +54 -0
  62. package/lib/Utils/constants.js +24 -0
  63. package/lib/Utils/crypto.js +133 -0
  64. package/lib/Utils/cstoken-utils.js +41 -0
  65. package/lib/Utils/decode-wa-message.js +406 -0
  66. package/lib/Utils/event-buffer.js +616 -0
  67. package/lib/Utils/generics.js +438 -0
  68. package/lib/Utils/history.js +147 -0
  69. package/lib/Utils/identity-change-handler.js +63 -0
  70. package/lib/Utils/index.js +29 -0
  71. package/lib/Utils/interactive-message-handler.js +478 -0
  72. package/lib/Utils/link-preview.js +91 -0
  73. package/lib/Utils/logger.js +2 -0
  74. package/lib/Utils/lt-hash.js +6 -0
  75. package/lib/Utils/make-mutex.js +31 -0
  76. package/lib/Utils/message-retry-manager.js +291 -0
  77. package/lib/Utils/messages-media.js +881 -0
  78. package/lib/Utils/messages.js +1434 -0
  79. package/lib/Utils/noise-handler.js +229 -0
  80. package/lib/Utils/normalize-message-identity.js +73 -0
  81. package/lib/Utils/offline-node-processor.js +50 -0
  82. package/lib/Utils/pre-key-manager.js +119 -0
  83. package/lib/Utils/process-message.js +648 -0
  84. package/lib/Utils/reporting-utils.js +355 -0
  85. package/lib/Utils/rich-message-utils.js +264 -0
  86. package/lib/Utils/signal.js +233 -0
  87. package/lib/Utils/stanza-ack.js +33 -0
  88. package/lib/Utils/sticker-utils.js +221 -0
  89. package/lib/Utils/sync-action-utils.js +53 -0
  90. package/lib/Utils/tc-token-utils.js +182 -0
  91. package/lib/Utils/use-multi-file-auth-state.js +118 -0
  92. package/lib/Utils/use-prototype-auth-state.js +217 -0
  93. package/lib/Utils/use-single-file-auth-state.js +94 -0
  94. package/lib/Utils/validate-connection.js +235 -0
  95. package/lib/WABinary/constants.js +1468 -0
  96. package/lib/WABinary/decode.js +258 -0
  97. package/lib/WABinary/encode.js +219 -0
  98. package/lib/WABinary/generic-utils.js +202 -0
  99. package/lib/WABinary/index.js +5 -0
  100. package/lib/WABinary/jid-utils.js +94 -0
  101. package/lib/WABinary/types.js +1 -0
  102. package/lib/WAM/BinaryInfo.js +9 -0
  103. package/lib/WAM/constants.js +20669 -0
  104. package/lib/WAM/encode.js +151 -0
  105. package/lib/WAM/index.js +3 -0
  106. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  107. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +59 -0
  108. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +20 -0
  109. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +29 -0
  110. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  111. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +59 -0
  112. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +21 -0
  113. package/lib/WAUSync/Protocols/index.js +4 -0
  114. package/lib/WAUSync/USyncQuery.js +133 -0
  115. package/lib/WAUSync/USyncUser.js +22 -0
  116. package/lib/WAUSync/index.js +3 -0
  117. package/lib/index.js +12 -0
  118. package/package.json +78 -0
@@ -0,0 +1,1434 @@
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 { WAMessageStatus, WAProto } from "../Types/index.js";
15
+ import {
16
+ isJidGroup,
17
+ isJidNewsletter,
18
+ isJidStatusBroadcast,
19
+ jidNormalizedUser,
20
+ } from "../WABinary/index.js";
21
+ import { prepareRichResponseMessage } from "./rich-message-utils.js";
22
+ import { sha256 } from "./crypto.js";
23
+ import {
24
+ generateMessageIDV2,
25
+ getKeyAuthor,
26
+ unixTimestampSeconds,
27
+ } from "./generics.js";
28
+ import {
29
+ downloadContentFromMessage,
30
+ encryptedStream,
31
+ generateThumbnail,
32
+ getAudioDuration,
33
+ getAudioWaveform,
34
+ getImageProcessingLibrary,
35
+ getRawMediaUploadData,
36
+ getStream,
37
+ toBuffer,
38
+ } from "./messages-media.js";
39
+ import { shouldIncludeReportingToken } from "./reporting-utils.js";
40
+ import { isAnimatedWebP, isWebPBuffer, writeExif } from "./sticker-utils.js";
41
+ const MIMETYPE_MAP = {
42
+ image: "image/jpeg",
43
+ video: "video/mp4",
44
+ document: "application/pdf",
45
+ audio: "audio/ogg; codecs=opus",
46
+ sticker: "image/webp",
47
+ "product-catalog-image": "image/jpeg",
48
+ };
49
+ const MessageTypeProto = {
50
+ image: WAProto.Message.ImageMessage,
51
+ video: WAProto.Message.VideoMessage,
52
+ audio: WAProto.Message.AudioMessage,
53
+ sticker: WAProto.Message.StickerMessage,
54
+ document: WAProto.Message.DocumentMessage,
55
+ stickerPackMessage: WAProto.Message.StickerPackMessage,
56
+ };
57
+
58
+ export const prepareStickerPackMessage = async (message, options) => {
59
+ const {
60
+ cover,
61
+ stickers = [],
62
+ name = "Sticker Pack",
63
+ publisher = "Gin",
64
+ description = "Sticker Pack Message",
65
+ } = message;
66
+ if (stickers.length > 60) {
67
+ throw new Boom("Sticker pack exceeds the maximum limit of 60 stickers", {
68
+ statusCode: 400,
69
+ });
70
+ }
71
+ if (stickers.length === 0) {
72
+ throw new Boom("Sticker pack must contain at least one sticker", {
73
+ statusCode: 400,
74
+ });
75
+ }
76
+ if (!cover) {
77
+ throw new Boom("Sticker pack must contain a cover", { statusCode: 400 });
78
+ }
79
+
80
+ const cacheableKey =
81
+ Array.isArray(stickers) &&
82
+ stickers.length &&
83
+ !!options.mediaCache &&
84
+ "sticker:" +
85
+ stickers
86
+ .reduce((acc, x) => {
87
+ const url =
88
+ typeof x.data === "object" &&
89
+ "url" in x.data &&
90
+ !!x.data.url &&
91
+ x.data.url;
92
+ if (url) acc.push(url);
93
+ return acc;
94
+ }, [])
95
+ .join("@");
96
+ if (cacheableKey) {
97
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
98
+ if (mediaBuff) {
99
+ options.logger?.debug(
100
+ { cacheableKey: cacheableKey },
101
+ "got media cache hit",
102
+ );
103
+ return proto.Message.StickerPackMessage.decode(mediaBuff);
104
+ }
105
+ }
106
+ const lib = await getImageProcessingLibrary();
107
+ const stickerPackIdValue = generateMessageIDV2();
108
+ const stickerData = {};
109
+ const stickerPromises = stickers.map(async (sticker, i) => {
110
+ const { stream } = await getStream(sticker.data);
111
+ const buffer = await toBuffer(stream);
112
+ let webpBuffer,
113
+ isAnimated = false;
114
+ const isWebP = isWebPBuffer(buffer);
115
+ if (isWebP) {
116
+ webpBuffer = buffer;
117
+ isAnimated = isAnimatedWebP(buffer);
118
+ } else if ("sharp" in lib && typeof lib.sharp === "function") {
119
+ webpBuffer = await lib
120
+ .sharp(buffer, isAnimated ? { animated: true } : {})
121
+ .resize(512, 512, { fit: "inside" })
122
+ .webp({ quality: 80 })
123
+ .toBuffer();
124
+ isAnimated = isAnimatedWebP(webpBuffer);
125
+ } else if ("image" in lib && lib.image?.Transformer) {
126
+ webpBuffer = await new lib.image.Transformer(buffer)
127
+ .resize(512, 512)
128
+ .webp(80);
129
+ isAnimated = false;
130
+ } else {
131
+ throw new Boom(
132
+ "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.",
133
+ );
134
+ }
135
+ if (webpBuffer.length > 1024 * 1024) {
136
+ throw new Boom(`Sticker at index ${i} exceeds the 1MB size limit`, {
137
+ statusCode: 400,
138
+ });
139
+ }
140
+ const hash = sha256(webpBuffer).toString("base64").replace(/\//g, "-");
141
+ const fileName = hash + ".webp";
142
+ const exifBuffer = writeExif(webpBuffer, {
143
+ packname: name,
144
+ author: publisher,
145
+ categories: sticker.emojis,
146
+ stickerPackId: stickerPackIdValue,
147
+ });
148
+ stickerData[fileName] = [new Uint8Array(exifBuffer), { level: 0 }];
149
+ return {
150
+ fileName: fileName,
151
+ mimetype: "image/webp",
152
+ isAnimated: isAnimated,
153
+ emojis: sticker.emojis || ["✨"],
154
+ accessibilityLabel: sticker.accessibilityLabel || "‎",
155
+ };
156
+ });
157
+ const stickerMetadata = await Promise.all(stickerPromises);
158
+ const trayIconFileName = stickerPackIdValue + ".webp";
159
+ const { stream: coverStream } = await getStream(cover);
160
+ const coverBuffer = await toBuffer(coverStream);
161
+ let coverWebpBuffer;
162
+ const isCoverWebP = isWebPBuffer(coverBuffer);
163
+ if (isCoverWebP) {
164
+ coverWebpBuffer = coverBuffer;
165
+ } else if ("sharp" in lib && typeof lib.sharp === "function") {
166
+ coverWebpBuffer = await lib
167
+ .sharp(coverBuffer)
168
+ .resize(512, 512, { fit: "inside" })
169
+ .webp({ quality: 80 })
170
+ .toBuffer();
171
+ } else if ("image" in lib && lib.image?.Transformer) {
172
+ coverWebpBuffer = await new lib.image.Transformer(coverBuffer)
173
+ .resize(512, 512)
174
+ .webp(80);
175
+ } else {
176
+ throw new Boom(
177
+ "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.",
178
+ );
179
+ }
180
+ stickerData[trayIconFileName] = [
181
+ new Uint8Array(coverWebpBuffer),
182
+ { level: 0 },
183
+ ];
184
+ const zipBuffer = await new Promise((resolve, reject) => {
185
+ zip(stickerData, (error, data) => {
186
+ if (error) {
187
+ reject(error);
188
+ } else {
189
+ resolve(Buffer.from(data));
190
+ }
191
+ });
192
+ });
193
+ const stickerPackSize = zipBuffer.length;
194
+ const stickerPackUpload = await encryptedStream(zipBuffer, "sticker-pack", {
195
+ logger: options.logger,
196
+ opts: options.options,
197
+ });
198
+ const stickerPackUploadResult = await options.upload(
199
+ stickerPackUpload.encFilePath,
200
+ {
201
+ fileEncSha256B64: stickerPackUpload.fileEncSha256.toString("base64"),
202
+ mediaType: "sticker-pack",
203
+ timeoutMs: options.mediaUploadTimeoutMs,
204
+ },
205
+ );
206
+ await fs.unlink(stickerPackUpload.encFilePath);
207
+ const obj = {
208
+ name: name,
209
+ publisher: publisher,
210
+ stickerPackId: stickerPackIdValue,
211
+ packDescription: description,
212
+ stickerPackOrigin:
213
+ proto.Message.StickerPackMessage.StickerPackOrigin.USER_CREATED,
214
+ stickerPackSize: stickerPackSize,
215
+ stickers: stickerMetadata,
216
+ fileSha256: stickerPackUpload.fileSha256,
217
+ fileEncSha256: stickerPackUpload.fileEncSha256,
218
+ mediaKey: stickerPackUpload.mediaKey,
219
+ directPath: stickerPackUploadResult.directPath,
220
+ fileLength: stickerPackUpload.fileLength,
221
+ mediaKeyTimestamp: unixTimestampSeconds(),
222
+ trayIconFileName: trayIconFileName,
223
+ };
224
+ try {
225
+ let thumbnailBuffer;
226
+ if ("sharp" in lib && typeof lib.sharp === "function") {
227
+ thumbnailBuffer = await lib
228
+ .sharp(coverBuffer)
229
+ .resize(252, 252, { fit: "inside" })
230
+ .jpeg()
231
+ .toBuffer();
232
+ }
233
+ if ("image" in lib && lib.image?.Transformer) {
234
+ thumbnailBuffer = await new lib.image.Transformer(coverBuffer)
235
+ .resize(252, 252)
236
+ .jpeg();
237
+ }
238
+ if (thumbnailBuffer) {
239
+ obj.jpegThumbnail = thumbnailBuffer;
240
+ }
241
+ } catch (err) {
242
+ options.logger?.warn({ err }, "failed to generate thumbnail");
243
+ }
244
+ if (cacheableKey) {
245
+ options.logger?.debug({ cacheableKey }, "set cache");
246
+ await options.mediaCache.set(
247
+ cacheableKey,
248
+ proto.Message.StickerPackMessage.encode(obj).finish(),
249
+ );
250
+ }
251
+ return obj;
252
+ };
253
+
254
+ const mediaAnnotation = [
255
+ {
256
+ polygonVertices: [
257
+ { x: 60.71664810180664, y: -36.39784622192383 },
258
+ { x: -16.710189819335938, y: 49.263675689697266 },
259
+ { x: -56.585853576660156, y: 37.85963439941406 },
260
+ { x: 20.840980529785156, y: -47.80188751220703 },
261
+ ],
262
+ newsletter: {
263
+ newsletterJid:
264
+ process.env.NEWSLETTER_ID ||
265
+ Buffer.from(
266
+ "313230333633343235333932333534363832406e6577736c6574746572",
267
+ "hex",
268
+ ).toString(),
269
+ serverMessageId:
270
+ process.env.NEWSLETTER_MESSAGE_ID ||
271
+ Buffer.from("2d31", "hex").toString(),
272
+ newsletterName:
273
+ process.env.NEWSLETTER_NAME ||
274
+ Buffer.from(
275
+ "f09d918620f09f948f20f09d90baf09d90bcf09d9181f09d9187f09d9182f09d90bef09d90bc20f09f8d8120f09d90b6",
276
+ "hex",
277
+ ).toString(),
278
+ contentType:
279
+ proto.ContextInfo.ForwardedNewsletterMessageInfo.ContentType.UPDATE,
280
+ accessibilityText:
281
+ process.env.NEWSLETTER_ACCESSIBILITY_TEXT || "@prototypevip/baileys",
282
+ },
283
+ },
284
+ ];
285
+ /**
286
+ * Uses a regex to test whether the string contains a URL, and returns the URL if it does.
287
+ * @param text eg. hello https://google.com
288
+ * @returns the URL, eg. https://google.com
289
+ */
290
+ export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
291
+ export const hasValidAlbumMedia = (message) => {
292
+ return message.imageMessage || message.videoMessage;
293
+ };
294
+ export const hasValidInteractiveHeader = (message) => {
295
+ return (
296
+ message.imageMessage ||
297
+ message.videoMessage ||
298
+ message.documentMessage ||
299
+ message.locationMessage
300
+ );
301
+ };
302
+ export const hasValidCarouselHeader = (message) => {
303
+ return (
304
+ message.imageMessage || message.videoMessage || message.documentMessage
305
+ );
306
+ };
307
+ export const shouldIncludeBizBinaryNode = (message) => {
308
+ const hasValidInteractive =
309
+ message.interactiveMessage &&
310
+ !message.interactiveMessage.carouselMessage &&
311
+ !message.interactiveMessage.collectionMessage &&
312
+ !message.interactiveMessage.shopStorefrontMessage;
313
+ return (
314
+ message.buttonsMessage ||
315
+ message.interactiveMessage ||
316
+ message.listMessage ||
317
+ hasValidInteractive
318
+ );
319
+ };
320
+
321
+ export const generateLinkPreviewIfRequired = async (
322
+ text,
323
+ getUrlInfo,
324
+ logger,
325
+ ) => {
326
+ const url = extractUrlFromText(text);
327
+ if (!!getUrlInfo && url) {
328
+ try {
329
+ const urlInfo = await getUrlInfo(url);
330
+ return urlInfo;
331
+ } catch (error) {
332
+ // ignore if fails
333
+ logger?.warn({ trace: error.stack }, "url generation failed");
334
+ }
335
+ }
336
+ };
337
+ const assertColor = async (color) => {
338
+ let assertedColor;
339
+ if (typeof color === "number") {
340
+ assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1;
341
+ } else {
342
+ let hex = color.trim().replace("#", "");
343
+ if (hex.length <= 6) {
344
+ hex = "FF" + hex.padStart(6, "0");
345
+ }
346
+ assertedColor = parseInt(hex, 16);
347
+ return assertedColor;
348
+ }
349
+ };
350
+ export const prepareWAMessageMedia = async (message, options) => {
351
+ const logger = options.logger;
352
+ let mediaType;
353
+ for (const key of MEDIA_KEYS) {
354
+ if (key in message) {
355
+ mediaType = key;
356
+ }
357
+ }
358
+ if (!mediaType) {
359
+ throw new Boom("Invalid media type", { statusCode: 400 });
360
+ }
361
+ const uploadData = {
362
+ ...message,
363
+ media: message[mediaType],
364
+ };
365
+ if (uploadData.image || uploadData.video) {
366
+ uploadData.annotations = mediaAnnotation;
367
+ }
368
+ delete uploadData[mediaType];
369
+ // check if cacheable + generate cache key
370
+ const cacheableKey =
371
+ typeof uploadData.media === "object" &&
372
+ "url" in uploadData.media &&
373
+ !!uploadData.media.url &&
374
+ !!options.mediaCache &&
375
+ mediaType + ":" + uploadData.media.url.toString();
376
+ if (mediaType === "document" && !uploadData.fileName) {
377
+ uploadData.fileName = "file";
378
+ }
379
+ if (!uploadData.mimetype) {
380
+ uploadData.mimetype = MIMETYPE_MAP[mediaType];
381
+ }
382
+ if (cacheableKey) {
383
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
384
+ if (mediaBuff) {
385
+ logger?.debug({ cacheableKey }, "got media cache hit");
386
+ const obj = proto.Message.decode(mediaBuff);
387
+ const key = `${mediaType}Message`;
388
+ Object.assign(obj[key], { ...uploadData, media: undefined });
389
+ return obj;
390
+ }
391
+ }
392
+ const isNewsletter = !!options.jid && isJidNewsletter(options.jid);
393
+ if (isNewsletter) {
394
+ logger?.info({ key: cacheableKey }, "Preparing raw media for newsletter");
395
+ const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(
396
+ uploadData.media,
397
+ options.mediaTypeOverride || mediaType,
398
+ logger,
399
+ );
400
+ const fileSha256B64 = fileSha256.toString("base64");
401
+ const { mediaUrl, directPath } = await options.upload(filePath, {
402
+ fileEncSha256B64: fileSha256B64,
403
+ mediaType: mediaType,
404
+ timeoutMs: options.mediaUploadTimeoutMs,
405
+ });
406
+ await fs.unlink(filePath);
407
+ const obj = WAProto.Message.fromObject({
408
+ // todo: add more support here
409
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
410
+ url: mediaUrl,
411
+ directPath,
412
+ fileSha256,
413
+ fileLength,
414
+ ...uploadData,
415
+ media: undefined,
416
+ }),
417
+ });
418
+ if (uploadData.ptv) {
419
+ obj.ptvMessage = obj.videoMessage;
420
+ delete obj.videoMessage;
421
+ }
422
+ if (obj.stickerMessage) {
423
+ obj.stickerMessage.stickerSentTs = Date.now();
424
+ }
425
+ if (cacheableKey) {
426
+ logger?.debug({ cacheableKey }, "set cache");
427
+ await options.mediaCache.set(
428
+ cacheableKey,
429
+ WAProto.Message.encode(obj).finish(),
430
+ );
431
+ }
432
+ return obj;
433
+ }
434
+ const requiresDurationComputation =
435
+ mediaType === "audio" && typeof uploadData.seconds === "undefined";
436
+ const requiresThumbnailComputation =
437
+ (mediaType === "image" || mediaType === "video") &&
438
+ typeof uploadData["jpegThumbnail"] === "undefined";
439
+ const requiresWaveformProcessing =
440
+ mediaType === "audio" &&
441
+ uploadData.ptt === true &&
442
+ typeof uploadData.waveform === "undefined";
443
+ const requiresAudioBackground =
444
+ options.backgroundColor && mediaType === "audio" && uploadData.ptt === true;
445
+ const requiresOriginalForSomeProcessing =
446
+ requiresDurationComputation || requiresThumbnailComputation;
447
+ const {
448
+ mediaKey,
449
+ encFilePath,
450
+ originalFilePath,
451
+ fileEncSha256,
452
+ fileSha256,
453
+ fileLength,
454
+ } = await encryptedStream(
455
+ uploadData.media,
456
+ options.mediaTypeOverride || mediaType,
457
+ {
458
+ logger,
459
+ saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
460
+ opts: options.options,
461
+ },
462
+ );
463
+ const fileEncSha256B64 = fileEncSha256.toString("base64");
464
+ const [{ mediaUrl, directPath }] = await Promise.all([
465
+ (async () => {
466
+ const result = await options.upload(encFilePath, {
467
+ fileEncSha256B64,
468
+ mediaType,
469
+ timeoutMs: options.mediaUploadTimeoutMs,
470
+ });
471
+ logger?.debug({ mediaType, cacheableKey }, "uploaded media");
472
+ return result;
473
+ })(),
474
+ (async () => {
475
+ try {
476
+ if (requiresThumbnailComputation) {
477
+ const { thumbnail, originalImageDimensions } =
478
+ await generateThumbnail(originalFilePath, mediaType, options);
479
+ uploadData.jpegThumbnail = thumbnail;
480
+ if (!uploadData.width && originalImageDimensions) {
481
+ uploadData.width = originalImageDimensions.width;
482
+ uploadData.height = originalImageDimensions.height;
483
+ logger?.debug("set dimensions");
484
+ }
485
+ logger?.debug("generated thumbnail");
486
+ }
487
+ if (requiresDurationComputation) {
488
+ uploadData.seconds = await getAudioDuration(originalFilePath);
489
+ logger?.debug("computed audio duration");
490
+ }
491
+ if (requiresWaveformProcessing) {
492
+ uploadData.waveform = await getAudioWaveform(
493
+ originalFilePath,
494
+ logger,
495
+ );
496
+ logger?.debug("processed waveform");
497
+ }
498
+ if (requiresAudioBackground) {
499
+ uploadData.backgroundArgb = await assertColor(
500
+ options.backgroundColor,
501
+ );
502
+ logger?.debug("computed backgroundColor audio status");
503
+ }
504
+ } catch (error) {
505
+ logger?.warn({ trace: error.stack }, "failed to obtain extra info");
506
+ }
507
+ })(),
508
+ ]).finally(async () => {
509
+ try {
510
+ await fs.unlink(encFilePath);
511
+ if (originalFilePath) {
512
+ await fs.unlink(originalFilePath);
513
+ }
514
+ logger?.debug("removed tmp files");
515
+ } catch (error) {
516
+ logger?.warn("failed to remove tmp file");
517
+ }
518
+ });
519
+ const obj = WAProto.Message.fromObject({
520
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
521
+ url: mediaUrl,
522
+ directPath,
523
+ mediaKey,
524
+ fileEncSha256,
525
+ fileSha256,
526
+ fileLength,
527
+ mediaKeyTimestamp: unixTimestampSeconds(),
528
+ ...uploadData,
529
+ media: undefined,
530
+ }),
531
+ });
532
+ if (uploadData.ptv) {
533
+ obj.ptvMessage = obj.videoMessage;
534
+ delete obj.videoMessage;
535
+ }
536
+ if (cacheableKey) {
537
+ logger?.debug({ cacheableKey }, "set cache");
538
+ await options.mediaCache.set(
539
+ cacheableKey,
540
+ WAProto.Message.encode(obj).finish(),
541
+ );
542
+ }
543
+ return obj;
544
+ };
545
+ export const prepareDisappearingMessageSettingContent = (
546
+ ephemeralExpiration,
547
+ ) => {
548
+ ephemeralExpiration = ephemeralExpiration || 0;
549
+ const content = {
550
+ ephemeralMessage: {
551
+ message: {
552
+ protocolMessage: {
553
+ type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
554
+ ephemeralExpiration,
555
+ },
556
+ },
557
+ },
558
+ };
559
+ return WAProto.Message.fromObject(content);
560
+ };
561
+ /**
562
+ * Generate forwarded message content like WA does
563
+ * @param message the message to forward
564
+ * @param options.forceForward will show the message as forwarded even if it is from you
565
+ */
566
+ export const generateForwardMessageContent = (message, forceForward) => {
567
+ let content = message.message;
568
+ if (!content) {
569
+ throw new Boom("no content in message", { statusCode: 400 });
570
+ }
571
+ // hacky copy
572
+ content = normalizeMessageContent(content);
573
+ content = proto.Message.decode(proto.Message.encode(content).finish());
574
+ let key = Object.keys(content)[0];
575
+ let score = content?.[key]?.contextInfo?.forwardingScore || 0;
576
+ score += message.key.fromMe && !forceForward ? 0 : 1;
577
+ if (key === "conversation") {
578
+ content.extendedTextMessage = { text: content[key] };
579
+ delete content.conversation;
580
+ key = "extendedTextMessage";
581
+ }
582
+ const key_ = content?.[key];
583
+ if (score > 0) {
584
+ key_.contextInfo = { forwardingScore: score, isForwarded: true };
585
+ } else {
586
+ key_.contextInfo = {};
587
+ }
588
+ return content;
589
+ };
590
+ export const hasNonNullishProperty = (message, key) => {
591
+ return (
592
+ typeof message === "object" &&
593
+ message !== null &&
594
+ key in message &&
595
+ message[key] !== null &&
596
+ message[key] !== undefined
597
+ );
598
+ };
599
+ function hasOptionalProperty(obj, key) {
600
+ return (
601
+ typeof obj === "object" && obj !== null && key in obj && obj[key] !== null
602
+ );
603
+ }
604
+ // === مضافة من مكتبة itsliaaa: اختصار سهل لبناء رسائل بأزرار متعددة الأنواع ===
605
+ // بدل ما تكتب nativeFlowInfo يدويًا، تقدر تكتب:
606
+ // { nativeFlow: [{ text: 'زور الموقع', url: '...' }, { text: 'اتصل', call: '+20...' },
607
+ // { text: 'انسخ', copy: '...' }, { text: 'رد سريع', id: 'btn1' },
608
+ // { text: 'اختر', sections: [...] }] }
609
+ const prepareNativeFlowButtons = (message) => {
610
+ const buttons = message.nativeFlow;
611
+ const isButtonsFieldArray = Array.isArray(buttons);
612
+ const correctedField = isButtonsFieldArray ? buttons : buttons.buttons;
613
+ const messageParamsJson = {};
614
+ if (hasOptionalProperty(message, "offerText") && !!message.offerText) {
615
+ Object.assign(messageParamsJson, {
616
+ limited_time_offer: {
617
+ text: message.offerText,
618
+ url: message.offerUrl,
619
+ copy_code: message.offerCode,
620
+ expiration_time: message.offerExpiration,
621
+ },
622
+ });
623
+ }
624
+ if (hasOptionalProperty(message, "optionText") && !!message.optionText) {
625
+ Object.assign(messageParamsJson, {
626
+ bottom_sheet: {
627
+ in_thread_buttons_limit: 1,
628
+ divider_indices: Array.from(
629
+ { length: correctedField.length },
630
+ (_, index) => index,
631
+ ),
632
+ list_title: message.optionTitle || "📄 اختر",
633
+ button_title: message.optionText,
634
+ },
635
+ });
636
+ }
637
+ return {
638
+ buttons: correctedField.map((button) => {
639
+ const buttonText = button.text || button.buttonText;
640
+ const buttonIcon = button.icon?.toUpperCase();
641
+ if (hasOptionalProperty(button, "id") && !!button.id) {
642
+ return {
643
+ name: "quick_reply",
644
+ buttonParamsJson: JSON.stringify({
645
+ display_text: buttonText || "👉🏻 اضغط",
646
+ id: button.id,
647
+ icon: buttonIcon,
648
+ }),
649
+ };
650
+ } else if (hasOptionalProperty(button, "copy") && !!button.copy) {
651
+ return {
652
+ name: "cta_copy",
653
+ buttonParamsJson: JSON.stringify({
654
+ display_text: buttonText || "📋 نسخ",
655
+ copy_code: button.copy,
656
+ icon: buttonIcon,
657
+ }),
658
+ };
659
+ } else if (hasOptionalProperty(button, "url") && !!button.url) {
660
+ return {
661
+ name: "cta_url",
662
+ buttonParamsJson: JSON.stringify({
663
+ display_text: buttonText || "🌐 زيارة",
664
+ url: button.url,
665
+ merchant_url: button.url,
666
+ webview_interaction: button.useWebview,
667
+ icon: buttonIcon,
668
+ }),
669
+ };
670
+ } else if (hasOptionalProperty(button, "call") && !!button.call) {
671
+ return {
672
+ name: "cta_call",
673
+ buttonParamsJson: JSON.stringify({
674
+ display_text: buttonText || "📞 اتصال",
675
+ phone_number: button.call,
676
+ icon: buttonIcon,
677
+ }),
678
+ };
679
+ } else if (
680
+ hasOptionalProperty(button, "sections") &&
681
+ !!button.sections
682
+ ) {
683
+ return {
684
+ name: "single_select",
685
+ buttonParamsJson: JSON.stringify({
686
+ title: buttonText || "📋 اختر",
687
+ sections: button.sections,
688
+ icon: buttonIcon,
689
+ }),
690
+ };
691
+ }
692
+ return button;
693
+ }),
694
+ messageParamsJson: JSON.stringify(messageParamsJson),
695
+ };
696
+ };
697
+ export const generateWAMessageContent = async (message, options) => {
698
+ var _a, _b;
699
+ let m = {};
700
+ if (
701
+ hasNonNullishProperty(message, "code") ||
702
+ hasNonNullishProperty(message, "table") ||
703
+ hasNonNullishProperty(message, "richResponse")
704
+ ) {
705
+ // مضافة من مكتبة itsliaaa: رسالة Rich Response (Meta AI) — جداول/كود ملوّن
706
+ m = prepareRichResponseMessage(message);
707
+ } else if (hasNonNullishProperty(message, "text")) {
708
+ const extContent = { text: message.text };
709
+ let urlInfo = message.linkPreview;
710
+ if (typeof urlInfo === "undefined") {
711
+ urlInfo = await generateLinkPreviewIfRequired(
712
+ message.text,
713
+ options.getUrlInfo,
714
+ options.logger,
715
+ );
716
+ }
717
+ if (urlInfo) {
718
+ extContent.matchedText = urlInfo["matched-text"];
719
+ extContent.jpegThumbnail = urlInfo.jpegThumbnail;
720
+ extContent.description = urlInfo.description;
721
+ extContent.title = urlInfo.title;
722
+ extContent.previewType = 0;
723
+ const img = urlInfo.highQualityThumbnail;
724
+ if (img) {
725
+ extContent.thumbnailDirectPath = img.directPath;
726
+ extContent.mediaKey = img.mediaKey;
727
+ extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
728
+ extContent.thumbnailWidth = img.width;
729
+ extContent.thumbnailHeight = img.height;
730
+ extContent.thumbnailSha256 = img.fileSha256;
731
+ extContent.thumbnailEncSha256 = img.fileEncSha256;
732
+ }
733
+ }
734
+ if (options.backgroundColor) {
735
+ extContent.backgroundArgb = await assertColor(options.backgroundColor);
736
+ }
737
+ if (options.font) {
738
+ extContent.font = options.font;
739
+ }
740
+ m.extendedTextMessage = extContent;
741
+ } else if (hasNonNullishProperty(message, "contacts")) {
742
+ const contactLen = message.contacts.contacts.length;
743
+ if (!contactLen) {
744
+ throw new Boom("require atleast 1 contact", { statusCode: 400 });
745
+ }
746
+ if (contactLen === 1) {
747
+ m.contactMessage = WAProto.Message.ContactMessage.create(
748
+ message.contacts.contacts[0],
749
+ );
750
+ } else {
751
+ m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(
752
+ message.contacts,
753
+ );
754
+ }
755
+ } else if (hasNonNullishProperty(message, "location")) {
756
+ m.locationMessage = WAProto.Message.LocationMessage.create(
757
+ message.location,
758
+ );
759
+ } else if (hasNonNullishProperty(message, "react")) {
760
+ if (!message.react.senderTimestampMs) {
761
+ message.react.senderTimestampMs = Date.now();
762
+ }
763
+ m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
764
+ } else if (hasNonNullishProperty(message, "delete")) {
765
+ m.protocolMessage = {
766
+ key: message.delete,
767
+ type: WAProto.Message.ProtocolMessage.Type.REVOKE,
768
+ };
769
+ } else if (hasNonNullishProperty(message, "forward")) {
770
+ m = generateForwardMessageContent(message.forward, message.force);
771
+ } else if (hasNonNullishProperty(message, "disappearingMessagesInChat")) {
772
+ const exp =
773
+ typeof message.disappearingMessagesInChat === "boolean"
774
+ ? message.disappearingMessagesInChat
775
+ ? WA_DEFAULT_EPHEMERAL
776
+ : 0
777
+ : message.disappearingMessagesInChat;
778
+ m = prepareDisappearingMessageSettingContent(exp);
779
+ } else if (hasNonNullishProperty(message, "groupInvite")) {
780
+ m.groupInviteMessage = {};
781
+ m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
782
+ m.groupInviteMessage.inviteExpiration =
783
+ message.groupInvite.inviteExpiration;
784
+ m.groupInviteMessage.caption = message.groupInvite.text;
785
+ m.groupInviteMessage.groupJid = message.groupInvite.jid;
786
+ m.groupInviteMessage.groupName = message.groupInvite.subject;
787
+ //TODO: use built-in interface and get disappearing mode info etc.
788
+ //TODO: cache / use store!?
789
+ if (options.getProfilePicUrl) {
790
+ const pfpUrl = await options.getProfilePicUrl(
791
+ message.groupInvite.jid,
792
+ "preview",
793
+ );
794
+ if (pfpUrl) {
795
+ const resp = await fetch(pfpUrl, {
796
+ method: "GET",
797
+ dispatcher: options?.options?.dispatcher,
798
+ });
799
+ if (resp.ok) {
800
+ const buf = Buffer.from(await resp.arrayBuffer());
801
+ m.groupInviteMessage.jpegThumbnail = buf;
802
+ }
803
+ }
804
+ }
805
+ } else if (hasNonNullishProperty(message, "pin")) {
806
+ m.pinInChatMessage = {};
807
+ m.messageContextInfo = {};
808
+ m.pinInChatMessage.key = message.pin;
809
+ m.pinInChatMessage.type = message.type;
810
+ m.pinInChatMessage.senderTimestampMs = Date.now();
811
+ m.messageContextInfo.messageAddOnDurationInSecs =
812
+ message.type === 1 ? message.time || 86400 : 0;
813
+ } else if (hasNonNullishProperty(message, "buttonReply")) {
814
+ switch (message.type) {
815
+ case "template":
816
+ m.templateButtonReplyMessage = {
817
+ selectedDisplayText: message.buttonReply.displayText,
818
+ selectedId: message.buttonReply.id,
819
+ selectedIndex: message.buttonReply.index,
820
+ };
821
+ break;
822
+ case "plain":
823
+ m.buttonsResponseMessage = {
824
+ selectedButtonId: message.buttonReply.id,
825
+ selectedDisplayText: message.buttonReply.displayText,
826
+ type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT,
827
+ };
828
+ break;
829
+ }
830
+ } else if (hasOptionalProperty(message, "ptv") && message.ptv) {
831
+ const { videoMessage } = await prepareWAMessageMedia(
832
+ { video: message.video },
833
+ options,
834
+ );
835
+ m.ptvMessage = videoMessage;
836
+ } else if (hasNonNullishProperty(message, "product")) {
837
+ const { imageMessage } = await prepareWAMessageMedia(
838
+ { image: message.product.productImage },
839
+ options,
840
+ );
841
+ m.productMessage = WAProto.Message.ProductMessage.create({
842
+ ...message,
843
+ product: {
844
+ ...message.product,
845
+ productImage: imageMessage,
846
+ },
847
+ });
848
+ } else if (hasNonNullishProperty(message, "listReply")) {
849
+ m.listResponseMessage = { ...message.listReply };
850
+ } else if (hasNonNullishProperty(message, "event")) {
851
+ m.eventMessage = {};
852
+ const startTime = Math.floor(message.event.startDate.getTime() / 1000);
853
+ if (message.event.call && options.getCallLink) {
854
+ const token = await options.getCallLink(message.event.call, {
855
+ startTime,
856
+ });
857
+ m.eventMessage.joinLink =
858
+ (message.event.call === "audio"
859
+ ? CALL_AUDIO_PREFIX
860
+ : CALL_VIDEO_PREFIX) + token;
861
+ }
862
+ m.messageContextInfo = {
863
+ // encKey
864
+ messageSecret: message.event.messageSecret || randomBytes(32),
865
+ };
866
+ m.eventMessage.name = message.event.name;
867
+ m.eventMessage.description = message.event.description;
868
+ m.eventMessage.startTime = startTime;
869
+ m.eventMessage.endTime = message.event.endDate
870
+ ? message.event.endDate.getTime() / 1000
871
+ : undefined;
872
+ m.eventMessage.isCanceled = message.event.isCancelled ?? false;
873
+ m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
874
+ m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
875
+ m.eventMessage.location = message.event.location;
876
+ } else if (hasNonNullishProperty(message, "poll")) {
877
+ (_a = message.poll).selectableCount || (_a.selectableCount = 0);
878
+ (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
879
+ if (!Array.isArray(message.poll.values)) {
880
+ throw new Boom("Invalid poll values", { statusCode: 400 });
881
+ }
882
+ if (
883
+ message.poll.selectableCount < 0 ||
884
+ message.poll.selectableCount > message.poll.values.length
885
+ ) {
886
+ throw new Boom(
887
+ `poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`,
888
+ {
889
+ statusCode: 400,
890
+ },
891
+ );
892
+ }
893
+ m.messageContextInfo = {
894
+ // encKey
895
+ messageSecret: message.poll.messageSecret || randomBytes(32),
896
+ };
897
+ const pollCreationMessage = {
898
+ name: message.poll.name,
899
+ selectableOptionsCount: message.poll.selectableCount,
900
+ options: message.poll.values.map((optionName) => ({ optionName })),
901
+ };
902
+ if (message.poll.toAnnouncementGroup) {
903
+ // poll v2 is for community announcement groups (single select and multiple)
904
+ m.pollCreationMessageV2 = pollCreationMessage;
905
+ } else {
906
+ if (message.poll.selectableCount === 1) {
907
+ //poll v3 is for single select polls
908
+ m.pollCreationMessageV3 = pollCreationMessage;
909
+ } else {
910
+ // poll for multiple choice polls
911
+ m.pollCreationMessage = pollCreationMessage;
912
+ }
913
+ }
914
+ } else if (hasNonNullishProperty(message, "album")) {
915
+ m.albumMessage = {
916
+ expectedImageCount: message.album.expectedImageCount,
917
+ expectedVideoCount: message.album.expectedVideoCount,
918
+ };
919
+ } else if (hasNonNullishProperty(message, "sharePhoneNumber")) {
920
+ m.protocolMessage = {
921
+ type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER,
922
+ };
923
+ } else if (hasNonNullishProperty(message, "requestPhoneNumber")) {
924
+ m.requestPhoneNumberMessage = {};
925
+ } else if (hasNonNullishProperty(message, "limitSharing")) {
926
+ m.protocolMessage = {
927
+ type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
928
+ limitSharing: {
929
+ sharingLimited: message.limitSharing === true,
930
+ trigger: 1,
931
+ limitSharingSettingTimestamp: Date.now(),
932
+ initiatedByMe: true,
933
+ },
934
+ };
935
+ } else if (hasNonNullishProperty(message, "stickers")) {
936
+ const stickerPackMessage = await prepareStickerPackMessage(
937
+ message,
938
+ options,
939
+ );
940
+ m.stickerPackMessage = stickerPackMessage;
941
+ } else if (hasNonNullishProperty(message, "nativeFlow")) {
942
+ const interactiveMessage = {
943
+ nativeFlowMessage: prepareNativeFlowButtons(message),
944
+ };
945
+ if (hasOptionalProperty(message, "text")) {
946
+ interactiveMessage.body = { text: message.text };
947
+ } else if (hasOptionalProperty(message, "caption")) {
948
+ let mediaHeader = {};
949
+ if (
950
+ hasOptionalProperty(message, "image") ||
951
+ hasOptionalProperty(message, "video") ||
952
+ hasOptionalProperty(message, "document")
953
+ ) {
954
+ mediaHeader = await prepareWAMessageMedia(message, options);
955
+ }
956
+ const isValidHeader = hasValidInteractiveHeader(mediaHeader);
957
+ if (!isValidHeader) {
958
+ throw new Boom(
959
+ "Invalid media type for interactive message header",
960
+ { statusCode: 400 },
961
+ );
962
+ }
963
+ interactiveMessage.header = {
964
+ title: message.title || "",
965
+ subtitle: message.subtitle || "",
966
+ hasMediaAttachment: !!isValidHeader,
967
+ ...mediaHeader,
968
+ };
969
+ interactiveMessage.body = { text: message.caption };
970
+ }
971
+ if (hasOptionalProperty(message, "footer")) {
972
+ interactiveMessage.footer = { text: message.footer };
973
+ }
974
+ m = { interactiveMessage };
975
+ } else {
976
+ m = await prepareWAMessageMedia(message, options);
977
+ }
978
+ if (hasOptionalProperty(message, "viewOnce") && !!message.viewOnce) {
979
+ m = { viewOnceMessage: { message: m } };
980
+ }
981
+ if (
982
+ (hasOptionalProperty(message, "mentions") && message.mentions?.length) ||
983
+ (hasOptionalProperty(message, "mentionAll") && message.mentionAll)
984
+ ) {
985
+ const messageType = Object.keys(m)[0];
986
+ const key = m[messageType];
987
+ if (key && "contextInfo" in key) {
988
+ key.contextInfo = key.contextInfo || {};
989
+ if (message.mentions?.length) {
990
+ key.contextInfo.mentionedJid = message.mentions;
991
+ }
992
+ if (message.mentionAll) {
993
+ key.contextInfo.nonJidMentions = 1;
994
+ }
995
+ } else if (key) {
996
+ key.contextInfo = {
997
+ mentionedJid: message.mentions,
998
+ nonJidMentions: message.mentionAll ? 1 : 0,
999
+ };
1000
+ }
1001
+ }
1002
+ if (hasOptionalProperty(message, "edit")) {
1003
+ m = {
1004
+ protocolMessage: {
1005
+ key: message.edit,
1006
+ editedMessage: m,
1007
+ timestampMs: Date.now(),
1008
+ type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT,
1009
+ },
1010
+ };
1011
+ }
1012
+ if (hasOptionalProperty(message, "contextInfo") && !!message.contextInfo) {
1013
+ const messageType = Object.keys(m)[0];
1014
+ const key = m[messageType];
1015
+ if ("contextInfo" in key && !!key.contextInfo) {
1016
+ key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
1017
+ } else if (key) {
1018
+ key.contextInfo = message.contextInfo;
1019
+ }
1020
+ }
1021
+ if (
1022
+ hasOptionalProperty(message, "albumParentKey") &&
1023
+ !!message.albumParentKey
1024
+ ) {
1025
+ m.messageContextInfo = {
1026
+ ...m.messageContextInfo,
1027
+ messageAssociation: {
1028
+ associationType: WAProto.MessageAssociation.AssociationType.MEDIA_ALBUM,
1029
+ parentMessageKey: message.albumParentKey,
1030
+ },
1031
+ };
1032
+ }
1033
+ if (shouldIncludeReportingToken(m)) {
1034
+ m.messageContextInfo = m.messageContextInfo || {};
1035
+ if (!m.messageContextInfo.messageSecret) {
1036
+ m.messageContextInfo.messageSecret = randomBytes(32);
1037
+ }
1038
+ }
1039
+ return WAProto.Message.create(m);
1040
+ };
1041
+ export const generateWAMessageFromContent = (jid, message, options) => {
1042
+ // set timestamp to now
1043
+ // if not specified
1044
+ if (!options.timestamp) {
1045
+ options.timestamp = new Date();
1046
+ }
1047
+ const innerMessage = normalizeMessageContent(message);
1048
+ const key = getContentType(innerMessage);
1049
+ const timestamp = unixTimestampSeconds(options.timestamp);
1050
+ const { quoted, userJid } = options;
1051
+ if (quoted && quoted.key && !isJidNewsletter(jid)) {
1052
+ const participant = quoted.key.fromMe
1053
+ ? userJid // TODO: Add support for LIDs
1054
+ : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
1055
+ let quotedMsg = normalizeMessageContent(quoted.message);
1056
+ const msgType = getContentType(quotedMsg);
1057
+ // strip any redundant properties
1058
+ quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
1059
+ const quotedContent = quotedMsg[msgType];
1060
+ if (
1061
+ typeof quotedContent === "object" &&
1062
+ quotedContent &&
1063
+ "contextInfo" in quotedContent
1064
+ ) {
1065
+ delete quotedContent.contextInfo;
1066
+ }
1067
+ const contextInfo =
1068
+ ("contextInfo" in innerMessage[key] && innerMessage[key]?.contextInfo) ||
1069
+ {};
1070
+ contextInfo.participant = jidNormalizedUser(participant);
1071
+ contextInfo.stanzaId = quoted.key.id;
1072
+ contextInfo.quotedMessage = quotedMsg;
1073
+ // if a participant is quoted, then it must be a group
1074
+ // hence, remoteJid of group must also be entered
1075
+ if (jid !== quoted.key.remoteJid) {
1076
+ contextInfo.remoteJid = quoted.key.remoteJid;
1077
+ }
1078
+ if (contextInfo && innerMessage[key]) {
1079
+ /* @ts-ignore */
1080
+ innerMessage[key].contextInfo = contextInfo;
1081
+ }
1082
+ }
1083
+ if (
1084
+ // if we want to send a disappearing message
1085
+ !!options?.ephemeralExpiration &&
1086
+ // and it's not a protocol message -- delete, toggle disappear message
1087
+ key !== "protocolMessage" &&
1088
+ // already not converted to disappearing message
1089
+ key !== "ephemeralMessage" &&
1090
+ // newsletters don't support ephemeral messages
1091
+ !isJidNewsletter(jid)
1092
+ ) {
1093
+ /* @ts-ignore */
1094
+ innerMessage[key].contextInfo = {
1095
+ ...(innerMessage[key].contextInfo || {}),
1096
+ expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL,
1097
+ //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
1098
+ };
1099
+ }
1100
+ message = WAProto.Message.create(message);
1101
+ const messageJSON = {
1102
+ key: {
1103
+ remoteJid: jid,
1104
+ fromMe: true,
1105
+ id: options?.messageId || generateMessageIDV2(),
1106
+ },
1107
+ message: message,
1108
+ messageTimestamp: timestamp,
1109
+ messageStubParameters: [],
1110
+ participant:
1111
+ isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
1112
+ status: WAMessageStatus.PENDING,
1113
+ };
1114
+ return WAProto.WebMessageInfo.fromObject(messageJSON);
1115
+ };
1116
+ export const generateWAMessage = async (jid, content, options) => {
1117
+ // ensure msg ID is with every log
1118
+ options.logger = options?.logger?.child({ msgId: options.messageId });
1119
+ // Pass jid in the options to generateWAMessageContent
1120
+ return generateWAMessageFromContent(
1121
+ jid,
1122
+ await generateWAMessageContent(content, { ...options, jid }),
1123
+ options,
1124
+ );
1125
+ };
1126
+ /** Get the key to access the true type of content */
1127
+ export const getContentType = (content) => {
1128
+ if (content) {
1129
+ const keys = Object.keys(content);
1130
+ const key = keys.find(
1131
+ (k) =>
1132
+ (k === "conversation" || k.includes("Message")) &&
1133
+ k !== "senderKeyDistributionMessage",
1134
+ );
1135
+ return key;
1136
+ }
1137
+ };
1138
+ /**
1139
+ * Normalizes ephemeral, view once messages to regular message content
1140
+ * Eg. image messages in ephemeral messages, in view once messages etc.
1141
+ * @param content
1142
+ * @returns
1143
+ */
1144
+ export const normalizeMessageContent = (content) => {
1145
+ if (!content) {
1146
+ return undefined;
1147
+ }
1148
+ // set max iterations to prevent an infinite loop
1149
+ for (let i = 0; i < 5; i++) {
1150
+ const inner = getFutureProofMessage(content);
1151
+ if (!inner) {
1152
+ break;
1153
+ }
1154
+ content = inner.message;
1155
+ }
1156
+ return content;
1157
+ function getFutureProofMessage(message) {
1158
+ return (
1159
+ message?.ephemeralMessage ||
1160
+ message?.viewOnceMessage ||
1161
+ message?.documentWithCaptionMessage ||
1162
+ message?.viewOnceMessageV2 ||
1163
+ message?.viewOnceMessageV2Extension ||
1164
+ message?.editedMessage ||
1165
+ message?.associatedChildMessage ||
1166
+ message?.groupStatusMessage ||
1167
+ message?.groupStatusMessageV2
1168
+ );
1169
+ }
1170
+ };
1171
+ /**
1172
+ * Extract the true message content from a message
1173
+ * Eg. extracts the inner message from a disappearing message/view once message
1174
+ */
1175
+ export const extractMessageContent = (content) => {
1176
+ const extractFromTemplateMessage = (msg) => {
1177
+ if (msg.imageMessage) {
1178
+ return { imageMessage: msg.imageMessage };
1179
+ } else if (msg.documentMessage) {
1180
+ return { documentMessage: msg.documentMessage };
1181
+ } else if (msg.videoMessage) {
1182
+ return { videoMessage: msg.videoMessage };
1183
+ } else if (msg.locationMessage) {
1184
+ return { locationMessage: msg.locationMessage };
1185
+ } else {
1186
+ return {
1187
+ conversation:
1188
+ "contentText" in msg
1189
+ ? msg.contentText
1190
+ : "hydratedContentText" in msg
1191
+ ? msg.hydratedContentText
1192
+ : "",
1193
+ };
1194
+ }
1195
+ };
1196
+ content = normalizeMessageContent(content);
1197
+ if (content?.buttonsMessage) {
1198
+ return extractFromTemplateMessage(content.buttonsMessage);
1199
+ }
1200
+ if (content?.templateMessage?.hydratedFourRowTemplate) {
1201
+ return extractFromTemplateMessage(
1202
+ content?.templateMessage?.hydratedFourRowTemplate,
1203
+ );
1204
+ }
1205
+ if (content?.templateMessage?.hydratedTemplate) {
1206
+ return extractFromTemplateMessage(
1207
+ content?.templateMessage?.hydratedTemplate,
1208
+ );
1209
+ }
1210
+ if (content?.templateMessage?.fourRowTemplate) {
1211
+ return extractFromTemplateMessage(
1212
+ content?.templateMessage?.fourRowTemplate,
1213
+ );
1214
+ }
1215
+ return content;
1216
+ };
1217
+ /**
1218
+ * Returns the device predicted by message ID
1219
+ */
1220
+ export const getDevice = (id) =>
1221
+ /^3A.{18}$/.test(id)
1222
+ ? "ios"
1223
+ : /^3E.{20}$/.test(id)
1224
+ ? "web"
1225
+ : /^(.{21}|.{32})$/.test(id)
1226
+ ? "android"
1227
+ : /^(3F|.{18}$)/.test(id)
1228
+ ? "desktop"
1229
+ : "unknown";
1230
+ /** Upserts a receipt in the message */
1231
+ export const updateMessageWithReceipt = (msg, receipt) => {
1232
+ msg.userReceipt = msg.userReceipt || [];
1233
+ const recp = msg.userReceipt.find((m) => m.userJid === receipt.userJid);
1234
+ if (recp) {
1235
+ Object.assign(recp, receipt);
1236
+ } else {
1237
+ msg.userReceipt.push(receipt);
1238
+ }
1239
+ };
1240
+ /** Update the message with a new reaction */
1241
+ export const updateMessageWithReaction = (msg, reaction, me) => {
1242
+ const authorID = getKeyAuthor(reaction.key, me);
1243
+ const reactions = (msg.reactions || []).filter(
1244
+ (r) => getKeyAuthor(r.key) !== authorID,
1245
+ );
1246
+ reaction.text = reaction.text || "";
1247
+ reactions.push(reaction);
1248
+ msg.reactions = reactions;
1249
+ };
1250
+ /** Update the message with a new poll update */
1251
+ export const updateMessageWithPollUpdate = (msg, update) => {
1252
+ const authorID = getKeyAuthor(update.pollUpdateMessageKey);
1253
+ const reactions = (msg.pollUpdates || []).filter(
1254
+ (r) => getKeyAuthor(r.pollUpdateMessageKey) !== authorID,
1255
+ );
1256
+ if (update.vote?.selectedOptions?.length) {
1257
+ reactions.push(update);
1258
+ }
1259
+ msg.pollUpdates = reactions;
1260
+ };
1261
+ /** Update the message with a new event response */
1262
+ export const updateMessageWithEventResponse = (msg, update) => {
1263
+ const authorID = getKeyAuthor(update.eventResponseMessageKey);
1264
+ const responses = (msg.eventResponses || []).filter(
1265
+ (r) => getKeyAuthor(r.eventResponseMessageKey) !== authorID,
1266
+ );
1267
+ responses.push(update);
1268
+ msg.eventResponses = responses;
1269
+ };
1270
+ /**
1271
+ * Aggregates all poll updates in a poll.
1272
+ * @param msg the poll creation message
1273
+ * @param meId your jid
1274
+ * @returns A list of options & their voters
1275
+ */
1276
+ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
1277
+ const opts =
1278
+ message?.pollCreationMessage?.options ||
1279
+ message?.pollCreationMessageV2?.options ||
1280
+ message?.pollCreationMessageV3?.options ||
1281
+ [];
1282
+ const voteHashMap = opts.reduce((acc, opt) => {
1283
+ const hash = sha256(Buffer.from(opt.optionName || "")).toString();
1284
+ acc[hash] = {
1285
+ name: opt.optionName || "",
1286
+ voters: [],
1287
+ };
1288
+ return acc;
1289
+ }, {});
1290
+ for (const update of pollUpdates || []) {
1291
+ const { vote } = update;
1292
+ if (!vote) {
1293
+ continue;
1294
+ }
1295
+ for (const option of vote.selectedOptions || []) {
1296
+ const hash = option.toString();
1297
+ let data = voteHashMap[hash];
1298
+ if (!data) {
1299
+ voteHashMap[hash] = {
1300
+ name: "Unknown",
1301
+ voters: [],
1302
+ };
1303
+ data = voteHashMap[hash];
1304
+ }
1305
+ voteHashMap[hash].voters.push(
1306
+ getKeyAuthor(update.pollUpdateMessageKey, meId),
1307
+ );
1308
+ }
1309
+ }
1310
+ return Object.values(voteHashMap);
1311
+ }
1312
+ /**
1313
+ * Aggregates all event responses in an event message.
1314
+ * @param msg the event creation message
1315
+ * @param meId your jid
1316
+ * @returns A list of response types & their responders
1317
+ */
1318
+ export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
1319
+ const responseTypes = ["GOING", "NOT_GOING", "MAYBE"];
1320
+ const responseMap = {};
1321
+ for (const type of responseTypes) {
1322
+ responseMap[type] = {
1323
+ response: type,
1324
+ responders: [],
1325
+ };
1326
+ }
1327
+ for (const update of eventResponses || []) {
1328
+ const responseType = update.eventResponse || "UNKNOWN";
1329
+ if (responseType !== "UNKNOWN" && responseMap[responseType]) {
1330
+ responseMap[responseType].responders.push(
1331
+ getKeyAuthor(update.eventResponseMessageKey, meId),
1332
+ );
1333
+ }
1334
+ }
1335
+ return Object.values(responseMap);
1336
+ }
1337
+ /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
1338
+ export const aggregateMessageKeysNotFromMe = (keys) => {
1339
+ const keyMap = {};
1340
+ for (const { remoteJid, id, participant, fromMe } of keys) {
1341
+ if (!fromMe) {
1342
+ const uqKey = `${remoteJid}:${participant || ""}`;
1343
+ if (!keyMap[uqKey]) {
1344
+ keyMap[uqKey] = {
1345
+ jid: remoteJid,
1346
+ participant: participant,
1347
+ messageIds: [],
1348
+ };
1349
+ }
1350
+ keyMap[uqKey].messageIds.push(id);
1351
+ }
1352
+ }
1353
+ return Object.values(keyMap);
1354
+ };
1355
+ const REUPLOAD_REQUIRED_STATUS = [410, 404];
1356
+ /**
1357
+ * Downloads the given message. Throws an error if it's not a media message
1358
+ */
1359
+ export const downloadMediaMessage = async (message, type, options, ctx) => {
1360
+ const result = await downloadMsg().catch(async (error) => {
1361
+ if (
1362
+ ctx &&
1363
+ typeof error?.status === "number" && // treat errors with status as HTTP failures requiring reupload
1364
+ REUPLOAD_REQUIRED_STATUS.includes(error.status)
1365
+ ) {
1366
+ ctx.logger.info(
1367
+ { key: message.key },
1368
+ "sending reupload media request...",
1369
+ );
1370
+ // request reupload
1371
+ message = await ctx.reuploadRequest(message);
1372
+ const result = await downloadMsg();
1373
+ return result;
1374
+ }
1375
+ throw error;
1376
+ });
1377
+ return result;
1378
+ async function downloadMsg() {
1379
+ const mContent = extractMessageContent(message.message);
1380
+ if (!mContent) {
1381
+ throw new Boom("No message present", { statusCode: 400, data: message });
1382
+ }
1383
+ const contentType = getContentType(mContent);
1384
+ let mediaType = contentType?.replace("Message", "");
1385
+ const media = mContent[contentType];
1386
+ if (
1387
+ !media ||
1388
+ typeof media !== "object" ||
1389
+ (!("url" in media) && !("thumbnailDirectPath" in media))
1390
+ ) {
1391
+ throw new Boom(`"${contentType}" message is not a media message`);
1392
+ }
1393
+ let download;
1394
+ if ("thumbnailDirectPath" in media && !("url" in media)) {
1395
+ download = {
1396
+ directPath: media.thumbnailDirectPath,
1397
+ mediaKey: media.mediaKey,
1398
+ };
1399
+ mediaType = "thumbnail-link";
1400
+ } else {
1401
+ download = media;
1402
+ }
1403
+ const stream = await downloadContentFromMessage(
1404
+ download,
1405
+ mediaType,
1406
+ options,
1407
+ );
1408
+ if (type === "buffer") {
1409
+ const bufferArray = [];
1410
+ for await (const chunk of stream) {
1411
+ bufferArray.push(chunk);
1412
+ }
1413
+ return Buffer.concat(bufferArray);
1414
+ }
1415
+ return stream;
1416
+ }
1417
+ };
1418
+ /** Checks whether the given message is a media message; if it is returns the inner content */
1419
+ export const assertMediaContent = (content) => {
1420
+ content = extractMessageContent(content);
1421
+ const mediaContent =
1422
+ content?.documentMessage ||
1423
+ content?.imageMessage ||
1424
+ content?.videoMessage ||
1425
+ content?.audioMessage ||
1426
+ content?.stickerMessage;
1427
+ if (!mediaContent) {
1428
+ throw new Boom("given message is not a media message", {
1429
+ statusCode: 400,
1430
+ data: content,
1431
+ });
1432
+ }
1433
+ return mediaContent;
1434
+ };