@rizzkezik/bails 6.1.0

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 (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +535 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +6902 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.d.ts +79257 -0
  7. package/WAProto/index.js +242946 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/index.js +130 -0
  10. package/lib/Signal/Group/ciphertext-message.js +12 -0
  11. package/lib/Signal/Group/group-session-builder.js +30 -0
  12. package/lib/Signal/Group/group_cipher.js +82 -0
  13. package/lib/Signal/Group/index.js +12 -0
  14. package/lib/Signal/Group/keyhelper.js +18 -0
  15. package/lib/Signal/Group/sender-chain-key.js +26 -0
  16. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  17. package/lib/Signal/Group/sender-key-message.js +66 -0
  18. package/lib/Signal/Group/sender-key-name.js +48 -0
  19. package/lib/Signal/Group/sender-key-record.js +41 -0
  20. package/lib/Signal/Group/sender-key-state.js +84 -0
  21. package/lib/Signal/Group/sender-message-key.js +26 -0
  22. package/lib/Signal/libsignal.js +431 -0
  23. package/lib/Signal/lid-mapping.js +277 -0
  24. package/lib/Socket/Client/index.js +3 -0
  25. package/lib/Socket/Client/types.js +11 -0
  26. package/lib/Socket/Client/websocket.js +54 -0
  27. package/lib/Socket/business.js +379 -0
  28. package/lib/Socket/chats.js +1193 -0
  29. package/lib/Socket/communities.js +431 -0
  30. package/lib/Socket/groups.js +374 -0
  31. package/lib/Socket/index.js +12 -0
  32. package/lib/Socket/luxu.js +387 -0
  33. package/lib/Socket/messages-recv.js +1916 -0
  34. package/lib/Socket/messages-send.js +1435 -0
  35. package/lib/Socket/mex.js +42 -0
  36. package/lib/Socket/newsletter.js +270 -0
  37. package/lib/Socket/socket.js +967 -0
  38. package/lib/Store/index.js +10 -0
  39. package/lib/Store/keyed-db.js +108 -0
  40. package/lib/Store/make-cache-manager-store.js +85 -0
  41. package/lib/Store/make-in-memory-store.js +198 -0
  42. package/lib/Store/make-ordered-dictionary.js +75 -0
  43. package/lib/Store/object-repository.js +32 -0
  44. package/lib/Types/Auth.js +2 -0
  45. package/lib/Types/Bussines.js +2 -0
  46. package/lib/Types/Call.js +2 -0
  47. package/lib/Types/Chat.js +8 -0
  48. package/lib/Types/Contact.js +2 -0
  49. package/lib/Types/Events.js +2 -0
  50. package/lib/Types/GroupMetadata.js +2 -0
  51. package/lib/Types/Label.js +25 -0
  52. package/lib/Types/LabelAssociation.js +7 -0
  53. package/lib/Types/Message.js +11 -0
  54. package/lib/Types/Mex.js +37 -0
  55. package/lib/Types/Product.js +2 -0
  56. package/lib/Types/Signal.js +2 -0
  57. package/lib/Types/Socket.js +3 -0
  58. package/lib/Types/State.js +56 -0
  59. package/lib/Types/USync.js +2 -0
  60. package/lib/Types/index.js +26 -0
  61. package/lib/Utils/auth-utils.js +302 -0
  62. package/lib/Utils/browser-utils.js +48 -0
  63. package/lib/Utils/business.js +231 -0
  64. package/lib/Utils/chat-utils.js +872 -0
  65. package/lib/Utils/companion-reg-client-utils.js +35 -0
  66. package/lib/Utils/crypto.js +118 -0
  67. package/lib/Utils/decode-wa-message.js +350 -0
  68. package/lib/Utils/event-buffer.js +622 -0
  69. package/lib/Utils/generics.js +403 -0
  70. package/lib/Utils/history.js +134 -0
  71. package/lib/Utils/identity-change-handler.js +50 -0
  72. package/lib/Utils/index.js +23 -0
  73. package/lib/Utils/link-preview.js +85 -0
  74. package/lib/Utils/logger.js +3 -0
  75. package/lib/Utils/lt-hash.js +8 -0
  76. package/lib/Utils/make-mutex.js +33 -0
  77. package/lib/Utils/message-composer.js +273 -0
  78. package/lib/Utils/message-retry-manager.js +265 -0
  79. package/lib/Utils/messages-media.js +788 -0
  80. package/lib/Utils/messages.js +1253 -0
  81. package/lib/Utils/noise-handler.js +201 -0
  82. package/lib/Utils/offline-node-processor.js +40 -0
  83. package/lib/Utils/pre-key-manager.js +106 -0
  84. package/lib/Utils/process-message.js +630 -0
  85. package/lib/Utils/reporting-utils.js +258 -0
  86. package/lib/Utils/signal.js +201 -0
  87. package/lib/Utils/stanza-ack.js +38 -0
  88. package/lib/Utils/sync-action-utils.js +49 -0
  89. package/lib/Utils/tc-token-utils.js +163 -0
  90. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  91. package/lib/Utils/validate-connection.js +203 -0
  92. package/lib/WABinary/constants.js +1301 -0
  93. package/lib/WABinary/decode.js +262 -0
  94. package/lib/WABinary/encode.js +220 -0
  95. package/lib/WABinary/generic-utils.js +204 -0
  96. package/lib/WABinary/index.js +6 -0
  97. package/lib/WABinary/jid-utils.js +98 -0
  98. package/lib/WABinary/types.js +2 -0
  99. package/lib/WAM/BinaryInfo.js +10 -0
  100. package/lib/WAM/constants.js +22853 -0
  101. package/lib/WAM/encode.js +150 -0
  102. package/lib/WAM/index.js +4 -0
  103. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  104. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  105. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  106. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  107. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  108. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  109. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  110. package/lib/WAUSync/Protocols/index.js +6 -0
  111. package/lib/WAUSync/USyncQuery.js +98 -0
  112. package/lib/WAUSync/USyncUser.js +31 -0
  113. package/lib/WAUSync/index.js +4 -0
  114. package/lib/index.js +31 -0
  115. package/package.json +143 -0
@@ -0,0 +1,1253 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { randomUUID, randomBytes } from 'crypto';
3
+ import { promises as fs } from 'fs';
4
+ import {} from 'stream';
5
+ import { proto } from '../../WAProto/index.js';
6
+ import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
7
+ import { WAMessageStatus, WAProto } from '../Types/index.js';
8
+ import { isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
9
+ import { sha256 } from './crypto.js';
10
+ import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
11
+ import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, getRawMediaUploadData } from './messages-media.js';
12
+ import { shouldIncludeReportingToken } from './reporting-utils.js';
13
+ const MIMETYPE_MAP = {
14
+ image: 'image/jpeg',
15
+ video: 'video/mp4',
16
+ document: 'application/pdf',
17
+ audio: 'audio/ogg; codecs=opus',
18
+ sticker: 'image/webp',
19
+ 'product-catalog-image': 'image/jpeg'
20
+ };
21
+ const MessageTypeProto = {
22
+ image: WAProto.Message.ImageMessage,
23
+ video: WAProto.Message.VideoMessage,
24
+ audio: WAProto.Message.AudioMessage,
25
+ sticker: WAProto.Message.StickerMessage,
26
+ document: WAProto.Message.DocumentMessage
27
+ };
28
+ const ButtonType = proto.Message.ButtonsMessage.HeaderType;
29
+ const RICH_RESPONSE_CODE_KEYWORDS = new Set([
30
+ 'break',
31
+ 'case',
32
+ 'catch',
33
+ 'continue',
34
+ 'debugger',
35
+ 'default',
36
+ 'delete',
37
+ 'do',
38
+ 'else',
39
+ 'finally',
40
+ 'for',
41
+ 'function',
42
+ 'if',
43
+ 'in',
44
+ 'instanceof',
45
+ 'new',
46
+ 'return',
47
+ 'switch',
48
+ 'this',
49
+ 'throw',
50
+ 'try',
51
+ 'typeof',
52
+ 'var',
53
+ 'void',
54
+ 'while',
55
+ 'with',
56
+ 'true',
57
+ 'false',
58
+ 'null',
59
+ 'undefined',
60
+ 'NaN',
61
+ 'Infinity',
62
+ 'class',
63
+ 'const',
64
+ 'let',
65
+ 'super',
66
+ 'extends',
67
+ 'export',
68
+ 'import',
69
+ 'yield',
70
+ 'static',
71
+ 'constructor',
72
+ 'of',
73
+ 'async',
74
+ 'await',
75
+ 'get',
76
+ 'set',
77
+ 'implements',
78
+ 'interface',
79
+ 'package',
80
+ 'private',
81
+ 'protected',
82
+ 'public',
83
+ 'enum',
84
+ 'throws',
85
+ 'transient'
86
+ ])
87
+ const tokenizeCode = code => {
88
+ const tokens = []
89
+ let i = 0
90
+ const len = code.length
91
+ while (i < len) {
92
+ if (/\s/.test(code[i])) {
93
+ const start = i
94
+ while (i < len && /\s/.test(code[i])) i++
95
+ tokens.push({ content: code.slice(start, i), type: 'DEFAULT' })
96
+ continue
97
+ }
98
+ if (code[i] === '"' || code[i] === "'" || code[i] === '`') {
99
+ const start = i
100
+ const quote = code[i]
101
+ i++
102
+ while (i < len && code[i] !== quote) {
103
+ if (code[i] === '\\') i++
104
+ i++
105
+ }
106
+ i++
107
+ tokens.push({ content: code.slice(start, i), type: 'STR' })
108
+ continue
109
+ }
110
+ if (code[i] === '/' && i + 1 < len && code[i + 1] === '/') {
111
+ const start = i
112
+ while (i < len && code[i] !== '\n') i++
113
+ tokens.push({ content: code.slice(start, i), type: 'COMMENT' })
114
+ continue
115
+ }
116
+ if (code[i] === '/' && i + 1 < len && code[i + 1] === '*') {
117
+ const start = i
118
+ i += 2
119
+ while (i + 1 < len && !(code[i] === '*' && code[i + 1] === '/')) i++
120
+ i += 2
121
+ tokens.push({ content: code.slice(start, i), type: 'COMMENT' })
122
+ continue
123
+ }
124
+ if (/[0-9]/.test(code[i])) {
125
+ const start = i
126
+ while (i < len && /[0-9.]/.test(code[i])) i++
127
+ tokens.push({ content: code.slice(start, i), type: 'NUMBER' })
128
+ continue
129
+ }
130
+ if (/[a-zA-Z_$]/.test(code[i])) {
131
+ const start = i
132
+ while (i < len && /[a-zA-Z0-9_$]/.test(code[i])) i++
133
+ const word = code.slice(start, i)
134
+ if (RICH_RESPONSE_CODE_KEYWORDS.has(word)) {
135
+ tokens.push({ content: word, type: 'KEYWORD' })
136
+ } else {
137
+ let j = i
138
+ while (j < len && /\s/.test(code[j])) j++
139
+ tokens.push({ content: word, type: j < len && code[j] === '(' ? 'METHOD' : 'DEFAULT' })
140
+ }
141
+ continue
142
+ }
143
+ tokens.push({ content: code[i], type: 'DEFAULT' })
144
+ i++
145
+ }
146
+ const merged = []
147
+ for (const t of tokens) {
148
+ if (merged.length && merged[merged.length - 1].type === 'DEFAULT' && t.type === 'DEFAULT') {
149
+ merged[merged.length - 1].content += t.content
150
+ } else {
151
+ merged.push(t)
152
+ }
153
+ }
154
+ return merged
155
+ }
156
+ /**
157
+ * Uses a regex to test whether the string contains a URL, and returns the URL if it does.
158
+ * @param text eg. hello https://google.com
159
+ * @returns the URL, eg. https://google.com
160
+ */
161
+ export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
162
+ export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
163
+ const url = extractUrlFromText(text);
164
+ if (!!getUrlInfo && url) {
165
+ try {
166
+ const urlInfo = await getUrlInfo(url);
167
+ return urlInfo;
168
+ }
169
+ catch (error) {
170
+ // ignore if fails
171
+ logger?.warn({ trace: error.stack }, 'url generation failed');
172
+ }
173
+ }
174
+ };
175
+ const assertColor = async (color) => {
176
+ let assertedColor;
177
+ if (typeof color === 'number') {
178
+ assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1;
179
+ }
180
+ else {
181
+ let hex = color.trim().replace('#', '');
182
+ if (hex.length <= 6) {
183
+ hex = 'FF' + hex.padStart(6, '0');
184
+ }
185
+ assertedColor = parseInt(hex, 16);
186
+ return assertedColor;
187
+ }
188
+ };
189
+ export const prepareWAMessageMedia = async (message, options) => {
190
+ const logger = options.logger;
191
+ let mediaType;
192
+ for (const key of MEDIA_KEYS) {
193
+ if (key in message) {
194
+ mediaType = key;
195
+ }
196
+ }
197
+ if (!mediaType) {
198
+ throw new Boom('Invalid media type', { statusCode: 400 });
199
+ }
200
+ const uploadData = {
201
+ ...message,
202
+ media: message[mediaType]
203
+ };
204
+ delete uploadData[mediaType];
205
+ // check if cacheable + generate cache key
206
+ const cacheableKey = typeof uploadData.media === 'object' &&
207
+ 'url' in uploadData.media &&
208
+ !!uploadData.media.url &&
209
+ !!options.mediaCache &&
210
+ mediaType + ':' + uploadData.media.url.toString();
211
+ if (mediaType === 'document' && !uploadData.fileName) {
212
+ uploadData.fileName = 'file';
213
+ }
214
+ if (!uploadData.mimetype) {
215
+ uploadData.mimetype = MIMETYPE_MAP[mediaType];
216
+ }
217
+ if (cacheableKey) {
218
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
219
+ if (mediaBuff) {
220
+ logger?.debug({ cacheableKey }, 'got media cache hit');
221
+ const obj = proto.Message.decode(mediaBuff);
222
+ const key = `${mediaType}Message`;
223
+ Object.assign(obj[key], { ...uploadData, media: undefined });
224
+ return obj;
225
+ }
226
+ }
227
+ const isNewsletter = !!options.jid && isJidNewsletter(options.jid);
228
+ if (isNewsletter) {
229
+ logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter');
230
+ const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger);
231
+ const fileSha256B64 = fileSha256.toString('base64');
232
+ const { mediaUrl, directPath } = await options.upload(filePath, {
233
+ fileEncSha256B64: fileSha256B64,
234
+ mediaType: mediaType,
235
+ timeoutMs: options.mediaUploadTimeoutMs
236
+ });
237
+ await fs.unlink(filePath);
238
+ const obj = WAProto.Message.fromObject({
239
+ // todo: add more support here
240
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
241
+ url: mediaUrl,
242
+ directPath,
243
+ fileSha256,
244
+ fileLength,
245
+ ...uploadData,
246
+ media: undefined
247
+ })
248
+ });
249
+ if (uploadData.ptv) {
250
+ obj.ptvMessage = obj.videoMessage;
251
+ delete obj.videoMessage;
252
+ }
253
+ if (obj.stickerMessage) {
254
+ obj.stickerMessage.stickerSentTs = Date.now();
255
+ }
256
+ if (cacheableKey) {
257
+ logger?.debug({ cacheableKey }, 'set cache');
258
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
259
+ }
260
+ return obj;
261
+ }
262
+ const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
263
+ const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined';
264
+ const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true && typeof uploadData.waveform === 'undefined';
265
+ const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
266
+ const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
267
+ const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
268
+ logger,
269
+ saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
270
+ opts: options.options
271
+ });
272
+ const fileEncSha256B64 = fileEncSha256.toString('base64');
273
+ const [{ mediaUrl, directPath }] = await Promise.all([
274
+ (async () => {
275
+ const result = await options.upload(encFilePath, {
276
+ fileEncSha256B64,
277
+ mediaType,
278
+ timeoutMs: options.mediaUploadTimeoutMs
279
+ });
280
+ logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
281
+ return result;
282
+ })(),
283
+ (async () => {
284
+ try {
285
+ if (requiresThumbnailComputation) {
286
+ const { thumbnail, originalImageDimensions } = await generateThumbnail(originalFilePath, mediaType, options);
287
+ uploadData.jpegThumbnail = thumbnail;
288
+ if (!uploadData.width && originalImageDimensions) {
289
+ uploadData.width = originalImageDimensions.width;
290
+ uploadData.height = originalImageDimensions.height;
291
+ logger?.debug('set dimensions');
292
+ }
293
+ logger?.debug('generated thumbnail');
294
+ }
295
+ if (requiresDurationComputation) {
296
+ uploadData.seconds = await getAudioDuration(originalFilePath);
297
+ logger?.debug('computed audio duration');
298
+ }
299
+ if (requiresWaveformProcessing) {
300
+ uploadData.waveform = await getAudioWaveform(originalFilePath, logger);
301
+ logger?.debug('processed waveform');
302
+ }
303
+ if (requiresAudioBackground) {
304
+ uploadData.backgroundArgb = await assertColor(options.backgroundColor);
305
+ logger?.debug('computed backgroundColor audio status');
306
+ }
307
+ }
308
+ catch (error) {
309
+ logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
310
+ }
311
+ })()
312
+ ]).finally(async () => {
313
+ try {
314
+ await fs.unlink(encFilePath);
315
+ if (originalFilePath) {
316
+ await fs.unlink(originalFilePath);
317
+ }
318
+ logger?.debug('removed tmp files');
319
+ }
320
+ catch (error) {
321
+ logger?.warn('failed to remove tmp file');
322
+ }
323
+ });
324
+ const obj = WAProto.Message.fromObject({
325
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
326
+ url: mediaUrl,
327
+ directPath,
328
+ mediaKey,
329
+ fileEncSha256,
330
+ fileSha256,
331
+ fileLength,
332
+ mediaKeyTimestamp: unixTimestampSeconds(),
333
+ ...uploadData,
334
+ media: undefined
335
+ })
336
+ });
337
+ if (uploadData.ptv) {
338
+ obj.ptvMessage = obj.videoMessage;
339
+ delete obj.videoMessage;
340
+ }
341
+ if (cacheableKey) {
342
+ logger?.debug({ cacheableKey }, 'set cache');
343
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
344
+ }
345
+ return obj;
346
+ };
347
+ export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
348
+ ephemeralExpiration = ephemeralExpiration || 0;
349
+ const content = {
350
+ ephemeralMessage: {
351
+ message: {
352
+ protocolMessage: {
353
+ type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
354
+ ephemeralExpiration
355
+ }
356
+ }
357
+ }
358
+ };
359
+ return WAProto.Message.fromObject(content);
360
+ };
361
+ /**
362
+ * Generate forwarded message content like WA does
363
+ * @param message the message to forward
364
+ * @param options.forceForward will show the message as forwarded even if it is from you
365
+ */
366
+ export const generateForwardMessageContent = (message, forceForward) => {
367
+ let content = message.message;
368
+ if (!content) {
369
+ throw new Boom('no content in message', { statusCode: 400 });
370
+ }
371
+ // hacky copy
372
+ content = normalizeMessageContent(content);
373
+ content = proto.Message.decode(proto.Message.encode(content).finish());
374
+ let key = Object.keys(content)[0];
375
+ let score = content?.[key]?.contextInfo?.forwardingScore || 0;
376
+ score += message.key.fromMe && !forceForward ? 0 : 1;
377
+ if (key === 'conversation') {
378
+ content.extendedTextMessage = { text: content[key] };
379
+ delete content.conversation;
380
+ key = 'extendedTextMessage';
381
+ }
382
+ const key_ = content?.[key];
383
+ if (score > 0) {
384
+ key_.contextInfo = { forwardingScore: score, isForwarded: true };
385
+ }
386
+ else {
387
+ key_.contextInfo = {};
388
+ }
389
+ return content;
390
+ };
391
+ export const hasNonNullishProperty = (message, key) => {
392
+ return (typeof message === 'object' &&
393
+ message !== null &&
394
+ key in message &&
395
+ message[key] !== null &&
396
+ message[key] !== undefined);
397
+ };
398
+ function hasOptionalProperty(obj, key) {
399
+ return typeof obj === 'object' && obj !== null && key in obj && obj[key] !== null;
400
+ }
401
+ const applyContextInfoAndMentions = (interactiveMessage, message) => {
402
+ if ('contextInfo' in message && !!message.contextInfo) {
403
+ interactiveMessage.contextInfo = message.contextInfo
404
+ }
405
+ if ('mentions' in message && !!message.mentions) {
406
+ interactiveMessage.contextInfo = {
407
+ ...(interactiveMessage.contextInfo || {}),
408
+ mentionedJid: message.mentions
409
+ }
410
+ }
411
+ }
412
+ export const generateWAMessageContent = async (message, options) => {
413
+ var _a, _b;
414
+ let m = {};
415
+ if ('interactiveButtons' in message && !!message.interactiveButtons) {
416
+ const nativeFlow = proto.Message.InteractiveMessage.NativeFlowMessage.fromObject({
417
+ buttons: message.interactiveButtons,
418
+ messageParamsJson: message.messageParams ?? "{}"
419
+ });
420
+ let interactiveMessage = { nativeFlowMessage: nativeFlow };
421
+ if ('text' in message) {
422
+ interactiveMessage.body = { text: message.text };
423
+ } else if ('caption' in message) {
424
+ interactiveMessage.body = { text: message.caption };
425
+ }
426
+ if ('title' in message && !!message.title) {
427
+ interactiveMessage.header = {
428
+ title: message.title,
429
+ subtitle: message.subtitle || "",
430
+ hasMediaAttachment: false
431
+ };
432
+ let media = null;
433
+ if ('image' in message && !!message.image) {
434
+ media = await prepareWAMessageMedia({ image: message.image }, options);
435
+ interactiveMessage.header.imageMessage = media.imageMessage;
436
+ if (message.image.caption) {
437
+ interactiveMessage.header.imageMessage.caption = message.image.caption;
438
+ }
439
+ } else if ('video' in message && !!message.video) {
440
+ media = await prepareWAMessageMedia({ video: message.video }, options);
441
+ interactiveMessage.header.videoMessage = media.videoMessage;
442
+ if (message.video.caption) {
443
+ interactiveMessage.header.videoMessage.caption = message.video.caption;
444
+ }
445
+ } else if ('gif' in message && !!message.gif) {
446
+ media = await prepareWAMessageMedia({ video: message.gif }, options);
447
+ interactiveMessage.header.videoMessage = media.videoMessage;
448
+ interactiveMessage.header.videoMessage.gifPlayback = true;
449
+ if (message.gif.caption) {
450
+ interactiveMessage.header.videoMessage.caption = message.gif.caption;
451
+ }
452
+ } else if ('document' in message && !!message.document) {
453
+ media = await prepareWAMessageMedia({ document: message.document }, options);
454
+ interactiveMessage.header.documentMessage = media.documentMessage;
455
+ let docuR = interactiveMessage.header.documentMessage;
456
+ docuR.fileName = message.document.fileName || "Document";
457
+ docuR.mimetype = message.document.mimetype || docuR.mimetype;
458
+ if (message.document.caption) docuR.caption = message.document.caption;
459
+ if (message.document.jpegThumbnail) docuR.jpegThumbnail = message.document.jpegThumbnail;
460
+ } else if ('location' in message && !!message.location) {
461
+ let mLoc = message.location;
462
+ interactiveMessage.header.locationMessage = {
463
+ degreesLongitude: mLoc.longitude || 0,
464
+ degreesLatitude: mLoc.latitude || 0,
465
+ name: mLoc.name || null,
466
+ address: mLoc.address || null,
467
+ url: mLoc.url || null
468
+ };
469
+ media = true;
470
+ } else if ('thumbnail' in message && !!message.thumbnail) {
471
+ interactiveMessage.header.jpegThumbnail = message.thumbnail;
472
+ }
473
+ if (media || ('thumbnail' in message && !!message.thumbnail)) {
474
+ interactiveMessage.header.hasMediaAttachment = true;
475
+ }
476
+ }
477
+ if ('footer' in message && !!message.footer) {
478
+ interactiveMessage.footer = { text: message.footer };
479
+ }
480
+ applyContextInfoAndMentions(interactiveMessage, message);
481
+ m = { interactiveMessage };
482
+ }
483
+ else if ('buttons' in message && !!message.buttons) {
484
+ const buttonsMessage = {
485
+ buttons: message.buttons.map(b => ({ ...b, type: proto.Message.ButtonsMessage.Button.Type.RESPONSE }))
486
+ };
487
+ if ('text' in message) {
488
+ buttonsMessage.contentText = message.text;
489
+ buttonsMessage.headerType = ButtonType.EMPTY;
490
+ }
491
+ else {
492
+ if ('caption' in message) {
493
+ buttonsMessage.contentText = message.caption;
494
+ }
495
+ const contentType = getContentType(m);
496
+ const type = contentType.replace('Message', '').toUpperCase();
497
+ buttonsMessage.headerType = ButtonType[type];
498
+ Object.assign(buttonsMessage, m);
499
+ }
500
+ if ('footer' in message && !!message.footer) {
501
+ buttonsMessage.footerText = message.footer;
502
+ }
503
+ m = { buttonsMessage };
504
+ }
505
+ else if ('richResponse' in message) {
506
+ const {
507
+ text,
508
+ code,
509
+ language = 'javascript',
510
+ botJid = '867051314767696@bot',
511
+ table,
512
+ latex,
513
+ map,
514
+ imageUrl,
515
+ imageUrls,
516
+ responseId,
517
+ messageSecret: richSecret
518
+ } = message.richResponse
519
+ const sections = []
520
+ if (text) {
521
+ sections.push({
522
+ view_model: {
523
+ primitive: { text, __typename: 'GenAIMarkdownTextUXPrimitive' },
524
+ __typename: 'GenAISingleLayoutViewModel'
525
+ }
526
+ })
527
+ }
528
+ if (code) {
529
+ sections.push({
530
+ view_model: {
531
+ primitive: {
532
+ language,
533
+ code_blocks: tokenizeCode(String(code)),
534
+ __typename: 'GenAICodeUXPrimitive'
535
+ },
536
+ __typename: 'GenAISingleLayoutViewModel'
537
+ }
538
+ })
539
+ }
540
+ if (table && Array.isArray(table.rows)) {
541
+ sections.push({
542
+ view_model: {
543
+ primitive: {
544
+ rows: table.rows.map(row => ({
545
+ cells: Array.isArray(row) ? row.map(c => ({ text: String(c) })) : row.cells
546
+ })),
547
+ __typename: 'GenAITableUXPrimitive'
548
+ },
549
+ __typename: 'GenAISingleLayoutViewModel'
550
+ }
551
+ })
552
+ }
553
+ if (latex) {
554
+ const expressions = Array.isArray(latex)
555
+ ? latex.map(e => (typeof e === 'string' ? { expression: e } : e))
556
+ : [{ expression: String(latex) }]
557
+ sections.push({
558
+ view_model: {
559
+ primitive: { expressions, __typename: 'GenAILatexUXPrimitive' },
560
+ __typename: 'GenAISingleLayoutViewModel'
561
+ }
562
+ })
563
+ }
564
+ if (map) {
565
+ sections.push({
566
+ view_model: {
567
+ primitive: {
568
+ latitude: map.latitude,
569
+ longitude: map.longitude,
570
+ zoom: map.zoom,
571
+ title: map.title,
572
+ annotations: map.annotations || [],
573
+ __typename: 'GenAIMapUXPrimitive'
574
+ },
575
+ __typename: 'GenAISingleLayoutViewModel'
576
+ }
577
+ })
578
+ }
579
+ if (imageUrl) {
580
+ sections.push({
581
+ view_model: {
582
+ primitive: { url: imageUrl, __typename: 'GenAIInlineImageUXPrimitive' },
583
+ __typename: 'GenAISingleLayoutViewModel'
584
+ }
585
+ })
586
+ }
587
+ if (imageUrls && Array.isArray(imageUrls) && imageUrls.length > 0) {
588
+ sections.push({
589
+ view_model: {
590
+ primitive: {
591
+ urls: imageUrls.map(u => (typeof u === 'string' ? { url: u } : u)),
592
+ __typename: 'GenAIGridImageUXPrimitive'
593
+ },
594
+ __typename: 'GenAISingleLayoutViewModel'
595
+ }
596
+ })
597
+ }
598
+ if (!sections.length && !text) {
599
+ sections.push({
600
+ view_model: {
601
+ primitive: { text: '', __typename: 'GenAIMarkdownTextUXPrimitive' },
602
+ __typename: 'GenAISingleLayoutViewModel'
603
+ }
604
+ })
605
+ }
606
+ const unifiedData = {
607
+ response_id: responseId || randomUUID(),
608
+ sections
609
+ }
610
+ return proto.Message.fromObject({
611
+ messageContextInfo: {
612
+ deviceListMetadata: {},
613
+ deviceListMetadataVersion: 2,
614
+ messageSecret: richSecret || randomBytes(32)
615
+ },
616
+ botForwardedMessage: {
617
+ message: {
618
+ richResponseMessage: {
619
+ submessages: [],
620
+ messageType: 1,
621
+ unifiedResponse: { data: Buffer.from(JSON.stringify(unifiedData)) },
622
+ contextInfo: {
623
+ forwardingScore: 2,
624
+ isForwarded: true,
625
+ forwardedAiBotMessageInfo: { botJid },
626
+ botMessageSharingInfo: {
627
+ botEntryPointOrigin: 1,
628
+ forwardScore: 2
629
+ }
630
+ }
631
+ }
632
+ }
633
+ }
634
+ })
635
+ }
636
+ else if (hasNonNullishProperty(message, 'text')) {
637
+ const extContent = { text: message.text };
638
+ let urlInfo = message.linkPreview;
639
+ if (typeof urlInfo === 'undefined') {
640
+ urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
641
+ }
642
+ if (urlInfo) {
643
+ extContent.matchedText = urlInfo['matched-text'];
644
+ extContent.jpegThumbnail = urlInfo.jpegThumbnail;
645
+ extContent.description = urlInfo.description;
646
+ extContent.title = urlInfo.title;
647
+ extContent.previewType = 0;
648
+ const img = urlInfo.highQualityThumbnail;
649
+ if (img) {
650
+ extContent.thumbnailDirectPath = img.directPath;
651
+ extContent.mediaKey = img.mediaKey;
652
+ extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
653
+ extContent.thumbnailWidth = img.width;
654
+ extContent.thumbnailHeight = img.height;
655
+ extContent.thumbnailSha256 = img.fileSha256;
656
+ extContent.thumbnailEncSha256 = img.fileEncSha256;
657
+ }
658
+ }
659
+ if (options.backgroundColor) {
660
+ extContent.backgroundArgb = await assertColor(options.backgroundColor);
661
+ }
662
+ if (options.font) {
663
+ extContent.font = options.font;
664
+ }
665
+ m.extendedTextMessage = extContent;
666
+ }
667
+ else if (hasNonNullishProperty(message, 'contacts')) {
668
+ const contactLen = message.contacts.contacts.length;
669
+ if (!contactLen) {
670
+ throw new Boom('require atleast 1 contact', { statusCode: 400 });
671
+ }
672
+ if (contactLen === 1) {
673
+ m.contactMessage = WAProto.Message.ContactMessage.create(message.contacts.contacts[0]);
674
+ }
675
+ else {
676
+ m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts);
677
+ }
678
+ }
679
+ else if (hasNonNullishProperty(message, 'location')) {
680
+ m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
681
+ }
682
+ else if (hasNonNullishProperty(message, 'react')) {
683
+ if (!message.react.senderTimestampMs) {
684
+ message.react.senderTimestampMs = Date.now();
685
+ }
686
+ m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
687
+ }
688
+ else if (hasNonNullishProperty(message, 'delete')) {
689
+ m.protocolMessage = {
690
+ key: message.delete,
691
+ type: WAProto.Message.ProtocolMessage.Type.REVOKE
692
+ };
693
+ }
694
+ else if (hasNonNullishProperty(message, 'forward')) {
695
+ m = generateForwardMessageContent(message.forward, message.force);
696
+ }
697
+ else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
698
+ const exp = typeof message.disappearingMessagesInChat === 'boolean'
699
+ ? message.disappearingMessagesInChat
700
+ ? WA_DEFAULT_EPHEMERAL
701
+ : 0
702
+ : message.disappearingMessagesInChat;
703
+ m = prepareDisappearingMessageSettingContent(exp);
704
+ }
705
+ else if (hasNonNullishProperty(message, 'groupInvite')) {
706
+ m.groupInviteMessage = {};
707
+ m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
708
+ m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
709
+ m.groupInviteMessage.caption = message.groupInvite.text;
710
+ m.groupInviteMessage.groupJid = message.groupInvite.jid;
711
+ m.groupInviteMessage.groupName = message.groupInvite.subject;
712
+ //TODO: use built-in interface and get disappearing mode info etc.
713
+ //TODO: cache / use store!?
714
+ if (options.getProfilePicUrl) {
715
+ const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
716
+ if (pfpUrl) {
717
+ const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
718
+ if (resp.ok) {
719
+ const buf = Buffer.from(await resp.arrayBuffer());
720
+ m.groupInviteMessage.jpegThumbnail = buf;
721
+ }
722
+ }
723
+ }
724
+ }
725
+ else if (hasNonNullishProperty(message, 'pin')) {
726
+ m.pinInChatMessage = {};
727
+ m.messageContextInfo = {};
728
+ m.pinInChatMessage.key = message.pin;
729
+ m.pinInChatMessage.type = message.type;
730
+ m.pinInChatMessage.senderTimestampMs = Date.now();
731
+ m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
732
+ }
733
+ else if (hasNonNullishProperty(message, 'buttonReply')) {
734
+ switch (message.type) {
735
+ case 'template':
736
+ m.templateButtonReplyMessage = {
737
+ selectedDisplayText: message.buttonReply.displayText,
738
+ selectedId: message.buttonReply.id,
739
+ selectedIndex: message.buttonReply.index
740
+ };
741
+ break;
742
+ case 'plain':
743
+ m.buttonsResponseMessage = {
744
+ selectedButtonId: message.buttonReply.id,
745
+ selectedDisplayText: message.buttonReply.displayText,
746
+ type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
747
+ };
748
+ break;
749
+ }
750
+ }
751
+ else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
752
+ const { videoMessage } = await prepareWAMessageMedia({ video: message.ptv }, options);
753
+ m.ptvMessage = videoMessage;
754
+ }
755
+ else if (hasNonNullishProperty(message, 'product')) {
756
+ const { imageMessage } = await prepareWAMessageMedia({ image: message.product.productImage }, options);
757
+ m.productMessage = WAProto.Message.ProductMessage.create({
758
+ ...message,
759
+ product: {
760
+ ...message.product,
761
+ productImage: imageMessage
762
+ }
763
+ });
764
+ }
765
+ else if (hasNonNullishProperty(message, 'listReply')) {
766
+ m.listResponseMessage = { ...message.listReply };
767
+ }
768
+ else if (hasNonNullishProperty(message, 'event')) {
769
+ m.eventMessage = {};
770
+ const startTime = Math.floor(message.event.startDate.getTime() / 1000);
771
+ if (message.event.call && options.getCallLink) {
772
+ const token = await options.getCallLink(message.event.call, { startTime });
773
+ m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
774
+ }
775
+ m.messageContextInfo = {
776
+ // encKey
777
+ messageSecret: message.event.messageSecret || randomBytes(32)
778
+ };
779
+ m.eventMessage.name = message.event.name;
780
+ m.eventMessage.description = message.event.description;
781
+ m.eventMessage.startTime = startTime;
782
+ m.eventMessage.endTime = message.event.endDate ? message.event.endDate.getTime() / 1000 : undefined;
783
+ m.eventMessage.isCanceled = message.event.isCancelled ?? false;
784
+ m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
785
+ m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
786
+ m.eventMessage.location = message.event.location;
787
+ }
788
+ else if (hasNonNullishProperty(message, 'poll')) {
789
+ (_a = message.poll).selectableCount || (_a.selectableCount = 0);
790
+ (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
791
+ if (!Array.isArray(message.poll.values)) {
792
+ throw new Boom('Invalid poll values', { statusCode: 400 });
793
+ }
794
+ if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
795
+ throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
796
+ statusCode: 400
797
+ });
798
+ }
799
+ m.messageContextInfo = {
800
+ // encKey
801
+ messageSecret: message.poll.messageSecret || randomBytes(32)
802
+ };
803
+ const pollCreationMessage = {
804
+ name: message.poll.name,
805
+ selectableOptionsCount: message.poll.selectableCount,
806
+ options: message.poll.values.map(optionName => ({ optionName }))
807
+ };
808
+ if (message.poll.toAnnouncementGroup) {
809
+ // poll v2 is for community announcement groups (single select and multiple)
810
+ m.pollCreationMessageV2 = pollCreationMessage;
811
+ }
812
+ else {
813
+ if (message.poll.selectableCount === 1) {
814
+ //poll v3 is for single select polls
815
+ m.pollCreationMessageV3 = pollCreationMessage;
816
+ }
817
+ else {
818
+ // poll for multiple choice polls
819
+ m.pollCreationMessage = pollCreationMessage;
820
+ }
821
+ }
822
+ }
823
+ else if (hasNonNullishProperty(message, 'album')) {
824
+ m.albumMessage = {
825
+ expectedImageCount: message.album.expectedImageCount,
826
+ expectedVideoCount: message.album.expectedVideoCount
827
+ };
828
+ }
829
+ else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
830
+ m.protocolMessage = {
831
+ type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
832
+ };
833
+ }
834
+ else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
835
+ m.requestPhoneNumberMessage = {};
836
+ }
837
+ else if (hasNonNullishProperty(message, 'limitSharing')) {
838
+ m.protocolMessage = {
839
+ type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
840
+ limitSharing: {
841
+ sharingLimited: message.limitSharing === true,
842
+ trigger: 1,
843
+ limitSharingSettingTimestamp: Date.now(),
844
+ initiatedByMe: true
845
+ }
846
+ };
847
+ }
848
+ else {
849
+ m = await prepareWAMessageMedia(message, options);
850
+ }
851
+ if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
852
+ m = { viewOnceMessage: { message: m } };
853
+ }
854
+ if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
855
+ (hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
856
+ const messageType = Object.keys(m)[0];
857
+ const key = m[messageType];
858
+ if (key && 'contextInfo' in key) {
859
+ key.contextInfo = key.contextInfo || {};
860
+ if (message.mentions?.length) {
861
+ key.contextInfo.mentionedJid = message.mentions;
862
+ }
863
+ if (message.mentionAll) {
864
+ key.contextInfo.nonJidMentions = 1;
865
+ }
866
+ }
867
+ else if (key) {
868
+ key.contextInfo = {
869
+ mentionedJid: message.mentions,
870
+ nonJidMentions: message.mentionAll ? 1 : 0
871
+ };
872
+ }
873
+ }
874
+ if (hasOptionalProperty(message, 'edit')) {
875
+ m = {
876
+ protocolMessage: {
877
+ key: message.edit,
878
+ editedMessage: m,
879
+ timestampMs: Date.now(),
880
+ type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
881
+ }
882
+ };
883
+ }
884
+ if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
885
+ const messageType = Object.keys(m)[0];
886
+ const key = m[messageType];
887
+ if ('contextInfo' in key && !!key.contextInfo) {
888
+ key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
889
+ }
890
+ else if (key) {
891
+ key.contextInfo = message.contextInfo;
892
+ }
893
+ }
894
+ if (hasOptionalProperty(message, 'albumParentKey') && !!message.albumParentKey) {
895
+ m.messageContextInfo = {
896
+ ...m.messageContextInfo,
897
+ messageAssociation: {
898
+ associationType: WAProto.MessageAssociation.AssociationType.MEDIA_ALBUM,
899
+ parentMessageKey: message.albumParentKey
900
+ }
901
+ };
902
+ }
903
+ if (shouldIncludeReportingToken(m)) {
904
+ m.messageContextInfo = m.messageContextInfo || {};
905
+ if (!m.messageContextInfo.messageSecret) {
906
+ m.messageContextInfo.messageSecret = randomBytes(32);
907
+ }
908
+ }
909
+ return WAProto.Message.create(m);
910
+ };
911
+ export const generateWAMessageFromContent = (jid, message, options) => {
912
+ // set timestamp to now
913
+ // if not specified
914
+ if (!options.timestamp) {
915
+ options.timestamp = new Date();
916
+ }
917
+ const innerMessage = normalizeMessageContent(message);
918
+ const key = getContentType(innerMessage);
919
+ const timestamp = unixTimestampSeconds(options.timestamp);
920
+ const { quoted, userJid } = options;
921
+ if (quoted && !isJidNewsletter(jid)) {
922
+ const participant = quoted.key.fromMe
923
+ ? userJid // TODO: Add support for LIDs
924
+ : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
925
+ let quotedMsg = normalizeMessageContent(quoted.message);
926
+ const msgType = getContentType(quotedMsg);
927
+ // strip any redundant properties
928
+ quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
929
+ const quotedContent = quotedMsg[msgType];
930
+ if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
931
+ delete quotedContent.contextInfo;
932
+ }
933
+ const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {};
934
+ contextInfo.participant = jidNormalizedUser(participant);
935
+ contextInfo.stanzaId = quoted.key.id;
936
+ contextInfo.quotedMessage = quotedMsg;
937
+ // if a participant is quoted, then it must be a group
938
+ // hence, remoteJid of group must also be entered
939
+ if (jid !== quoted.key.remoteJid) {
940
+ contextInfo.remoteJid = quoted.key.remoteJid;
941
+ }
942
+ if (contextInfo && innerMessage[key]) {
943
+ /* @ts-ignore */
944
+ innerMessage[key].contextInfo = contextInfo;
945
+ }
946
+ }
947
+ if (
948
+ // if we want to send a disappearing message
949
+ !!options?.ephemeralExpiration &&
950
+ // and it's not a protocol message -- delete, toggle disappear message
951
+ key !== 'protocolMessage' &&
952
+ // already not converted to disappearing message
953
+ key !== 'ephemeralMessage' &&
954
+ // newsletters don't support ephemeral messages
955
+ !isJidNewsletter(jid)) {
956
+ /* @ts-ignore */
957
+ innerMessage[key].contextInfo = {
958
+ ...(innerMessage[key].contextInfo || {}),
959
+ expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
960
+ //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
961
+ };
962
+ }
963
+ message = WAProto.Message.create(message);
964
+ const messageJSON = {
965
+ key: {
966
+ remoteJid: jid,
967
+ fromMe: true,
968
+ id: options?.messageId || generateMessageIDV2()
969
+ },
970
+ message: message,
971
+ messageTimestamp: timestamp,
972
+ messageStubParameters: [],
973
+ participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
974
+ status: WAMessageStatus.PENDING
975
+ };
976
+ return WAProto.WebMessageInfo.fromObject(messageJSON);
977
+ };
978
+ export const generateWAMessage = async (jid, content, options) => {
979
+ // ensure msg ID is with every log
980
+ options.logger = options?.logger?.child({ msgId: options.messageId });
981
+ // Pass jid in the options to generateWAMessageContent
982
+ return generateWAMessageFromContent(jid, await generateWAMessageContent(content, { ...options, jid }), options);
983
+ };
984
+ /** Get the key to access the true type of content */
985
+ export const getContentType = (content) => {
986
+ if (content) {
987
+ const keys = Object.keys(content);
988
+ const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
989
+ return key;
990
+ }
991
+ };
992
+ /**
993
+ * Normalizes ephemeral, view once messages to regular message content
994
+ * Eg. image messages in ephemeral messages, in view once messages etc.
995
+ * @param content
996
+ * @returns
997
+ */
998
+ export const normalizeMessageContent = (content) => {
999
+ if (!content) {
1000
+ return undefined;
1001
+ }
1002
+ // set max iterations to prevent an infinite loop
1003
+ for (let i = 0; i < 5; i++) {
1004
+ const inner = getFutureProofMessage(content);
1005
+ if (!inner) {
1006
+ break;
1007
+ }
1008
+ content = inner.message;
1009
+ }
1010
+ return content;
1011
+ function getFutureProofMessage(message) {
1012
+ return (message?.ephemeralMessage ||
1013
+ message?.viewOnceMessage ||
1014
+ message?.documentWithCaptionMessage ||
1015
+ message?.viewOnceMessageV2 ||
1016
+ message?.viewOnceMessageV2Extension ||
1017
+ message?.editedMessage ||
1018
+ message?.associatedChildMessage ||
1019
+ message?.groupStatusMessage ||
1020
+ message?.groupStatusMessageV2);
1021
+ }
1022
+ };
1023
+ /**
1024
+ * Extract the true message content from a message
1025
+ * Eg. extracts the inner message from a disappearing message/view once message
1026
+ */
1027
+ export const extractMessageContent = (content) => {
1028
+ const extractFromTemplateMessage = (msg) => {
1029
+ if (msg.imageMessage) {
1030
+ return { imageMessage: msg.imageMessage };
1031
+ }
1032
+ else if (msg.documentMessage) {
1033
+ return { documentMessage: msg.documentMessage };
1034
+ }
1035
+ else if (msg.videoMessage) {
1036
+ return { videoMessage: msg.videoMessage };
1037
+ }
1038
+ else if (msg.locationMessage) {
1039
+ return { locationMessage: msg.locationMessage };
1040
+ }
1041
+ else {
1042
+ return {
1043
+ conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
1044
+ };
1045
+ }
1046
+ };
1047
+ content = normalizeMessageContent(content);
1048
+ if (content?.buttonsMessage) {
1049
+ return extractFromTemplateMessage(content.buttonsMessage);
1050
+ }
1051
+ if (content?.templateMessage?.hydratedFourRowTemplate) {
1052
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
1053
+ }
1054
+ if (content?.templateMessage?.hydratedTemplate) {
1055
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
1056
+ }
1057
+ if (content?.templateMessage?.fourRowTemplate) {
1058
+ return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
1059
+ }
1060
+ return content;
1061
+ };
1062
+ /**
1063
+ * Returns the device predicted by message ID
1064
+ */
1065
+ export const getDevice = (id) => /^3A.{18}$/.test(id)
1066
+ ? 'ios'
1067
+ : /^3E.{20}$/.test(id)
1068
+ ? 'web'
1069
+ : /^(.{21}|.{32})$/.test(id)
1070
+ ? 'android'
1071
+ : /^(3F|.{18}$)/.test(id)
1072
+ ? 'desktop'
1073
+ : 'wa bot';
1074
+ /** Upserts a receipt in the message */
1075
+ export const updateMessageWithReceipt = (msg, receipt) => {
1076
+ msg.userReceipt = msg.userReceipt || [];
1077
+ const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
1078
+ if (recp) {
1079
+ Object.assign(recp, receipt);
1080
+ }
1081
+ else {
1082
+ msg.userReceipt.push(receipt);
1083
+ }
1084
+ };
1085
+ /** Update the message with a new reaction */
1086
+ export const updateMessageWithReaction = (msg, reaction) => {
1087
+ const authorID = getKeyAuthor(reaction.key);
1088
+ const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID);
1089
+ reaction.text = reaction.text || '';
1090
+ reactions.push(reaction);
1091
+ msg.reactions = reactions;
1092
+ };
1093
+ /** Update the message with a new poll update */
1094
+ export const updateMessageWithPollUpdate = (msg, update) => {
1095
+ const authorID = getKeyAuthor(update.pollUpdateMessageKey);
1096
+ const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID);
1097
+ if (update.vote?.selectedOptions?.length) {
1098
+ reactions.push(update);
1099
+ }
1100
+ msg.pollUpdates = reactions;
1101
+ };
1102
+ /** Update the message with a new event response */
1103
+ export const updateMessageWithEventResponse = (msg, update) => {
1104
+ const authorID = getKeyAuthor(update.eventResponseMessageKey);
1105
+ const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID);
1106
+ responses.push(update);
1107
+ msg.eventResponses = responses;
1108
+ };
1109
+ /**
1110
+ * Aggregates all poll updates in a poll.
1111
+ * @param msg the poll creation message
1112
+ * @param meId your jid
1113
+ * @returns A list of options & their voters
1114
+ */
1115
+ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
1116
+ const opts = message?.pollCreationMessage?.options ||
1117
+ message?.pollCreationMessageV2?.options ||
1118
+ message?.pollCreationMessageV3?.options ||
1119
+ [];
1120
+ const voteHashMap = opts.reduce((acc, opt) => {
1121
+ const hash = sha256(Buffer.from(opt.optionName || '')).toString();
1122
+ acc[hash] = {
1123
+ name: opt.optionName || '',
1124
+ voters: []
1125
+ };
1126
+ return acc;
1127
+ }, {});
1128
+ for (const update of pollUpdates || []) {
1129
+ const { vote } = update;
1130
+ if (!vote) {
1131
+ continue;
1132
+ }
1133
+ for (const option of vote.selectedOptions || []) {
1134
+ const hash = option.toString();
1135
+ let data = voteHashMap[hash];
1136
+ if (!data) {
1137
+ voteHashMap[hash] = {
1138
+ name: 'Unknown',
1139
+ voters: []
1140
+ };
1141
+ data = voteHashMap[hash];
1142
+ }
1143
+ voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId));
1144
+ }
1145
+ }
1146
+ return Object.values(voteHashMap);
1147
+ }
1148
+ /**
1149
+ * Aggregates all event responses in an event message.
1150
+ * @param msg the event creation message
1151
+ * @param meId your jid
1152
+ * @returns A list of response types & their responders
1153
+ */
1154
+ export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
1155
+ const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE'];
1156
+ const responseMap = {};
1157
+ for (const type of responseTypes) {
1158
+ responseMap[type] = {
1159
+ response: type,
1160
+ responders: []
1161
+ };
1162
+ }
1163
+ for (const update of eventResponses || []) {
1164
+ const responseType = update.eventResponse || 'UNKNOWN';
1165
+ if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
1166
+ responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId));
1167
+ }
1168
+ }
1169
+ return Object.values(responseMap);
1170
+ }
1171
+ /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
1172
+ export const aggregateMessageKeysNotFromMe = (keys) => {
1173
+ const keyMap = {};
1174
+ for (const { remoteJid, id, participant, fromMe } of keys) {
1175
+ if (!fromMe) {
1176
+ const uqKey = `${remoteJid}:${participant || ''}`;
1177
+ if (!keyMap[uqKey]) {
1178
+ keyMap[uqKey] = {
1179
+ jid: remoteJid,
1180
+ participant: participant,
1181
+ messageIds: []
1182
+ };
1183
+ }
1184
+ keyMap[uqKey].messageIds.push(id);
1185
+ }
1186
+ }
1187
+ return Object.values(keyMap);
1188
+ };
1189
+ const REUPLOAD_REQUIRED_STATUS = [410, 404];
1190
+ /**
1191
+ * Downloads the given message. Throws an error if it's not a media message
1192
+ */
1193
+ export const downloadMediaMessage = async (message, type, options, ctx) => {
1194
+ const result = await downloadMsg().catch(async (error) => {
1195
+ if (ctx &&
1196
+ typeof error?.status === 'number' && // treat errors with status as HTTP failures requiring reupload
1197
+ REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
1198
+ ctx.logger.info({ key: message.key }, 'sending reupload media request...');
1199
+ // request reupload
1200
+ message = await ctx.reuploadRequest(message);
1201
+ const result = await downloadMsg();
1202
+ return result;
1203
+ }
1204
+ throw error;
1205
+ });
1206
+ return result;
1207
+ async function downloadMsg() {
1208
+ const mContent = extractMessageContent(message.message);
1209
+ if (!mContent) {
1210
+ throw new Boom('No message present', { statusCode: 400, data: message });
1211
+ }
1212
+ const contentType = getContentType(mContent);
1213
+ let mediaType = contentType?.replace('Message', '');
1214
+ const media = mContent[contentType];
1215
+ if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
1216
+ throw new Boom(`"${contentType}" message is not a media message`);
1217
+ }
1218
+ let download;
1219
+ if ('thumbnailDirectPath' in media && !('url' in media)) {
1220
+ download = {
1221
+ directPath: media.thumbnailDirectPath,
1222
+ mediaKey: media.mediaKey
1223
+ };
1224
+ mediaType = 'thumbnail-link';
1225
+ }
1226
+ else {
1227
+ download = media;
1228
+ }
1229
+ const stream = await downloadContentFromMessage(download, mediaType, options);
1230
+ if (type === 'buffer') {
1231
+ const bufferArray = [];
1232
+ for await (const chunk of stream) {
1233
+ bufferArray.push(chunk);
1234
+ }
1235
+ return Buffer.concat(bufferArray);
1236
+ }
1237
+ return stream;
1238
+ }
1239
+ };
1240
+ /** Checks whether the given message is a media message; if it is returns the inner content */
1241
+ export const assertMediaContent = (content) => {
1242
+ content = extractMessageContent(content);
1243
+ const mediaContent = content?.documentMessage ||
1244
+ content?.imageMessage ||
1245
+ content?.videoMessage ||
1246
+ content?.audioMessage ||
1247
+ content?.stickerMessage;
1248
+ if (!mediaContent) {
1249
+ throw new Boom('given message is not a media message', { statusCode: 400, data: content });
1250
+ }
1251
+ return mediaContent;
1252
+ };
1253
+ //# sourceMappingURL=messages.js.map