@skycodee/baileys 8.0.3 → 8.0.4

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