@vinzsocket/baileys 2.8.9 → 2.8.20

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 (83) hide show
  1. package/lib/Defaults/index.js +75 -73
  2. package/lib/Signal/Group/ciphertext-message.js +9 -9
  3. package/lib/Signal/Group/group-session-builder.js +21 -21
  4. package/lib/Signal/Group/group_cipher.js +79 -81
  5. package/lib/Signal/Group/index.js +2 -2
  6. package/lib/Signal/Group/keyhelper.js +9 -9
  7. package/lib/Signal/Group/queue-job.js +43 -46
  8. package/lib/Signal/Group/sender-chain-key.js +24 -25
  9. package/lib/Signal/Group/sender-key-distribution-message.js +50 -58
  10. package/lib/Signal/Group/sender-key-message.js +55 -60
  11. package/lib/Signal/Group/sender-key-name.js +38 -39
  12. package/lib/Signal/Group/sender-key-record.js +39 -41
  13. package/lib/Signal/Group/sender-key-state.js +85 -89
  14. package/lib/Signal/Group/sender-message-key.js +22 -22
  15. package/lib/Signal/libsignal.js +387 -292
  16. package/lib/Signal/lid-mapping.js +98 -93
  17. package/lib/Socket/Client/types.js +6 -6
  18. package/lib/Socket/Client/websocket.js +44 -44
  19. package/lib/Socket/business.js +350 -365
  20. package/lib/Socket/chats.js +1019 -914
  21. package/lib/Socket/communities.js +454 -376
  22. package/lib/Socket/groups.js +378 -310
  23. package/lib/Socket/index.js +11 -11
  24. package/lib/Socket/messages-recv.js +1355 -1182
  25. package/lib/Socket/messages-send.js +1224 -1081
  26. package/lib/Socket/mex.js +40 -34
  27. package/lib/Socket/newsletter.js +212 -169
  28. package/lib/Socket/socket.js +896 -757
  29. package/lib/Store/index.js +1 -1
  30. package/lib/Store/make-cache-manager-store.js +75 -79
  31. package/lib/Store/make-in-memory-store.js +450 -389
  32. package/lib/Store/make-ordered-dictionary.js +73 -76
  33. package/lib/Store/object-repository.js +24 -22
  34. package/lib/Types/Chat.js +1 -7
  35. package/lib/Types/Label.js +20 -20
  36. package/lib/Types/LabelAssociation.js +2 -2
  37. package/lib/Types/Message.js +2 -2
  38. package/lib/Types/Newsletter.js +24 -24
  39. package/lib/Types/Socket.js +1 -1
  40. package/lib/Types/State.js +8 -8
  41. package/lib/Types/index.js +10 -10
  42. package/lib/Utils/auth-utils.js +408 -401
  43. package/lib/Utils/baileys-event-stream.js +44 -35
  44. package/lib/Utils/business.js +200 -197
  45. package/lib/Utils/chat-utils.js +775 -708
  46. package/lib/Utils/crypto.js +97 -85
  47. package/lib/Utils/decode-wa-message.js +240 -227
  48. package/lib/Utils/event-buffer.js +547 -518
  49. package/lib/Utils/extended-messages.js +250 -203
  50. package/lib/Utils/generics.js +300 -289
  51. package/lib/Utils/history.js +76 -69
  52. package/lib/Utils/lid-resolver.js +47 -42
  53. package/lib/Utils/link-preview.js +75 -65
  54. package/lib/Utils/logger.js +3 -1
  55. package/lib/Utils/lt-hash.js +38 -34
  56. package/lib/Utils/make-mutex.js +32 -34
  57. package/lib/Utils/mention.js +79 -86
  58. package/lib/Utils/message-retry-manager.js +148 -136
  59. package/lib/Utils/messages-media.js +652 -562
  60. package/lib/Utils/messages.js +753 -707
  61. package/lib/Utils/noise-handler.js +156 -135
  62. package/lib/Utils/process-message.js +404 -341
  63. package/lib/Utils/signal.js +180 -118
  64. package/lib/Utils/use-multi-file-auth-state.js +87 -91
  65. package/lib/Utils/validate-connection.js +167 -142
  66. package/lib/WABinary/constants.js +28 -1293
  67. package/lib/WABinary/decode.js +220 -218
  68. package/lib/WABinary/encode.js +199 -201
  69. package/lib/WABinary/generic-utils.js +80 -77
  70. package/lib/WABinary/jid-utils.js +41 -35
  71. package/lib/WAM/BinaryInfo.js +7 -7
  72. package/lib/WAM/constants.js +1 -15241
  73. package/lib/WAM/encode.js +124 -131
  74. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  75. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +51 -47
  76. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +22 -22
  77. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +30 -32
  78. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +19 -19
  79. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -43
  80. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +17 -17
  81. package/lib/WAUSync/USyncQuery.js +82 -84
  82. package/lib/WAUSync/USyncUser.js +20 -20
  83. package/package.json +4 -1
@@ -2,7 +2,7 @@ import { Boom } from '@hapi/boom';
2
2
  import axios from 'axios';
3
3
  import { randomBytes } from 'crypto';
4
4
  import { promises as fs } from 'fs';
5
- import {} from 'stream';
5
+ import 'stream';
6
6
  import { proto } from '../../WAProto/index.js';
7
7
  import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
8
8
  import { WAMessageStatus, WAProto } from '../Types/index.js';
@@ -11,221 +11,250 @@ import { sha256 } from './crypto.js';
11
11
  import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
12
12
  import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, getRawMediaUploadData } from './messages-media.js';
13
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'
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
20
  };
21
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
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
27
  };
28
28
  /**
29
29
  * Uses a regex to test whether the string contains a URL, and returns the URL if it does.
30
30
  * @param text eg. hello https://google.com
31
31
  * @returns the URL, eg. https://google.com
32
32
  */
33
- export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
33
+ export const extractUrlFromText = text => text.match(URL_REGEX)?.[0];
34
34
  export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
35
- const url = extractUrlFromText(text);
36
- if (!!getUrlInfo && url) {
37
- try {
38
- const urlInfo = await getUrlInfo(url);
39
- return urlInfo;
40
- }
41
- catch (error) {
42
- // ignore if fails
43
- logger?.warn({ trace: error.stack }, 'url generation failed');
44
- }
45
- }
35
+ const url = extractUrlFromText(text);
36
+ if (!!getUrlInfo && url) {
37
+ try {
38
+ const urlInfo = await getUrlInfo(url);
39
+ return urlInfo;
40
+ } catch (error) {
41
+ // ignore if fails
42
+ logger?.warn({
43
+ trace: error.stack
44
+ }, 'url generation failed');
45
+ }
46
+ }
46
47
  };
47
- const assertColor = async (color) => {
48
- let assertedColor;
49
- if (typeof color === 'number') {
50
- assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1;
51
- }
52
- else {
53
- let hex = color.trim().replace('#', '');
54
- if (hex.length <= 6) {
55
- hex = 'FF' + hex.padStart(6, '0');
56
- }
57
- assertedColor = parseInt(hex, 16);
58
- return assertedColor;
59
- }
48
+ const assertColor = async color => {
49
+ let assertedColor;
50
+ if (typeof color === 'number') {
51
+ assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1;
52
+ } else {
53
+ let hex = color.trim().replace('#', '');
54
+ if (hex.length <= 6) {
55
+ hex = 'FF' + hex.padStart(6, '0');
56
+ }
57
+ assertedColor = parseInt(hex, 16);
58
+ return assertedColor;
59
+ }
60
60
  };
61
61
  export const prepareWAMessageMedia = async (message, options) => {
62
- const logger = options.logger;
63
- let mediaType;
64
- for (const key of MEDIA_KEYS) {
65
- if (key in message) {
66
- mediaType = key;
67
- }
68
- }
69
- if (!mediaType) {
70
- throw new Boom('Invalid media type', { statusCode: 400 });
71
- }
72
- const uploadData = {
73
- ...message,
74
- media: message[mediaType]
75
- };
76
- delete uploadData[mediaType];
77
- // check if cacheable + generate cache key
78
- const cacheableKey = typeof uploadData.media === 'object' &&
79
- 'url' in uploadData.media &&
80
- !!uploadData.media.url &&
81
- !!options.mediaCache &&
82
- mediaType + ':' + uploadData.media.url.toString();
83
- if (mediaType === 'document' && !uploadData.fileName) {
84
- uploadData.fileName = 'file';
85
- }
86
- if (!uploadData.mimetype) {
87
- uploadData.mimetype = MIMETYPE_MAP[mediaType];
88
- }
89
- if (cacheableKey) {
90
- const mediaBuff = options.mediaCache.get(cacheableKey);
91
- if (mediaBuff) {
92
- logger?.debug({ cacheableKey }, 'got media cache hit');
93
- const obj = WAProto.Message.decode(mediaBuff);
94
- const key = `${mediaType}Message`;
95
- Object.assign(obj[key], { ...uploadData, media: undefined });
96
- return obj;
97
- }
98
- }
99
- const isNewsletter = !!options.jid && isJidNewsletter(options.jid);
100
- if (isNewsletter) {
101
- logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter');
102
- const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger);
103
- const fileSha256B64 = fileSha256.toString('base64');
104
- const { mediaUrl, directPath } = await options.upload(filePath, {
105
- fileEncSha256B64: fileSha256B64,
106
- mediaType: mediaType,
107
- timeoutMs: options.mediaUploadTimeoutMs
108
- });
109
- await fs.unlink(filePath);
110
- const obj = WAProto.Message.create({
111
- // todo: add more support here
112
- [`${mediaType}Message`]: MessageTypeProto[mediaType].create({
113
- url: mediaUrl,
114
- directPath,
115
- fileSha256,
116
- fileLength,
117
- ...uploadData,
118
- media: undefined
119
- })
120
- });
121
- if (uploadData.ptv) {
122
- obj.ptvMessage = obj.videoMessage;
123
- delete obj.videoMessage;
124
- }
125
- if (cacheableKey) {
126
- logger?.debug({ cacheableKey }, 'set cache');
127
- options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
128
- }
129
- return obj;
130
- }
131
- const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
132
- const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined';
133
- const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true;
134
- const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
135
- const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
136
- const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
137
- logger,
138
- saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
139
- opts: options.options
62
+ const logger = options.logger;
63
+ let mediaType;
64
+ for (const key of MEDIA_KEYS) {
65
+ if (key in message) {
66
+ mediaType = key;
67
+ }
68
+ }
69
+ if (!mediaType) {
70
+ throw new Boom('Invalid media type', {
71
+ statusCode: 400
140
72
  });
141
- const fileEncSha256B64 = fileEncSha256.toString('base64');
142
- const [{ mediaUrl, directPath }] = await Promise.all([
143
- (async () => {
144
- const result = await options.upload(encFilePath, {
145
- fileEncSha256B64,
146
- mediaType,
147
- timeoutMs: options.mediaUploadTimeoutMs
148
- });
149
- logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
150
- return result;
151
- })(),
152
- (async () => {
153
- try {
154
- if (requiresThumbnailComputation) {
155
- const { thumbnail, originalImageDimensions } = await generateThumbnail(originalFilePath, mediaType, options);
156
- uploadData.jpegThumbnail = thumbnail;
157
- if (!uploadData.width && originalImageDimensions) {
158
- uploadData.width = originalImageDimensions.width;
159
- uploadData.height = originalImageDimensions.height;
160
- logger?.debug('set dimensions');
161
- }
162
- logger?.debug('generated thumbnail');
163
- }
164
- if (requiresDurationComputation) {
165
- uploadData.seconds = await getAudioDuration(originalFilePath);
166
- logger?.debug('computed audio duration');
167
- }
168
- if (requiresWaveformProcessing) {
169
- uploadData.waveform = await getAudioWaveform(originalFilePath, logger);
170
- logger?.debug('processed waveform');
171
- }
172
- if (requiresAudioBackground) {
173
- uploadData.backgroundArgb = await assertColor(options.backgroundColor);
174
- logger?.debug('computed backgroundColor audio status');
175
- }
176
- }
177
- catch (error) {
178
- logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
179
- }
180
- })()
181
- ]).finally(async () => {
182
- try {
183
- await fs.unlink(encFilePath);
184
- if (originalFilePath) {
185
- await fs.unlink(originalFilePath);
186
- }
187
- logger?.debug('removed tmp files');
188
- }
189
- catch (error) {
190
- logger?.warn('failed to remove tmp file');
191
- }
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' && 'url' in uploadData.media && !!uploadData.media.url && !!options.mediaCache && mediaType + ':' + uploadData.media.url.toString();
81
+ if (mediaType === 'document' && !uploadData.fileName) {
82
+ uploadData.fileName = 'file';
83
+ }
84
+ if (!uploadData.mimetype) {
85
+ uploadData.mimetype = MIMETYPE_MAP[mediaType];
86
+ }
87
+ if (cacheableKey) {
88
+ const mediaBuff = options.mediaCache.get(cacheableKey);
89
+ if (mediaBuff) {
90
+ logger?.debug({
91
+ cacheableKey
92
+ }, 'got media cache hit');
93
+ const obj = WAProto.Message.decode(mediaBuff);
94
+ const key = `${mediaType}Message`;
95
+ Object.assign(obj[key], {
96
+ ...uploadData,
97
+ media: undefined
98
+ });
99
+ return obj;
100
+ }
101
+ }
102
+ const isNewsletter = !!options.jid && isJidNewsletter(options.jid);
103
+ if (isNewsletter) {
104
+ logger?.info({
105
+ key: cacheableKey
106
+ }, 'Preparing raw media for newsletter');
107
+ const {
108
+ filePath,
109
+ fileSha256,
110
+ fileLength
111
+ } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger);
112
+ const fileSha256B64 = fileSha256.toString('base64');
113
+ const {
114
+ mediaUrl,
115
+ directPath
116
+ } = await options.upload(filePath, {
117
+ fileEncSha256B64: fileSha256B64,
118
+ mediaType: mediaType,
119
+ timeoutMs: options.mediaUploadTimeoutMs
192
120
  });
121
+ await fs.unlink(filePath);
193
122
  const obj = WAProto.Message.create({
194
- [`${mediaType}Message`]: MessageTypeProto[mediaType].create({
195
- url: mediaUrl,
196
- directPath,
197
- mediaKey,
198
- fileEncSha256,
199
- fileSha256,
200
- fileLength,
201
- mediaKeyTimestamp: unixTimestampSeconds(),
202
- ...uploadData,
203
- media: undefined
204
- })
123
+ // todo: add more support here
124
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].create({
125
+ url: mediaUrl,
126
+ directPath,
127
+ fileSha256,
128
+ fileLength,
129
+ ...uploadData,
130
+ media: undefined
131
+ })
205
132
  });
206
133
  if (uploadData.ptv) {
207
- obj.ptvMessage = obj.videoMessage;
208
- delete obj.videoMessage;
134
+ obj.ptvMessage = obj.videoMessage;
135
+ delete obj.videoMessage;
209
136
  }
210
137
  if (cacheableKey) {
211
- logger?.debug({ cacheableKey }, 'set cache');
212
- options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
138
+ logger?.debug({
139
+ cacheableKey
140
+ }, 'set cache');
141
+ options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
213
142
  }
214
143
  return obj;
144
+ }
145
+ const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
146
+ const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined';
147
+ const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true;
148
+ const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
149
+ const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
150
+ const {
151
+ mediaKey,
152
+ encFilePath,
153
+ originalFilePath,
154
+ fileEncSha256,
155
+ fileSha256,
156
+ fileLength
157
+ } = await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
158
+ logger,
159
+ saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
160
+ opts: options.options
161
+ });
162
+ const fileEncSha256B64 = fileEncSha256.toString('base64');
163
+ const [{
164
+ mediaUrl,
165
+ directPath
166
+ }] = await Promise.all([(async () => {
167
+ const result = await options.upload(encFilePath, {
168
+ fileEncSha256B64,
169
+ mediaType,
170
+ timeoutMs: options.mediaUploadTimeoutMs
171
+ });
172
+ logger?.debug({
173
+ mediaType,
174
+ cacheableKey
175
+ }, 'uploaded media');
176
+ return result;
177
+ })(), (async () => {
178
+ try {
179
+ if (requiresThumbnailComputation) {
180
+ const {
181
+ thumbnail,
182
+ originalImageDimensions
183
+ } = await generateThumbnail(originalFilePath, mediaType, options);
184
+ uploadData.jpegThumbnail = thumbnail;
185
+ if (!uploadData.width && originalImageDimensions) {
186
+ uploadData.width = originalImageDimensions.width;
187
+ uploadData.height = originalImageDimensions.height;
188
+ logger?.debug('set dimensions');
189
+ }
190
+ logger?.debug('generated thumbnail');
191
+ }
192
+ if (requiresDurationComputation) {
193
+ uploadData.seconds = await getAudioDuration(originalFilePath);
194
+ logger?.debug('computed audio duration');
195
+ }
196
+ if (requiresWaveformProcessing) {
197
+ uploadData.waveform = await getAudioWaveform(originalFilePath, logger);
198
+ logger?.debug('processed waveform');
199
+ }
200
+ if (requiresAudioBackground) {
201
+ uploadData.backgroundArgb = await assertColor(options.backgroundColor);
202
+ logger?.debug('computed backgroundColor audio status');
203
+ }
204
+ } catch (error) {
205
+ logger?.warn({
206
+ trace: error.stack
207
+ }, 'failed to obtain extra info');
208
+ }
209
+ })()]).finally(async () => {
210
+ try {
211
+ await fs.unlink(encFilePath);
212
+ if (originalFilePath) {
213
+ await fs.unlink(originalFilePath);
214
+ }
215
+ logger?.debug('removed tmp files');
216
+ } catch (error) {
217
+ logger?.warn('failed to remove tmp file');
218
+ }
219
+ });
220
+ const obj = WAProto.Message.create({
221
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].create({
222
+ url: mediaUrl,
223
+ directPath,
224
+ mediaKey,
225
+ fileEncSha256,
226
+ fileSha256,
227
+ fileLength,
228
+ mediaKeyTimestamp: unixTimestampSeconds(),
229
+ ...uploadData,
230
+ media: undefined
231
+ })
232
+ });
233
+ if (uploadData.ptv) {
234
+ obj.ptvMessage = obj.videoMessage;
235
+ delete obj.videoMessage;
236
+ }
237
+ if (cacheableKey) {
238
+ logger?.debug({
239
+ cacheableKey
240
+ }, 'set cache');
241
+ options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
242
+ }
243
+ return obj;
215
244
  };
216
- export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
217
- ephemeralExpiration = ephemeralExpiration || 0;
218
- const content = {
219
- ephemeralMessage: {
220
- message: {
221
- protocolMessage: {
222
- type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
223
- ephemeralExpiration
224
- }
225
- }
226
- }
227
- };
228
- return WAProto.Message.create(content);
245
+ export const prepareDisappearingMessageSettingContent = ephemeralExpiration => {
246
+ ephemeralExpiration = ephemeralExpiration || 0;
247
+ const content = {
248
+ ephemeralMessage: {
249
+ message: {
250
+ protocolMessage: {
251
+ type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
252
+ ephemeralExpiration
253
+ }
254
+ }
255
+ }
256
+ };
257
+ return WAProto.Message.create(content);
229
258
  };
230
259
  /**
231
260
  * Generate forwarded message content like WA does
@@ -233,347 +262,364 @@ export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) =>
233
262
  * @param options.forceForward will show the message as forwarded even if it is from you
234
263
  */
235
264
  export const generateForwardMessageContent = (message, forceForward) => {
236
- let content = message.message;
237
- if (!content) {
238
- throw new Boom('no content in message', { statusCode: 400 });
239
- }
240
- // hacky copy
241
- content = normalizeMessageContent(content);
242
- content = proto.Message.decode(proto.Message.encode(content).finish());
243
- let key = Object.keys(content)[0];
244
- let score = content?.[key]?.contextInfo?.forwardingScore || 0;
245
- score += message.key.fromMe && !forceForward ? 0 : 1;
246
- if (key === 'conversation') {
247
- content.extendedTextMessage = { text: content[key] };
248
- delete content.conversation;
249
- key = 'extendedTextMessage';
250
- }
251
- const key_ = content?.[key];
252
- if (score > 0) {
253
- key_.contextInfo = { forwardingScore: score, isForwarded: true };
254
- }
255
- else {
256
- key_.contextInfo = {};
257
- }
258
- return content;
265
+ let content = message.message;
266
+ if (!content) {
267
+ throw new Boom('no content in message', {
268
+ statusCode: 400
269
+ });
270
+ }
271
+ // hacky copy
272
+ content = normalizeMessageContent(content);
273
+ content = proto.Message.decode(proto.Message.encode(content).finish());
274
+ let key = Object.keys(content)[0];
275
+ let score = content?.[key]?.contextInfo?.forwardingScore || 0;
276
+ score += message.key.fromMe && !forceForward ? 0 : 1;
277
+ if (key === 'conversation') {
278
+ content.extendedTextMessage = {
279
+ text: content[key]
280
+ };
281
+ delete content.conversation;
282
+ key = 'extendedTextMessage';
283
+ }
284
+ const key_ = content?.[key];
285
+ if (score > 0) {
286
+ key_.contextInfo = {
287
+ forwardingScore: score,
288
+ isForwarded: true
289
+ };
290
+ } else {
291
+ key_.contextInfo = {};
292
+ }
293
+ return content;
259
294
  };
260
295
  export const generateWAMessageContent = async (message, options) => {
261
- var _a, _b;
262
- let m = {};
263
- if ('text' in message) {
264
- const extContent = { text: message.text };
265
- let urlInfo = message.linkPreview;
266
- if (typeof urlInfo === 'undefined') {
267
- urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
268
- }
269
- if (urlInfo) {
270
- extContent.matchedText = urlInfo['matched-text'];
271
- extContent.jpegThumbnail = urlInfo.jpegThumbnail;
272
- extContent.description = urlInfo.description;
273
- extContent.title = urlInfo.title;
274
- extContent.previewType = 0;
275
- const img = urlInfo.highQualityThumbnail;
276
- if (img) {
277
- extContent.thumbnailDirectPath = img.directPath;
278
- extContent.mediaKey = img.mediaKey;
279
- extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
280
- extContent.thumbnailWidth = img.width;
281
- extContent.thumbnailHeight = img.height;
282
- extContent.thumbnailSha256 = img.fileSha256;
283
- extContent.thumbnailEncSha256 = img.fileEncSha256;
284
- }
285
- }
286
- if (options.backgroundColor) {
287
- extContent.backgroundArgb = await assertColor(options.backgroundColor);
288
- }
289
- if (options.font) {
290
- extContent.font = options.font;
291
- }
292
- m.extendedTextMessage = extContent;
293
- }
294
- else if ('contacts' in message) {
295
- const contactLen = message.contacts.contacts.length;
296
- if (!contactLen) {
297
- throw new Boom('require atleast 1 contact', { statusCode: 400 });
298
- }
299
- if (contactLen === 1) {
300
- m.contactMessage = WAProto.Message.ContactMessage.create(message.contacts.contacts[0]);
301
- }
302
- else {
303
- m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts);
304
- }
305
- }
306
- else if ('location' in message) {
307
- m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
308
- }
309
- else if ('react' in message) {
310
- if (!message.react.senderTimestampMs) {
311
- message.react.senderTimestampMs = Date.now();
312
- }
313
- m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
314
- }
315
- else if ('delete' in message) {
316
- m.protocolMessage = {
317
- key: message.delete,
318
- type: WAProto.Message.ProtocolMessage.Type.REVOKE
319
- };
320
- }
321
- else if ('forward' in message) {
322
- m = generateForwardMessageContent(message.forward, message.force);
323
- }
324
- else if ('disappearingMessagesInChat' in message) {
325
- const exp = typeof message.disappearingMessagesInChat === 'boolean'
326
- ? message.disappearingMessagesInChat
327
- ? WA_DEFAULT_EPHEMERAL
328
- : 0
329
- : message.disappearingMessagesInChat;
330
- m = prepareDisappearingMessageSettingContent(exp);
331
- }
332
- else if ('groupInvite' in message) {
333
- m.groupInviteMessage = {};
334
- m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
335
- m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
336
- m.groupInviteMessage.caption = message.groupInvite.text;
337
- m.groupInviteMessage.groupJid = message.groupInvite.jid;
338
- m.groupInviteMessage.groupName = message.groupInvite.subject;
339
- //TODO: use built-in interface and get disappearing mode info etc.
340
- //TODO: cache / use store!?
341
- if (options.getProfilePicUrl) {
342
- const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
343
- if (pfpUrl) {
344
- const resp = await axios.get(pfpUrl, { responseType: 'arraybuffer' });
345
- if (resp.status === 200) {
346
- m.groupInviteMessage.jpegThumbnail = resp.data;
347
- }
348
- }
349
- }
350
- }
351
- else if ('pin' in message) {
352
- m.pinInChatMessage = {};
353
- m.messageContextInfo = {};
354
- m.pinInChatMessage.key = message.pin;
355
- m.pinInChatMessage.type = message.type;
356
- m.pinInChatMessage.senderTimestampMs = Date.now();
357
- m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
358
- }
359
- else if ('buttonReply' in message) {
360
- switch (message.type) {
361
- case 'template':
362
- m.templateButtonReplyMessage = {
363
- selectedDisplayText: message.buttonReply.displayText,
364
- selectedId: message.buttonReply.id,
365
- selectedIndex: message.buttonReply.index
366
- };
367
- break;
368
- case 'plain':
369
- m.buttonsResponseMessage = {
370
- selectedButtonId: message.buttonReply.id,
371
- selectedDisplayText: message.buttonReply.displayText,
372
- type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
373
- };
374
- break;
375
- }
376
- }
377
- else if ('ptv' in message && message.ptv) {
378
- const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options);
379
- m.ptvMessage = videoMessage;
380
- }
381
- else if ('product' in message) {
382
- const { imageMessage } = await prepareWAMessageMedia({ image: message.product.productImage }, options);
383
- m.productMessage = WAProto.Message.ProductMessage.create({
384
- ...message,
385
- product: {
386
- ...message.product,
387
- productImage: imageMessage
388
- }
296
+ var _a, _b;
297
+ let m = {};
298
+ if ('text' in message) {
299
+ const extContent = {
300
+ text: message.text
301
+ };
302
+ let urlInfo = message.linkPreview;
303
+ if (typeof urlInfo === 'undefined') {
304
+ urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
305
+ }
306
+ if (urlInfo) {
307
+ extContent.matchedText = urlInfo['matched-text'];
308
+ extContent.jpegThumbnail = urlInfo.jpegThumbnail;
309
+ extContent.description = urlInfo.description;
310
+ extContent.title = urlInfo.title;
311
+ extContent.previewType = 0;
312
+ const img = urlInfo.highQualityThumbnail;
313
+ if (img) {
314
+ extContent.thumbnailDirectPath = img.directPath;
315
+ extContent.mediaKey = img.mediaKey;
316
+ extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
317
+ extContent.thumbnailWidth = img.width;
318
+ extContent.thumbnailHeight = img.height;
319
+ extContent.thumbnailSha256 = img.fileSha256;
320
+ extContent.thumbnailEncSha256 = img.fileEncSha256;
321
+ }
322
+ }
323
+ if (options.backgroundColor) {
324
+ extContent.backgroundArgb = await assertColor(options.backgroundColor);
325
+ }
326
+ if (options.font) {
327
+ extContent.font = options.font;
328
+ }
329
+ m.extendedTextMessage = extContent;
330
+ } else if ('contacts' in message) {
331
+ const contactLen = message.contacts.contacts.length;
332
+ if (!contactLen) {
333
+ throw new Boom('require atleast 1 contact', {
334
+ statusCode: 400
335
+ });
336
+ }
337
+ if (contactLen === 1) {
338
+ m.contactMessage = WAProto.Message.ContactMessage.create(message.contacts.contacts[0]);
339
+ } else {
340
+ m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts);
341
+ }
342
+ } else if ('location' in message) {
343
+ m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
344
+ } else if ('react' in message) {
345
+ if (!message.react.senderTimestampMs) {
346
+ message.react.senderTimestampMs = Date.now();
347
+ }
348
+ m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
349
+ } else if ('delete' in message) {
350
+ m.protocolMessage = {
351
+ key: message.delete,
352
+ type: WAProto.Message.ProtocolMessage.Type.REVOKE
353
+ };
354
+ } else if ('forward' in message) {
355
+ m = generateForwardMessageContent(message.forward, message.force);
356
+ } else if ('disappearingMessagesInChat' in message) {
357
+ const exp = typeof message.disappearingMessagesInChat === 'boolean' ? message.disappearingMessagesInChat ? WA_DEFAULT_EPHEMERAL : 0 : message.disappearingMessagesInChat;
358
+ m = prepareDisappearingMessageSettingContent(exp);
359
+ } else if ('groupInvite' in message) {
360
+ m.groupInviteMessage = {};
361
+ m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
362
+ m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
363
+ m.groupInviteMessage.caption = message.groupInvite.text;
364
+ m.groupInviteMessage.groupJid = message.groupInvite.jid;
365
+ m.groupInviteMessage.groupName = message.groupInvite.subject;
366
+ //TODO: use built-in interface and get disappearing mode info etc.
367
+ //TODO: cache / use store!?
368
+ if (options.getProfilePicUrl) {
369
+ const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
370
+ if (pfpUrl) {
371
+ const resp = await axios.get(pfpUrl, {
372
+ responseType: 'arraybuffer'
389
373
  });
390
- }
391
- else if ('listReply' in message) {
392
- m.listResponseMessage = { ...message.listReply };
393
- }
394
- else if ('event' in message) {
395
- m.eventMessage = {};
396
- const startTime = Math.floor(message.event.startDate.getTime() / 1000);
397
- if (message.event.call && options.getCallLink) {
398
- const token = await options.getCallLink(message.event.call, { startTime });
399
- m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
400
- }
401
- m.messageContextInfo = {
402
- // encKey
403
- messageSecret: message.event.messageSecret || randomBytes(32)
404
- };
405
- m.eventMessage.name = message.event.name;
406
- m.eventMessage.description = message.event.description;
407
- m.eventMessage.startTime = startTime;
408
- m.eventMessage.endTime = message.event.endDate ? message.event.endDate.getTime() / 1000 : undefined;
409
- m.eventMessage.isCanceled = message.event.isCancelled ?? false;
410
- m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
411
- m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
412
- m.eventMessage.location = message.event.location;
413
- }
414
- else if ('poll' in message) {
415
- (_a = message.poll).selectableCount || (_a.selectableCount = 0);
416
- (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
417
- if (!Array.isArray(message.poll.values)) {
418
- throw new Boom('Invalid poll values', { statusCode: 400 });
419
- }
420
- if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
421
- throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
422
- statusCode: 400
423
- });
424
- }
425
- m.messageContextInfo = {
426
- // encKey
427
- messageSecret: message.poll.messageSecret || randomBytes(32)
374
+ if (resp.status === 200) {
375
+ m.groupInviteMessage.jpegThumbnail = resp.data;
376
+ }
377
+ }
378
+ }
379
+ } else if ('pin' in message) {
380
+ m.pinInChatMessage = {};
381
+ m.messageContextInfo = {};
382
+ m.pinInChatMessage.key = message.pin;
383
+ m.pinInChatMessage.type = message.type;
384
+ m.pinInChatMessage.senderTimestampMs = Date.now();
385
+ m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
386
+ } else if ('buttonReply' in message) {
387
+ switch (message.type) {
388
+ case 'template':
389
+ m.templateButtonReplyMessage = {
390
+ selectedDisplayText: message.buttonReply.displayText,
391
+ selectedId: message.buttonReply.id,
392
+ selectedIndex: message.buttonReply.index
428
393
  };
429
- const pollCreationMessage = {
430
- name: message.poll.name,
431
- selectableOptionsCount: message.poll.selectableCount,
432
- options: message.poll.values.map(optionName => ({ optionName }))
394
+ break;
395
+ case 'plain':
396
+ m.buttonsResponseMessage = {
397
+ selectedButtonId: message.buttonReply.id,
398
+ selectedDisplayText: message.buttonReply.displayText,
399
+ type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
433
400
  };
434
- if (message.poll.toAnnouncementGroup) {
435
- // poll v2 is for community announcement groups (single select and multiple)
436
- m.pollCreationMessageV2 = pollCreationMessage;
437
- }
438
- else {
439
- if (message.poll.selectableCount === 1) {
440
- //poll v3 is for single select polls
441
- m.pollCreationMessageV3 = pollCreationMessage;
442
- }
443
- else {
444
- // poll for multiple choice polls
445
- m.pollCreationMessage = pollCreationMessage;
446
- }
447
- }
448
- }
449
- else if ('sharePhoneNumber' in message) {
450
- m.protocolMessage = {
451
- type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
452
- };
453
- }
454
- else if ('requestPhoneNumber' in message) {
455
- m.requestPhoneNumberMessage = {};
456
- }
457
- else {
458
- m = await prepareWAMessageMedia(message, options);
459
- }
460
- if ('viewOnce' in message && !!message.viewOnce) {
461
- m = { viewOnceMessage: { message: m } };
462
- }
463
- if ('mentions' in message && message.mentions?.length) {
464
- const messageType = Object.keys(m)[0];
465
- const key = m[messageType];
466
- if ('contextInfo' in key && !!key.contextInfo) {
467
- key.contextInfo.mentionedJid = message.mentions;
468
- }
469
- else if (key) {
470
- key.contextInfo = {
471
- mentionedJid: message.mentions
472
- };
473
- }
474
- }
475
- if ('edit' in message) {
476
- m = {
477
- protocolMessage: {
478
- key: message.edit,
479
- editedMessage: m,
480
- timestampMs: Date.now(),
481
- type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
482
- }
483
- };
484
- }
485
- if ('contextInfo' in message && !!message.contextInfo) {
486
- const messageType = Object.keys(m)[0];
487
- const key = m[messageType];
488
- if ('contextInfo' in key && !!key.contextInfo) {
489
- key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
490
- }
491
- else if (key) {
492
- key.contextInfo = message.contextInfo;
493
- }
494
- }
495
- return WAProto.Message.create(m);
401
+ break;
402
+ }
403
+ } else if ('ptv' in message && message.ptv) {
404
+ const {
405
+ videoMessage
406
+ } = await prepareWAMessageMedia({
407
+ video: message.video
408
+ }, options);
409
+ m.ptvMessage = videoMessage;
410
+ } else if ('product' in message) {
411
+ const {
412
+ imageMessage
413
+ } = await prepareWAMessageMedia({
414
+ image: message.product.productImage
415
+ }, options);
416
+ m.productMessage = WAProto.Message.ProductMessage.create({
417
+ ...message,
418
+ product: {
419
+ ...message.product,
420
+ productImage: imageMessage
421
+ }
422
+ });
423
+ } else if ('listReply' in message) {
424
+ m.listResponseMessage = {
425
+ ...message.listReply
426
+ };
427
+ } else if ('event' in message) {
428
+ m.eventMessage = {};
429
+ const startTime = Math.floor(message.event.startDate.getTime() / 1000);
430
+ if (message.event.call && options.getCallLink) {
431
+ const token = await options.getCallLink(message.event.call, {
432
+ startTime
433
+ });
434
+ m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
435
+ }
436
+ m.messageContextInfo = {
437
+ // encKey
438
+ messageSecret: message.event.messageSecret || randomBytes(32)
439
+ };
440
+ m.eventMessage.name = message.event.name;
441
+ m.eventMessage.description = message.event.description;
442
+ m.eventMessage.startTime = startTime;
443
+ m.eventMessage.endTime = message.event.endDate ? message.event.endDate.getTime() / 1000 : undefined;
444
+ m.eventMessage.isCanceled = message.event.isCancelled ?? false;
445
+ m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
446
+ m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
447
+ m.eventMessage.location = message.event.location;
448
+ } else if ('poll' in message) {
449
+ (_a = message.poll).selectableCount || (_a.selectableCount = 0);
450
+ (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
451
+ if (!Array.isArray(message.poll.values)) {
452
+ throw new Boom('Invalid poll values', {
453
+ statusCode: 400
454
+ });
455
+ }
456
+ if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
457
+ throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
458
+ statusCode: 400
459
+ });
460
+ }
461
+ m.messageContextInfo = {
462
+ // encKey
463
+ messageSecret: message.poll.messageSecret || randomBytes(32)
464
+ };
465
+ const pollCreationMessage = {
466
+ name: message.poll.name,
467
+ selectableOptionsCount: message.poll.selectableCount,
468
+ options: message.poll.values.map(optionName => ({
469
+ optionName
470
+ }))
471
+ };
472
+ if (message.poll.toAnnouncementGroup) {
473
+ // poll v2 is for community announcement groups (single select and multiple)
474
+ m.pollCreationMessageV2 = pollCreationMessage;
475
+ } else {
476
+ if (message.poll.selectableCount === 1) {
477
+ //poll v3 is for single select polls
478
+ m.pollCreationMessageV3 = pollCreationMessage;
479
+ } else {
480
+ // poll for multiple choice polls
481
+ m.pollCreationMessage = pollCreationMessage;
482
+ }
483
+ }
484
+ } else if ('sharePhoneNumber' in message) {
485
+ m.protocolMessage = {
486
+ type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
487
+ };
488
+ } else if ('requestPhoneNumber' in message) {
489
+ m.requestPhoneNumberMessage = {};
490
+ } else {
491
+ m = await prepareWAMessageMedia(message, options);
492
+ }
493
+ if ('viewOnce' in message && !!message.viewOnce) {
494
+ m = {
495
+ viewOnceMessage: {
496
+ message: m
497
+ }
498
+ };
499
+ }
500
+ if ('mentions' in message && message.mentions?.length) {
501
+ const messageType = Object.keys(m)[0];
502
+ const key = m[messageType];
503
+ if ('contextInfo' in key && !!key.contextInfo) {
504
+ key.contextInfo.mentionedJid = message.mentions;
505
+ } else if (key) {
506
+ key.contextInfo = {
507
+ mentionedJid: message.mentions
508
+ };
509
+ }
510
+ }
511
+ if ('edit' in message) {
512
+ m = {
513
+ protocolMessage: {
514
+ key: message.edit,
515
+ editedMessage: m,
516
+ timestampMs: Date.now(),
517
+ type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
518
+ }
519
+ };
520
+ }
521
+ if ('contextInfo' in message && !!message.contextInfo) {
522
+ const messageType = Object.keys(m)[0];
523
+ const key = m[messageType];
524
+ if ('contextInfo' in key && !!key.contextInfo) {
525
+ key.contextInfo = {
526
+ ...key.contextInfo,
527
+ ...message.contextInfo
528
+ };
529
+ } else if (key) {
530
+ key.contextInfo = message.contextInfo;
531
+ }
532
+ }
533
+ return WAProto.Message.create(m);
496
534
  };
497
535
  export const generateWAMessageFromContent = (jid, message, options) => {
498
- // set timestamp to now
499
- // if not specified
500
- if (!options.timestamp) {
501
- options.timestamp = new Date();
502
- }
503
- const innerMessage = normalizeMessageContent(message);
504
- const key = getContentType(innerMessage);
505
- const timestamp = unixTimestampSeconds(options.timestamp);
506
- const { quoted, userJid } = options;
507
- if (quoted && !isJidNewsletter(jid)) {
508
- const participant = quoted.key.fromMe
509
- ? userJid
510
- : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
511
- let quotedMsg = normalizeMessageContent(quoted.message);
512
- const msgType = getContentType(quotedMsg);
513
- // strip any redundant properties
514
- quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
515
- const quotedContent = quotedMsg[msgType];
516
- if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
517
- delete quotedContent.contextInfo;
518
- }
519
- const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {};
520
- contextInfo.participant = jidNormalizedUser(participant);
521
- contextInfo.stanzaId = quoted.key.id;
522
- contextInfo.quotedMessage = quotedMsg;
523
- // if a participant is quoted, then it must be a group
524
- // hence, remoteJid of group must also be entered
525
- if (jid !== quoted.key.remoteJid) {
526
- contextInfo.remoteJid = quoted.key.remoteJid;
527
- }
528
- if (contextInfo && innerMessage[key]) {
529
- /* @ts-ignore */
530
- innerMessage[key].contextInfo = contextInfo;
531
- }
532
- }
533
- if (
534
- // if we want to send a disappearing message
535
- !!options?.ephemeralExpiration &&
536
- // and it's not a protocol message -- delete, toggle disappear message
537
- key !== 'protocolMessage' &&
538
- // already not converted to disappearing message
539
- key !== 'ephemeralMessage' &&
540
- // newsletters don't support ephemeral messages
541
- !isJidNewsletter(jid)) {
542
- /* @ts-ignore */
543
- innerMessage[key].contextInfo = {
544
- ...(innerMessage[key].contextInfo || {}),
545
- expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
546
- //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
547
- };
548
- }
549
- message = WAProto.Message.create(message);
550
- const messageJSON = {
551
- key: {
552
- remoteJid: jid,
553
- fromMe: true,
554
- id: options?.messageId || generateMessageIDV2()
555
- },
556
- message: message,
557
- messageTimestamp: timestamp,
558
- messageStubParameters: [],
559
- participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined,
560
- status: WAMessageStatus.PENDING
536
+ // set timestamp to now
537
+ // if not specified
538
+ if (!options.timestamp) {
539
+ options.timestamp = new Date();
540
+ }
541
+ const innerMessage = normalizeMessageContent(message);
542
+ const key = getContentType(innerMessage);
543
+ const timestamp = unixTimestampSeconds(options.timestamp);
544
+ const {
545
+ quoted,
546
+ userJid
547
+ } = options;
548
+ if (quoted && !isJidNewsletter(jid)) {
549
+ const participant = quoted.key.fromMe ? userJid : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
550
+ let quotedMsg = normalizeMessageContent(quoted.message);
551
+ const msgType = getContentType(quotedMsg);
552
+ // strip any redundant properties
553
+ quotedMsg = proto.Message.create({
554
+ [msgType]: quotedMsg[msgType]
555
+ });
556
+ const quotedContent = quotedMsg[msgType];
557
+ if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
558
+ delete quotedContent.contextInfo;
559
+ }
560
+ const contextInfo = 'contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo || {};
561
+ contextInfo.participant = jidNormalizedUser(participant);
562
+ contextInfo.stanzaId = quoted.key.id;
563
+ contextInfo.quotedMessage = quotedMsg;
564
+ // if a participant is quoted, then it must be a group
565
+ // hence, remoteJid of group must also be entered
566
+ if (jid !== quoted.key.remoteJid) {
567
+ contextInfo.remoteJid = quoted.key.remoteJid;
568
+ }
569
+ if (contextInfo && innerMessage[key]) {
570
+ /* @ts-ignore */
571
+ innerMessage[key].contextInfo = contextInfo;
572
+ }
573
+ }
574
+ if (
575
+ // if we want to send a disappearing message
576
+ !!options?.ephemeralExpiration &&
577
+ // and it's not a protocol message -- delete, toggle disappear message
578
+ key !== 'protocolMessage' &&
579
+ // already not converted to disappearing message
580
+ key !== 'ephemeralMessage' &&
581
+ // newsletters don't support ephemeral messages
582
+ !isJidNewsletter(jid)) {
583
+ /* @ts-ignore */
584
+ innerMessage[key].contextInfo = {
585
+ ...(innerMessage[key].contextInfo || {}),
586
+ expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
587
+ //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
561
588
  };
562
- return WAProto.WebMessageInfo.create(messageJSON);
589
+ }
590
+ message = WAProto.Message.create(message);
591
+ const messageJSON = {
592
+ key: {
593
+ remoteJid: jid,
594
+ fromMe: true,
595
+ id: options?.messageId || generateMessageIDV2()
596
+ },
597
+ message: message,
598
+ messageTimestamp: timestamp,
599
+ messageStubParameters: [],
600
+ participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined,
601
+ status: WAMessageStatus.PENDING
602
+ };
603
+ return WAProto.WebMessageInfo.create(messageJSON);
563
604
  };
564
605
  export const generateWAMessage = async (jid, content, options) => {
565
- // ensure msg ID is with every log
566
- options.logger = options?.logger?.child({ msgId: options.messageId });
567
- // Pass jid in the options to generateWAMessageContent
568
- return generateWAMessageFromContent(jid, await generateWAMessageContent(content, { ...options, jid }), options);
606
+ // ensure msg ID is with every log
607
+ options.logger = options?.logger?.child({
608
+ msgId: options.messageId
609
+ });
610
+ // Pass jid in the options to generateWAMessageContent
611
+ return generateWAMessageFromContent(jid, await generateWAMessageContent(content, {
612
+ ...options,
613
+ jid
614
+ }), options);
569
615
  };
570
616
  /** Get the key to access the true type of content */
571
- export const getContentType = (content) => {
572
- if (content) {
573
- const keys = Object.keys(content);
574
- const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
575
- return key;
576
- }
617
+ export const getContentType = content => {
618
+ if (content) {
619
+ const keys = Object.keys(content);
620
+ const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
621
+ return key;
622
+ }
577
623
  };
578
624
  /**
579
625
  * Normalizes ephemeral, view once messages to regular message content
@@ -581,106 +627,96 @@ export const getContentType = (content) => {
581
627
  * @param content
582
628
  * @returns
583
629
  */
584
- export const normalizeMessageContent = (content) => {
585
- if (!content) {
586
- return undefined;
587
- }
588
- // set max iterations to prevent an infinite loop
589
- for (let i = 0; i < 5; i++) {
590
- const inner = getFutureProofMessage(content);
591
- if (!inner) {
592
- break;
593
- }
594
- content = inner.message;
595
- }
596
- return content;
597
- function getFutureProofMessage(message) {
598
- return (message?.ephemeralMessage ||
599
- message?.viewOnceMessage ||
600
- message?.documentWithCaptionMessage ||
601
- message?.viewOnceMessageV2 ||
602
- message?.viewOnceMessageV2Extension ||
603
- message?.editedMessage);
604
- }
630
+ export const normalizeMessageContent = content => {
631
+ if (!content) {
632
+ return undefined;
633
+ }
634
+ // set max iterations to prevent an infinite loop
635
+ for (let i = 0; i < 5; i++) {
636
+ const inner = getFutureProofMessage(content);
637
+ if (!inner) {
638
+ break;
639
+ }
640
+ content = inner.message;
641
+ }
642
+ return content;
643
+ function getFutureProofMessage(message) {
644
+ return message?.ephemeralMessage || message?.viewOnceMessage || message?.documentWithCaptionMessage || message?.viewOnceMessageV2 || message?.viewOnceMessageV2Extension || message?.editedMessage;
645
+ }
605
646
  };
606
647
  /**
607
648
  * Extract the true message content from a message
608
649
  * Eg. extracts the inner message from a disappearing message/view once message
609
650
  */
610
- export const extractMessageContent = (content) => {
611
- const extractFromTemplateMessage = (msg) => {
612
- if (msg.imageMessage) {
613
- return { imageMessage: msg.imageMessage };
614
- }
615
- else if (msg.documentMessage) {
616
- return { documentMessage: msg.documentMessage };
617
- }
618
- else if (msg.videoMessage) {
619
- return { videoMessage: msg.videoMessage };
620
- }
621
- else if (msg.locationMessage) {
622
- return { locationMessage: msg.locationMessage };
623
- }
624
- else {
625
- return {
626
- conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
627
- };
628
- }
629
- };
630
- content = normalizeMessageContent(content);
631
- if (content?.buttonsMessage) {
632
- return extractFromTemplateMessage(content.buttonsMessage);
633
- }
634
- if (content?.templateMessage?.hydratedFourRowTemplate) {
635
- return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
636
- }
637
- if (content?.templateMessage?.hydratedTemplate) {
638
- return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
639
- }
640
- if (content?.templateMessage?.fourRowTemplate) {
641
- return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
642
- }
643
- return content;
651
+ export const extractMessageContent = content => {
652
+ const extractFromTemplateMessage = msg => {
653
+ if (msg.imageMessage) {
654
+ return {
655
+ imageMessage: msg.imageMessage
656
+ };
657
+ } else if (msg.documentMessage) {
658
+ return {
659
+ documentMessage: msg.documentMessage
660
+ };
661
+ } else if (msg.videoMessage) {
662
+ return {
663
+ videoMessage: msg.videoMessage
664
+ };
665
+ } else if (msg.locationMessage) {
666
+ return {
667
+ locationMessage: msg.locationMessage
668
+ };
669
+ } else {
670
+ return {
671
+ conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
672
+ };
673
+ }
674
+ };
675
+ content = normalizeMessageContent(content);
676
+ if (content?.buttonsMessage) {
677
+ return extractFromTemplateMessage(content.buttonsMessage);
678
+ }
679
+ if (content?.templateMessage?.hydratedFourRowTemplate) {
680
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
681
+ }
682
+ if (content?.templateMessage?.hydratedTemplate) {
683
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
684
+ }
685
+ if (content?.templateMessage?.fourRowTemplate) {
686
+ return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
687
+ }
688
+ return content;
644
689
  };
645
690
  /**
646
691
  * Returns the device predicted by message ID
647
692
  */
648
- export const getDevice = (id) => /^3A.{18}$/.test(id)
649
- ? 'ios'
650
- : /^3E.{20}$/.test(id)
651
- ? 'web'
652
- : /^(.{21}|.{32})$/.test(id)
653
- ? 'android'
654
- : /^(3F|.{18}$)/.test(id)
655
- ? 'desktop'
656
- : 'unknown';
693
+ export const getDevice = id => /^3A.{18}$/.test(id) ? 'ios' : /^3E.{20}$/.test(id) ? 'web' : /^(.{21}|.{32})$/.test(id) ? 'android' : /^(3F|.{18}$)/.test(id) ? 'desktop' : 'unknown';
657
694
  /** Upserts a receipt in the message */
658
695
  export const updateMessageWithReceipt = (msg, receipt) => {
659
- msg.userReceipt = msg.userReceipt || [];
660
- const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
661
- if (recp) {
662
- Object.assign(recp, receipt);
663
- }
664
- else {
665
- msg.userReceipt.push(receipt);
666
- }
696
+ msg.userReceipt = msg.userReceipt || [];
697
+ const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
698
+ if (recp) {
699
+ Object.assign(recp, receipt);
700
+ } else {
701
+ msg.userReceipt.push(receipt);
702
+ }
667
703
  };
668
704
  /** Update the message with a new reaction */
669
705
  export const updateMessageWithReaction = (msg, reaction) => {
670
- const authorID = getKeyAuthor(reaction.key);
671
- const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID);
672
- reaction.text = reaction.text || '';
673
- reactions.push(reaction);
674
- msg.reactions = reactions;
706
+ const authorID = getKeyAuthor(reaction.key);
707
+ const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID);
708
+ reaction.text = reaction.text || '';
709
+ reactions.push(reaction);
710
+ msg.reactions = reactions;
675
711
  };
676
712
  /** Update the message with a new poll update */
677
713
  export const updateMessageWithPollUpdate = (msg, update) => {
678
- const authorID = getKeyAuthor(update.pollUpdateMessageKey);
679
- const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID);
680
- if (update.vote?.selectedOptions?.length) {
681
- reactions.push(update);
682
- }
683
- msg.pollUpdates = reactions;
714
+ const authorID = getKeyAuthor(update.pollUpdateMessageKey);
715
+ const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID);
716
+ if (update.vote?.selectedOptions?.length) {
717
+ reactions.push(update);
718
+ }
719
+ msg.pollUpdates = reactions;
684
720
  };
685
721
  /**
686
722
  * Aggregates all poll updates in a poll.
@@ -688,119 +724,129 @@ export const updateMessageWithPollUpdate = (msg, update) => {
688
724
  * @param meId your jid
689
725
  * @returns A list of options & their voters
690
726
  */
691
- export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
692
- const opts = message?.pollCreationMessage?.options ||
693
- message?.pollCreationMessageV2?.options ||
694
- message?.pollCreationMessageV3?.options ||
695
- [];
696
- const voteHashMap = opts.reduce((acc, opt) => {
697
- const hash = sha256(Buffer.from(opt.optionName || '')).toString();
698
- acc[hash] = {
699
- name: opt.optionName || '',
700
- voters: []
727
+ export function getAggregateVotesInPollMessage({
728
+ message,
729
+ pollUpdates
730
+ }, meId) {
731
+ const opts = message?.pollCreationMessage?.options || message?.pollCreationMessageV2?.options || message?.pollCreationMessageV3?.options || [];
732
+ const voteHashMap = opts.reduce((acc, opt) => {
733
+ const hash = sha256(Buffer.from(opt.optionName || '')).toString();
734
+ acc[hash] = {
735
+ name: opt.optionName || '',
736
+ voters: []
737
+ };
738
+ return acc;
739
+ }, {});
740
+ for (const update of pollUpdates || []) {
741
+ const {
742
+ vote
743
+ } = update;
744
+ if (!vote) {
745
+ continue;
746
+ }
747
+ for (const option of vote.selectedOptions || []) {
748
+ const hash = option.toString();
749
+ let data = voteHashMap[hash];
750
+ if (!data) {
751
+ voteHashMap[hash] = {
752
+ name: 'Unknown',
753
+ voters: []
701
754
  };
702
- return acc;
703
- }, {});
704
- for (const update of pollUpdates || []) {
705
- const { vote } = update;
706
- if (!vote) {
707
- continue;
708
- }
709
- for (const option of vote.selectedOptions || []) {
710
- const hash = option.toString();
711
- let data = voteHashMap[hash];
712
- if (!data) {
713
- voteHashMap[hash] = {
714
- name: 'Unknown',
715
- voters: []
716
- };
717
- data = voteHashMap[hash];
718
- }
719
- voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId));
720
- }
755
+ data = voteHashMap[hash];
756
+ }
757
+ voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId));
721
758
  }
722
- return Object.values(voteHashMap);
759
+ }
760
+ return Object.values(voteHashMap);
723
761
  }
724
762
  /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
725
- export const aggregateMessageKeysNotFromMe = (keys) => {
726
- const keyMap = {};
727
- for (const { remoteJid, id, participant, fromMe } of keys) {
728
- if (!fromMe) {
729
- const uqKey = `${remoteJid}:${participant || ''}`;
730
- if (!keyMap[uqKey]) {
731
- keyMap[uqKey] = {
732
- jid: remoteJid,
733
- participant: participant,
734
- messageIds: []
735
- };
736
- }
737
- keyMap[uqKey].messageIds.push(id);
738
- }
763
+ export const aggregateMessageKeysNotFromMe = keys => {
764
+ const keyMap = {};
765
+ for (const {
766
+ remoteJid,
767
+ id,
768
+ participant,
769
+ fromMe
770
+ } of keys) {
771
+ if (!fromMe) {
772
+ const uqKey = `${remoteJid}:${participant || ''}`;
773
+ if (!keyMap[uqKey]) {
774
+ keyMap[uqKey] = {
775
+ jid: remoteJid,
776
+ participant: participant,
777
+ messageIds: []
778
+ };
779
+ }
780
+ keyMap[uqKey].messageIds.push(id);
739
781
  }
740
- return Object.values(keyMap);
782
+ }
783
+ return Object.values(keyMap);
741
784
  };
742
785
  const REUPLOAD_REQUIRED_STATUS = [410, 404];
743
786
  /**
744
787
  * Downloads the given message. Throws an error if it's not a media message
745
788
  */
746
789
  export const downloadMediaMessage = async (message, type, options, ctx) => {
747
- const result = await downloadMsg().catch(async (error) => {
748
- if (ctx &&
749
- axios.isAxiosError(error) && // check if the message requires a reupload
750
- REUPLOAD_REQUIRED_STATUS.includes(error.response?.status)) {
751
- ctx.logger.info({ key: message.key }, 'sending reupload media request...');
752
- // request reupload
753
- message = await ctx.reuploadRequest(message);
754
- const result = await downloadMsg();
755
- return result;
756
- }
757
- throw error;
758
- });
759
- return result;
760
- async function downloadMsg() {
761
- const mContent = extractMessageContent(message.message);
762
- if (!mContent) {
763
- throw new Boom('No message present', { statusCode: 400, data: message });
764
- }
765
- const contentType = getContentType(mContent);
766
- let mediaType = contentType?.replace('Message', '');
767
- const media = mContent[contentType];
768
- if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
769
- throw new Boom(`"${contentType}" message is not a media message`);
770
- }
771
- let download;
772
- if ('thumbnailDirectPath' in media && !('url' in media)) {
773
- download = {
774
- directPath: media.thumbnailDirectPath,
775
- mediaKey: media.mediaKey
776
- };
777
- mediaType = 'thumbnail-link';
778
- }
779
- else {
780
- download = media;
781
- }
782
- const stream = await downloadContentFromMessage(download, mediaType, options);
783
- if (type === 'buffer') {
784
- const bufferArray = [];
785
- for await (const chunk of stream) {
786
- bufferArray.push(chunk);
787
- }
788
- return Buffer.concat(bufferArray);
789
- }
790
- return stream;
791
- }
790
+ const result = await downloadMsg().catch(async error => {
791
+ if (ctx && axios.isAxiosError(error) &&
792
+ // check if the message requires a reupload
793
+ REUPLOAD_REQUIRED_STATUS.includes(error.response?.status)) {
794
+ ctx.logger.info({
795
+ key: message.key
796
+ }, 'sending reupload media request...');
797
+ // request reupload
798
+ message = await ctx.reuploadRequest(message);
799
+ const result = await downloadMsg();
800
+ return result;
801
+ }
802
+ throw error;
803
+ });
804
+ return result;
805
+ async function downloadMsg() {
806
+ const mContent = extractMessageContent(message.message);
807
+ if (!mContent) {
808
+ throw new Boom('No message present', {
809
+ statusCode: 400,
810
+ data: message
811
+ });
812
+ }
813
+ const contentType = getContentType(mContent);
814
+ let mediaType = contentType?.replace('Message', '');
815
+ const media = mContent[contentType];
816
+ if (!media || typeof media !== 'object' || !('url' in media) && !('thumbnailDirectPath' in media)) {
817
+ throw new Boom(`"${contentType}" message is not a media message`);
818
+ }
819
+ let download;
820
+ if ('thumbnailDirectPath' in media && !('url' in media)) {
821
+ download = {
822
+ directPath: media.thumbnailDirectPath,
823
+ mediaKey: media.mediaKey
824
+ };
825
+ mediaType = 'thumbnail-link';
826
+ } else {
827
+ download = media;
828
+ }
829
+ const stream = await downloadContentFromMessage(download, mediaType, options);
830
+ if (type === 'buffer') {
831
+ const bufferArray = [];
832
+ for await (const chunk of stream) {
833
+ bufferArray.push(chunk);
834
+ }
835
+ return Buffer.concat(bufferArray);
836
+ }
837
+ return stream;
838
+ }
792
839
  };
793
840
  /** Checks whether the given message is a media message; if it is returns the inner content */
794
- export const assertMediaContent = (content) => {
795
- content = extractMessageContent(content);
796
- const mediaContent = content?.documentMessage ||
797
- content?.imageMessage ||
798
- content?.videoMessage ||
799
- content?.audioMessage ||
800
- content?.stickerMessage;
801
- if (!mediaContent) {
802
- throw new Boom('given message is not a media message', { statusCode: 400, data: content });
803
- }
804
- return mediaContent;
841
+ export const assertMediaContent = content => {
842
+ content = extractMessageContent(content);
843
+ const mediaContent = content?.documentMessage || content?.imageMessage || content?.videoMessage || content?.audioMessage || content?.stickerMessage;
844
+ if (!mediaContent) {
845
+ throw new Boom('given message is not a media message', {
846
+ statusCode: 400,
847
+ data: content
848
+ });
849
+ }
850
+ return mediaContent;
805
851
  };
806
852
  //# sourceMappingURL=messages.js.map