@bellachu/litebails 1.0.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 (116) hide show
  1. package/LICENSE +30 -0
  2. package/README.md +30 -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 +1453 -0
  35. package/lib/Socket/mex.js +41 -0
  36. package/lib/Socket/newsletter.js +279 -0
  37. package/lib/Socket/socket.js +980 -0
  38. package/lib/Socket/username.js +234 -0
  39. package/lib/Store/index.js +10 -0
  40. package/lib/Store/keyed-db.js +108 -0
  41. package/lib/Store/make-cache-manager-store.js +85 -0
  42. package/lib/Store/make-in-memory-store.js +198 -0
  43. package/lib/Store/make-ordered-dictionary.js +75 -0
  44. package/lib/Store/object-repository.js +32 -0
  45. package/lib/Types/Auth.js +2 -0
  46. package/lib/Types/Bussines.js +2 -0
  47. package/lib/Types/Call.js +2 -0
  48. package/lib/Types/Chat.js +8 -0
  49. package/lib/Types/Contact.js +2 -0
  50. package/lib/Types/Events.js +2 -0
  51. package/lib/Types/GroupMetadata.js +2 -0
  52. package/lib/Types/Label.js +25 -0
  53. package/lib/Types/LabelAssociation.js +7 -0
  54. package/lib/Types/Message.js +11 -0
  55. package/lib/Types/Mex.js +37 -0
  56. package/lib/Types/Product.js +2 -0
  57. package/lib/Types/Signal.js +2 -0
  58. package/lib/Types/Socket.js +3 -0
  59. package/lib/Types/State.js +56 -0
  60. package/lib/Types/USync.js +2 -0
  61. package/lib/Types/index.js +26 -0
  62. package/lib/Utils/auth-utils.js +302 -0
  63. package/lib/Utils/browser-utils.js +49 -0
  64. package/lib/Utils/business.js +231 -0
  65. package/lib/Utils/chat-utils.js +872 -0
  66. package/lib/Utils/companion-reg-client-utils.js +35 -0
  67. package/lib/Utils/crypto.js +118 -0
  68. package/lib/Utils/decode-wa-message.js +350 -0
  69. package/lib/Utils/event-buffer.js +622 -0
  70. package/lib/Utils/generics.js +403 -0
  71. package/lib/Utils/history.js +134 -0
  72. package/lib/Utils/identity-change-handler.js +50 -0
  73. package/lib/Utils/index.js +23 -0
  74. package/lib/Utils/link-preview.js +85 -0
  75. package/lib/Utils/logger.js +3 -0
  76. package/lib/Utils/lt-hash.js +8 -0
  77. package/lib/Utils/make-mutex.js +33 -0
  78. package/lib/Utils/message-composer.js +273 -0
  79. package/lib/Utils/message-retry-manager.js +265 -0
  80. package/lib/Utils/messages-media.js +788 -0
  81. package/lib/Utils/messages.js +1260 -0
  82. package/lib/Utils/noise-handler.js +201 -0
  83. package/lib/Utils/offline-node-processor.js +40 -0
  84. package/lib/Utils/pre-key-manager.js +106 -0
  85. package/lib/Utils/process-message.js +630 -0
  86. package/lib/Utils/reporting-utils.js +258 -0
  87. package/lib/Utils/signal.js +201 -0
  88. package/lib/Utils/stanza-ack.js +38 -0
  89. package/lib/Utils/sync-action-utils.js +49 -0
  90. package/lib/Utils/tc-token-utils.js +163 -0
  91. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  92. package/lib/Utils/validate-connection.js +203 -0
  93. package/lib/WABinary/constants.js +1301 -0
  94. package/lib/WABinary/decode.js +262 -0
  95. package/lib/WABinary/encode.js +220 -0
  96. package/lib/WABinary/generic-utils.js +204 -0
  97. package/lib/WABinary/index.js +6 -0
  98. package/lib/WABinary/jid-utils.js +98 -0
  99. package/lib/WABinary/types.js +2 -0
  100. package/lib/WAM/BinaryInfo.js +10 -0
  101. package/lib/WAM/constants.js +22853 -0
  102. package/lib/WAM/encode.js +150 -0
  103. package/lib/WAM/index.js +4 -0
  104. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  105. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  106. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  107. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  108. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  109. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  110. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  111. package/lib/WAUSync/Protocols/index.js +6 -0
  112. package/lib/WAUSync/USyncQuery.js +98 -0
  113. package/lib/WAUSync/USyncUser.js +31 -0
  114. package/lib/WAUSync/index.js +4 -0
  115. package/lib/index.js +21 -0
  116. package/package.json +148 -0
@@ -0,0 +1,1260 @@
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 ('botInvoke' in message && !!message.botInvoke) {
637
+ m = {
638
+ botInvokeMessage: {
639
+ message: message.botInvoke
640
+ }
641
+ }
642
+ }
643
+ else if (hasNonNullishProperty(message, 'text')) {
644
+ const extContent = { text: message.text };
645
+ let urlInfo = message.linkPreview;
646
+ if (typeof urlInfo === 'undefined') {
647
+ urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
648
+ }
649
+ if (urlInfo) {
650
+ extContent.matchedText = urlInfo['matched-text'];
651
+ extContent.jpegThumbnail = urlInfo.jpegThumbnail;
652
+ extContent.description = urlInfo.description;
653
+ extContent.title = urlInfo.title;
654
+ extContent.previewType = 0;
655
+ const img = urlInfo.highQualityThumbnail;
656
+ if (img) {
657
+ extContent.thumbnailDirectPath = img.directPath;
658
+ extContent.mediaKey = img.mediaKey;
659
+ extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
660
+ extContent.thumbnailWidth = img.width;
661
+ extContent.thumbnailHeight = img.height;
662
+ extContent.thumbnailSha256 = img.fileSha256;
663
+ extContent.thumbnailEncSha256 = img.fileEncSha256;
664
+ }
665
+ }
666
+ if (options.backgroundColor) {
667
+ extContent.backgroundArgb = await assertColor(options.backgroundColor);
668
+ }
669
+ if (options.font) {
670
+ extContent.font = options.font;
671
+ }
672
+ m.extendedTextMessage = extContent;
673
+ }
674
+ else if (hasNonNullishProperty(message, 'contacts')) {
675
+ const contactLen = message.contacts.contacts.length;
676
+ if (!contactLen) {
677
+ throw new Boom('require atleast 1 contact', { statusCode: 400 });
678
+ }
679
+ if (contactLen === 1) {
680
+ m.contactMessage = WAProto.Message.ContactMessage.create(message.contacts.contacts[0]);
681
+ }
682
+ else {
683
+ m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts);
684
+ }
685
+ }
686
+ else if (hasNonNullishProperty(message, 'location')) {
687
+ m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
688
+ }
689
+ else if (hasNonNullishProperty(message, 'react')) {
690
+ if (!message.react.senderTimestampMs) {
691
+ message.react.senderTimestampMs = Date.now();
692
+ }
693
+ m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
694
+ }
695
+ else if (hasNonNullishProperty(message, 'delete')) {
696
+ m.protocolMessage = {
697
+ key: message.delete,
698
+ type: WAProto.Message.ProtocolMessage.Type.REVOKE
699
+ };
700
+ }
701
+ else if (hasNonNullishProperty(message, 'forward')) {
702
+ m = generateForwardMessageContent(message.forward, message.force);
703
+ }
704
+ else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
705
+ const exp = typeof message.disappearingMessagesInChat === 'boolean'
706
+ ? message.disappearingMessagesInChat
707
+ ? WA_DEFAULT_EPHEMERAL
708
+ : 0
709
+ : message.disappearingMessagesInChat;
710
+ m = prepareDisappearingMessageSettingContent(exp);
711
+ }
712
+ else if (hasNonNullishProperty(message, 'groupInvite')) {
713
+ m.groupInviteMessage = {};
714
+ m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
715
+ m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
716
+ m.groupInviteMessage.caption = message.groupInvite.text;
717
+ m.groupInviteMessage.groupJid = message.groupInvite.jid;
718
+ m.groupInviteMessage.groupName = message.groupInvite.subject;
719
+ //TODO: use built-in interface and get disappearing mode info etc.
720
+ //TODO: cache / use store!?
721
+ if (options.getProfilePicUrl) {
722
+ const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
723
+ if (pfpUrl) {
724
+ const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
725
+ if (resp.ok) {
726
+ const buf = Buffer.from(await resp.arrayBuffer());
727
+ m.groupInviteMessage.jpegThumbnail = buf;
728
+ }
729
+ }
730
+ }
731
+ }
732
+ else if (hasNonNullishProperty(message, 'pin')) {
733
+ m.pinInChatMessage = {};
734
+ m.messageContextInfo = {};
735
+ m.pinInChatMessage.key = message.pin;
736
+ m.pinInChatMessage.type = message.type;
737
+ m.pinInChatMessage.senderTimestampMs = Date.now();
738
+ m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
739
+ }
740
+ else if (hasNonNullishProperty(message, 'buttonReply')) {
741
+ switch (message.type) {
742
+ case 'template':
743
+ m.templateButtonReplyMessage = {
744
+ selectedDisplayText: message.buttonReply.displayText,
745
+ selectedId: message.buttonReply.id,
746
+ selectedIndex: message.buttonReply.index
747
+ };
748
+ break;
749
+ case 'plain':
750
+ m.buttonsResponseMessage = {
751
+ selectedButtonId: message.buttonReply.id,
752
+ selectedDisplayText: message.buttonReply.displayText,
753
+ type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
754
+ };
755
+ break;
756
+ }
757
+ }
758
+ else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
759
+ const { videoMessage } = await prepareWAMessageMedia({ video: message.ptv }, options);
760
+ m.ptvMessage = videoMessage;
761
+ }
762
+ else if (hasNonNullishProperty(message, 'product')) {
763
+ const { imageMessage } = await prepareWAMessageMedia({ image: message.product.productImage }, options);
764
+ m.productMessage = WAProto.Message.ProductMessage.create({
765
+ ...message,
766
+ product: {
767
+ ...message.product,
768
+ productImage: imageMessage
769
+ }
770
+ });
771
+ }
772
+ else if (hasNonNullishProperty(message, 'listReply')) {
773
+ m.listResponseMessage = { ...message.listReply };
774
+ }
775
+ else if (hasNonNullishProperty(message, 'event')) {
776
+ m.eventMessage = {};
777
+ const startTime = Math.floor(message.event.startDate.getTime() / 1000);
778
+ if (message.event.call && options.getCallLink) {
779
+ const token = await options.getCallLink(message.event.call, { startTime });
780
+ m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
781
+ }
782
+ m.messageContextInfo = {
783
+ // encKey
784
+ messageSecret: message.event.messageSecret || randomBytes(32)
785
+ };
786
+ m.eventMessage.name = message.event.name;
787
+ m.eventMessage.description = message.event.description;
788
+ m.eventMessage.startTime = startTime;
789
+ m.eventMessage.endTime = message.event.endDate ? message.event.endDate.getTime() / 1000 : undefined;
790
+ m.eventMessage.isCanceled = message.event.isCancelled ?? false;
791
+ m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
792
+ m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
793
+ m.eventMessage.location = message.event.location;
794
+ }
795
+ else if (hasNonNullishProperty(message, 'poll')) {
796
+ (_a = message.poll).selectableCount || (_a.selectableCount = 0);
797
+ (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
798
+ if (!Array.isArray(message.poll.values)) {
799
+ throw new Boom('Invalid poll values', { statusCode: 400 });
800
+ }
801
+ if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
802
+ throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
803
+ statusCode: 400
804
+ });
805
+ }
806
+ m.messageContextInfo = {
807
+ // encKey
808
+ messageSecret: message.poll.messageSecret || randomBytes(32)
809
+ };
810
+ const pollCreationMessage = {
811
+ name: message.poll.name,
812
+ selectableOptionsCount: message.poll.selectableCount,
813
+ options: message.poll.values.map(optionName => ({ optionName }))
814
+ };
815
+ if (message.poll.toAnnouncementGroup) {
816
+ // poll v2 is for community announcement groups (single select and multiple)
817
+ m.pollCreationMessageV2 = pollCreationMessage;
818
+ }
819
+ else {
820
+ if (message.poll.selectableCount === 1) {
821
+ //poll v3 is for single select polls
822
+ m.pollCreationMessageV3 = pollCreationMessage;
823
+ }
824
+ else {
825
+ // poll for multiple choice polls
826
+ m.pollCreationMessage = pollCreationMessage;
827
+ }
828
+ }
829
+ }
830
+ else if (hasNonNullishProperty(message, 'album')) {
831
+ m.albumMessage = {
832
+ expectedImageCount: message.album.expectedImageCount,
833
+ expectedVideoCount: message.album.expectedVideoCount
834
+ };
835
+ }
836
+ else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
837
+ m.protocolMessage = {
838
+ type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
839
+ };
840
+ }
841
+ else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
842
+ m.requestPhoneNumberMessage = {};
843
+ }
844
+ else if (hasNonNullishProperty(message, 'limitSharing')) {
845
+ m.protocolMessage = {
846
+ type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
847
+ limitSharing: {
848
+ sharingLimited: message.limitSharing === true,
849
+ trigger: 1,
850
+ limitSharingSettingTimestamp: Date.now(),
851
+ initiatedByMe: true
852
+ }
853
+ };
854
+ }
855
+ else {
856
+ m = await prepareWAMessageMedia(message, options);
857
+ }
858
+ if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
859
+ m = { viewOnceMessage: { message: m } };
860
+ }
861
+ if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
862
+ (hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
863
+ const messageType = Object.keys(m)[0];
864
+ const key = m[messageType];
865
+ if (key && 'contextInfo' in key) {
866
+ key.contextInfo = key.contextInfo || {};
867
+ if (message.mentions?.length) {
868
+ key.contextInfo.mentionedJid = message.mentions;
869
+ }
870
+ if (message.mentionAll) {
871
+ key.contextInfo.nonJidMentions = 1;
872
+ }
873
+ }
874
+ else if (key) {
875
+ key.contextInfo = {
876
+ mentionedJid: message.mentions,
877
+ nonJidMentions: message.mentionAll ? 1 : 0
878
+ };
879
+ }
880
+ }
881
+ if (hasOptionalProperty(message, 'edit')) {
882
+ m = {
883
+ protocolMessage: {
884
+ key: message.edit,
885
+ editedMessage: m,
886
+ timestampMs: Date.now(),
887
+ type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
888
+ }
889
+ };
890
+ }
891
+ if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
892
+ const messageType = Object.keys(m)[0];
893
+ const key = m[messageType];
894
+ if ('contextInfo' in key && !!key.contextInfo) {
895
+ key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
896
+ }
897
+ else if (key) {
898
+ key.contextInfo = message.contextInfo;
899
+ }
900
+ }
901
+ if (hasOptionalProperty(message, 'albumParentKey') && !!message.albumParentKey) {
902
+ m.messageContextInfo = {
903
+ ...m.messageContextInfo,
904
+ messageAssociation: {
905
+ associationType: WAProto.MessageAssociation.AssociationType.MEDIA_ALBUM,
906
+ parentMessageKey: message.albumParentKey
907
+ }
908
+ };
909
+ }
910
+ if (shouldIncludeReportingToken(m)) {
911
+ m.messageContextInfo = m.messageContextInfo || {};
912
+ if (!m.messageContextInfo.messageSecret) {
913
+ m.messageContextInfo.messageSecret = randomBytes(32);
914
+ }
915
+ }
916
+ return WAProto.Message.create(m);
917
+ };
918
+ export const generateWAMessageFromContent = (jid, message, options) => {
919
+ // set timestamp to now
920
+ // if not specified
921
+ if (!options.timestamp) {
922
+ options.timestamp = new Date();
923
+ }
924
+ const innerMessage = normalizeMessageContent(message);
925
+ const key = getContentType(innerMessage);
926
+ const timestamp = unixTimestampSeconds(options.timestamp);
927
+ const { quoted, userJid } = options;
928
+ if (quoted && !isJidNewsletter(jid)) {
929
+ const participant = quoted.key.fromMe
930
+ ? userJid // TODO: Add support for LIDs
931
+ : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
932
+ let quotedMsg = normalizeMessageContent(quoted.message);
933
+ const msgType = getContentType(quotedMsg);
934
+ // strip any redundant properties
935
+ quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
936
+ const quotedContent = quotedMsg[msgType];
937
+ if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
938
+ delete quotedContent.contextInfo;
939
+ }
940
+ const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {};
941
+ contextInfo.participant = jidNormalizedUser(participant);
942
+ contextInfo.stanzaId = quoted.key.id;
943
+ contextInfo.quotedMessage = quotedMsg;
944
+ // if a participant is quoted, then it must be a group
945
+ // hence, remoteJid of group must also be entered
946
+ if (jid !== quoted.key.remoteJid) {
947
+ contextInfo.remoteJid = quoted.key.remoteJid;
948
+ }
949
+ if (contextInfo && innerMessage[key]) {
950
+ /* @ts-ignore */
951
+ innerMessage[key].contextInfo = contextInfo;
952
+ }
953
+ }
954
+ if (
955
+ // if we want to send a disappearing message
956
+ !!options?.ephemeralExpiration &&
957
+ // and it's not a protocol message -- delete, toggle disappear message
958
+ key !== 'protocolMessage' &&
959
+ // already not converted to disappearing message
960
+ key !== 'ephemeralMessage' &&
961
+ // newsletters don't support ephemeral messages
962
+ !isJidNewsletter(jid)) {
963
+ /* @ts-ignore */
964
+ innerMessage[key].contextInfo = {
965
+ ...(innerMessage[key].contextInfo || {}),
966
+ expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
967
+ //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
968
+ };
969
+ }
970
+ message = WAProto.Message.create(message);
971
+ const messageJSON = {
972
+ key: {
973
+ remoteJid: jid,
974
+ fromMe: true,
975
+ id: options?.messageId || generateMessageIDV2()
976
+ },
977
+ message: message,
978
+ messageTimestamp: timestamp,
979
+ messageStubParameters: [],
980
+ participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
981
+ status: WAMessageStatus.PENDING
982
+ };
983
+ return WAProto.WebMessageInfo.fromObject(messageJSON);
984
+ };
985
+ export const generateWAMessage = async (jid, content, options) => {
986
+ // ensure msg ID is with every log
987
+ options.logger = options?.logger?.child({ msgId: options.messageId });
988
+ // Pass jid in the options to generateWAMessageContent
989
+ return generateWAMessageFromContent(jid, await generateWAMessageContent(content, { ...options, jid }), options);
990
+ };
991
+ /** Get the key to access the true type of content */
992
+ export const getContentType = (content) => {
993
+ if (content) {
994
+ const keys = Object.keys(content);
995
+ const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
996
+ return key;
997
+ }
998
+ };
999
+ /**
1000
+ * Normalizes ephemeral, view once messages to regular message content
1001
+ * Eg. image messages in ephemeral messages, in view once messages etc.
1002
+ * @param content
1003
+ * @returns
1004
+ */
1005
+ export const normalizeMessageContent = (content) => {
1006
+ if (!content) {
1007
+ return undefined;
1008
+ }
1009
+ // set max iterations to prevent an infinite loop
1010
+ for (let i = 0; i < 5; i++) {
1011
+ const inner = getFutureProofMessage(content);
1012
+ if (!inner) {
1013
+ break;
1014
+ }
1015
+ content = inner.message;
1016
+ }
1017
+ return content;
1018
+ function getFutureProofMessage(message) {
1019
+ return (message?.ephemeralMessage ||
1020
+ message?.viewOnceMessage ||
1021
+ message?.documentWithCaptionMessage ||
1022
+ message?.viewOnceMessageV2 ||
1023
+ message?.viewOnceMessageV2Extension ||
1024
+ message?.editedMessage ||
1025
+ message?.associatedChildMessage ||
1026
+ message?.groupStatusMessage ||
1027
+ message?.groupStatusMessageV2);
1028
+ }
1029
+ };
1030
+ /**
1031
+ * Extract the true message content from a message
1032
+ * Eg. extracts the inner message from a disappearing message/view once message
1033
+ */
1034
+ export const extractMessageContent = (content) => {
1035
+ const extractFromTemplateMessage = (msg) => {
1036
+ if (msg.imageMessage) {
1037
+ return { imageMessage: msg.imageMessage };
1038
+ }
1039
+ else if (msg.documentMessage) {
1040
+ return { documentMessage: msg.documentMessage };
1041
+ }
1042
+ else if (msg.videoMessage) {
1043
+ return { videoMessage: msg.videoMessage };
1044
+ }
1045
+ else if (msg.locationMessage) {
1046
+ return { locationMessage: msg.locationMessage };
1047
+ }
1048
+ else {
1049
+ return {
1050
+ conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
1051
+ };
1052
+ }
1053
+ };
1054
+ content = normalizeMessageContent(content);
1055
+ if (content?.buttonsMessage) {
1056
+ return extractFromTemplateMessage(content.buttonsMessage);
1057
+ }
1058
+ if (content?.templateMessage?.hydratedFourRowTemplate) {
1059
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
1060
+ }
1061
+ if (content?.templateMessage?.hydratedTemplate) {
1062
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
1063
+ }
1064
+ if (content?.templateMessage?.fourRowTemplate) {
1065
+ return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
1066
+ }
1067
+ return content;
1068
+ };
1069
+ /**
1070
+ * Returns the device predicted by message ID
1071
+ */
1072
+ export const getDevice = (id) => /^3A.{18}$/.test(id)
1073
+ ? 'ios'
1074
+ : /^3E.{20}$/.test(id)
1075
+ ? 'web'
1076
+ : /^(.{21}|.{32})$/.test(id)
1077
+ ? 'android'
1078
+ : /^(3F|.{18}$)/.test(id)
1079
+ ? 'desktop'
1080
+ : 'wa bot';
1081
+ /** Upserts a receipt in the message */
1082
+ export const updateMessageWithReceipt = (msg, receipt) => {
1083
+ msg.userReceipt = msg.userReceipt || [];
1084
+ const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
1085
+ if (recp) {
1086
+ Object.assign(recp, receipt);
1087
+ }
1088
+ else {
1089
+ msg.userReceipt.push(receipt);
1090
+ }
1091
+ };
1092
+ /** Update the message with a new reaction */
1093
+ export const updateMessageWithReaction = (msg, reaction) => {
1094
+ const authorID = getKeyAuthor(reaction.key);
1095
+ const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID);
1096
+ reaction.text = reaction.text || '';
1097
+ reactions.push(reaction);
1098
+ msg.reactions = reactions;
1099
+ };
1100
+ /** Update the message with a new poll update */
1101
+ export const updateMessageWithPollUpdate = (msg, update) => {
1102
+ const authorID = getKeyAuthor(update.pollUpdateMessageKey);
1103
+ const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID);
1104
+ if (update.vote?.selectedOptions?.length) {
1105
+ reactions.push(update);
1106
+ }
1107
+ msg.pollUpdates = reactions;
1108
+ };
1109
+ /** Update the message with a new event response */
1110
+ export const updateMessageWithEventResponse = (msg, update) => {
1111
+ const authorID = getKeyAuthor(update.eventResponseMessageKey);
1112
+ const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID);
1113
+ responses.push(update);
1114
+ msg.eventResponses = responses;
1115
+ };
1116
+ /**
1117
+ * Aggregates all poll updates in a poll.
1118
+ * @param msg the poll creation message
1119
+ * @param meId your jid
1120
+ * @returns A list of options & their voters
1121
+ */
1122
+ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
1123
+ const opts = message?.pollCreationMessage?.options ||
1124
+ message?.pollCreationMessageV2?.options ||
1125
+ message?.pollCreationMessageV3?.options ||
1126
+ [];
1127
+ const voteHashMap = opts.reduce((acc, opt) => {
1128
+ const hash = sha256(Buffer.from(opt.optionName || '')).toString();
1129
+ acc[hash] = {
1130
+ name: opt.optionName || '',
1131
+ voters: []
1132
+ };
1133
+ return acc;
1134
+ }, {});
1135
+ for (const update of pollUpdates || []) {
1136
+ const { vote } = update;
1137
+ if (!vote) {
1138
+ continue;
1139
+ }
1140
+ for (const option of vote.selectedOptions || []) {
1141
+ const hash = option.toString();
1142
+ let data = voteHashMap[hash];
1143
+ if (!data) {
1144
+ voteHashMap[hash] = {
1145
+ name: 'Unknown',
1146
+ voters: []
1147
+ };
1148
+ data = voteHashMap[hash];
1149
+ }
1150
+ voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId));
1151
+ }
1152
+ }
1153
+ return Object.values(voteHashMap);
1154
+ }
1155
+ /**
1156
+ * Aggregates all event responses in an event message.
1157
+ * @param msg the event creation message
1158
+ * @param meId your jid
1159
+ * @returns A list of response types & their responders
1160
+ */
1161
+ export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
1162
+ const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE'];
1163
+ const responseMap = {};
1164
+ for (const type of responseTypes) {
1165
+ responseMap[type] = {
1166
+ response: type,
1167
+ responders: []
1168
+ };
1169
+ }
1170
+ for (const update of eventResponses || []) {
1171
+ const responseType = update.eventResponse || 'UNKNOWN';
1172
+ if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
1173
+ responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId));
1174
+ }
1175
+ }
1176
+ return Object.values(responseMap);
1177
+ }
1178
+ /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
1179
+ export const aggregateMessageKeysNotFromMe = (keys) => {
1180
+ const keyMap = {};
1181
+ for (const { remoteJid, id, participant, fromMe } of keys) {
1182
+ if (!fromMe) {
1183
+ const uqKey = `${remoteJid}:${participant || ''}`;
1184
+ if (!keyMap[uqKey]) {
1185
+ keyMap[uqKey] = {
1186
+ jid: remoteJid,
1187
+ participant: participant,
1188
+ messageIds: []
1189
+ };
1190
+ }
1191
+ keyMap[uqKey].messageIds.push(id);
1192
+ }
1193
+ }
1194
+ return Object.values(keyMap);
1195
+ };
1196
+ const REUPLOAD_REQUIRED_STATUS = [410, 404];
1197
+ /**
1198
+ * Downloads the given message. Throws an error if it's not a media message
1199
+ */
1200
+ export const downloadMediaMessage = async (message, type, options, ctx) => {
1201
+ const result = await downloadMsg().catch(async (error) => {
1202
+ if (ctx &&
1203
+ typeof error?.status === 'number' && // treat errors with status as HTTP failures requiring reupload
1204
+ REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
1205
+ ctx.logger.info({ key: message.key }, 'sending reupload media request...');
1206
+ // request reupload
1207
+ message = await ctx.reuploadRequest(message);
1208
+ const result = await downloadMsg();
1209
+ return result;
1210
+ }
1211
+ throw error;
1212
+ });
1213
+ return result;
1214
+ async function downloadMsg() {
1215
+ const mContent = extractMessageContent(message.message);
1216
+ if (!mContent) {
1217
+ throw new Boom('No message present', { statusCode: 400, data: message });
1218
+ }
1219
+ const contentType = getContentType(mContent);
1220
+ let mediaType = contentType?.replace('Message', '');
1221
+ const media = mContent[contentType];
1222
+ if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
1223
+ throw new Boom(`"${contentType}" message is not a media message`);
1224
+ }
1225
+ let download;
1226
+ if ('thumbnailDirectPath' in media && !('url' in media)) {
1227
+ download = {
1228
+ directPath: media.thumbnailDirectPath,
1229
+ mediaKey: media.mediaKey
1230
+ };
1231
+ mediaType = 'thumbnail-link';
1232
+ }
1233
+ else {
1234
+ download = media;
1235
+ }
1236
+ const stream = await downloadContentFromMessage(download, mediaType, options);
1237
+ if (type === 'buffer') {
1238
+ const bufferArray = [];
1239
+ for await (const chunk of stream) {
1240
+ bufferArray.push(chunk);
1241
+ }
1242
+ return Buffer.concat(bufferArray);
1243
+ }
1244
+ return stream;
1245
+ }
1246
+ };
1247
+ /** Checks whether the given message is a media message; if it is returns the inner content */
1248
+ export const assertMediaContent = (content) => {
1249
+ content = extractMessageContent(content);
1250
+ const mediaContent = content?.documentMessage ||
1251
+ content?.imageMessage ||
1252
+ content?.videoMessage ||
1253
+ content?.audioMessage ||
1254
+ content?.stickerMessage;
1255
+ if (!mediaContent) {
1256
+ throw new Boom('given message is not a media message', { statusCode: 400, data: content });
1257
+ }
1258
+ return mediaContent;
1259
+ };
1260
+ //# sourceMappingURL=messages.js.map