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