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