@zervonexx/baileys 5.0.0 → 5.0.1

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 (125) hide show
  1. package/LICENSE +22 -22
  2. package/README.md +4112 -4112
  3. package/WAProto/WAProtoCompile.js +322 -322
  4. package/WAProto/fetcher.js +67 -67
  5. package/WAProto/index.js +95 -95
  6. package/WAProto/parser.js +333 -333
  7. package/lib/Builders/AIRich.js +673 -673
  8. package/lib/Builders/auto.js +49 -49
  9. package/lib/Builders/base.js +144 -144
  10. package/lib/Builders/builders.js +588 -588
  11. package/lib/Builders/index.js +3 -3
  12. package/lib/Defaults/index.js +248 -248
  13. package/lib/Signal/index.js +2 -2
  14. package/lib/Signal/libsignal.js +526 -526
  15. package/lib/Signal/lid-mapping.js +282 -282
  16. package/lib/Socket/Client/index.js +1 -1
  17. package/lib/Socket/Client/types.js +9 -9
  18. package/lib/Socket/Client/websocket.js +83 -83
  19. package/lib/Socket/business.js +151 -151
  20. package/lib/Socket/chats.js +854 -854
  21. package/lib/Socket/communities.js +146 -146
  22. package/lib/Socket/groups.js +293 -293
  23. package/lib/Socket/index.js +14 -14
  24. package/lib/Socket/messages-recv.js +993 -993
  25. package/lib/Socket/messages-send.js +722 -722
  26. package/lib/Socket/mex.js +33 -33
  27. package/lib/Socket/newsletter.js +783 -783
  28. package/lib/Socket/registration.js +154 -154
  29. package/lib/Socket/socket.js +797 -797
  30. package/lib/Socket/spam-report.js +143 -143
  31. package/lib/Socket/username.js +81 -81
  32. package/lib/Socket/zervonex-handler.js +57 -57
  33. package/lib/Store/index.js +6 -6
  34. package/lib/Store/make-cache-manager-store.js +80 -80
  35. package/lib/Store/make-in-memory-store.js +426 -426
  36. package/lib/Store/make-ordered-dictionary.js +81 -81
  37. package/lib/Store/object-repository.js +30 -30
  38. package/lib/Store/reporting-info-store.js +37 -37
  39. package/lib/Types/Auth.js +1 -1
  40. package/lib/Types/Bussines.js +1 -1
  41. package/lib/Types/Call.js +1 -1
  42. package/lib/Types/Chat.js +7 -7
  43. package/lib/Types/Contact.js +1 -1
  44. package/lib/Types/Events.js +1 -1
  45. package/lib/Types/GroupMetadata.js +1 -1
  46. package/lib/Types/Label.js +24 -24
  47. package/lib/Types/LabelAssociation.js +6 -6
  48. package/lib/Types/Message.js +14 -14
  49. package/lib/Types/Newsletter.js +99 -99
  50. package/lib/Types/Product.js +1 -1
  51. package/lib/Types/Signal.js +1 -1
  52. package/lib/Types/Socket.js +14 -14
  53. package/lib/Types/State.js +26 -26
  54. package/lib/Types/USync.js +1 -1
  55. package/lib/Types/index.js +30 -30
  56. package/lib/Utils/auth-utils.js +159 -159
  57. package/lib/Utils/baileys-event-stream.js +32 -32
  58. package/lib/Utils/bot-capabilities.js +40 -40
  59. package/lib/Utils/bot-planning-replay.js +43 -43
  60. package/lib/Utils/browser-utils.js +29 -29
  61. package/lib/Utils/business.js +74 -74
  62. package/lib/Utils/chat-utils.js +316 -316
  63. package/lib/Utils/companion-reg-client-utils.js +19 -19
  64. package/lib/Utils/consumer-application.js +37 -37
  65. package/lib/Utils/crypto.js +52 -52
  66. package/lib/Utils/cstoken.js +14 -14
  67. package/lib/Utils/decode-wa-message.js +199 -199
  68. package/lib/Utils/event-buffer.js +272 -272
  69. package/lib/Utils/extras.js +186 -186
  70. package/lib/Utils/generics.js +194 -194
  71. package/lib/Utils/history.js +50 -50
  72. package/lib/Utils/identity-change-handler.js +18 -18
  73. package/lib/Utils/index.js +40 -40
  74. package/lib/Utils/link-preview.js +50 -50
  75. package/lib/Utils/logger.js +2 -2
  76. package/lib/Utils/lt-hash.js +3 -3
  77. package/lib/Utils/make-mutex.js +15 -15
  78. package/lib/Utils/message-composer.js +61 -61
  79. package/lib/Utils/message-retry-manager.js +47 -47
  80. package/lib/Utils/messages-media.js +501 -501
  81. package/lib/Utils/messages.js +942 -942
  82. package/lib/Utils/meta-ai-msmsg.js +121 -121
  83. package/lib/Utils/meta-compositing.js +74 -74
  84. package/lib/Utils/modern-messages.js +234 -234
  85. package/lib/Utils/native-flow.js +80 -80
  86. package/lib/Utils/noise-handler.js +160 -160
  87. package/lib/Utils/pre-key-manager.js +75 -75
  88. package/lib/Utils/process-message.js +400 -400
  89. package/lib/Utils/reporting-utils.js +170 -170
  90. package/lib/Utils/signal.js +166 -166
  91. package/lib/Utils/spam-report-utils.js +165 -165
  92. package/lib/Utils/sync-action-utils.js +33 -33
  93. package/lib/Utils/tc-token-utils.js +153 -153
  94. package/lib/Utils/use-keyv-auth-state.js +199 -199
  95. package/lib/Utils/use-multi-file-auth-state.js +83 -83
  96. package/lib/Utils/validate-connection.js +171 -171
  97. package/lib/WABinary/constants.js +1320 -1320
  98. package/lib/WABinary/decode.js +151 -151
  99. package/lib/WABinary/encode.js +139 -139
  100. package/lib/WABinary/generic-utils.js +202 -202
  101. package/lib/WABinary/index.js +6 -6
  102. package/lib/WABinary/jid-utils.js +235 -235
  103. package/lib/WABinary/types.js +4 -4
  104. package/lib/WAM/BinaryInfo.js +9 -9
  105. package/lib/WAM/constants.js +22852 -22852
  106. package/lib/WAM/encode.js +149 -149
  107. package/lib/WAM/index.js +3 -3
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
  120. package/lib/WAUSync/Protocols/index.js +12 -12
  121. package/lib/WAUSync/USyncQuery.js +88 -88
  122. package/lib/WAUSync/USyncUser.js +20 -20
  123. package/lib/WAUSync/index.js +3 -3
  124. package/lib/index.js +66 -66
  125. package/package.json +191 -192
@@ -1,502 +1,502 @@
1
- import { Boom } from '@hapi/boom'
2
- import { spawn } from 'child_process'
3
- import * as Crypto from 'crypto'
4
- import { once } from 'events'
5
- import { createWriteStream, createReadStream, mkdirSync, promises as fs } from 'fs'
6
- import { join } from 'path'
7
- import { Transform } from 'stream'
8
- import urlRegexSafe from 'url-regex-safe'
9
- import { tmpdir as osTmpdir } from 'os'
10
- import { fileTypeFromBuffer } from 'file-type'
11
- import intoStream from 'into-stream'
12
- import { getStreamAsBuffer } from 'get-stream'
13
- import got from 'got'
14
- import { temporaryFile, temporaryDirectory } from 'tempy'
15
- import { proto } from '../../WAProto/index.js'
16
- import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP } from '../Defaults/index.js'
17
- import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary/index.js'
18
- import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto.js'
19
- import { generateMessageIDV2 } from './generics.js'
20
-
21
- // ─── TMP ──────────────────────────────────────────────────────────────────────
22
-
23
- const BAILEYS_TMP_DIR = (() => {
24
- for (const dir of [join(process.cwd(), '.b-tmp'), join(osTmpdir(), '.b-tmp')]) {
25
- try {
26
- mkdirSync(dir, { recursive: true, mode: 0o700 })
27
- process.env.TMPDIR = dir
28
- process.env.VIPS_TMPDIR = dir
29
- process.env.VIPS_DISC_THRESHOLD = '999999999999'
30
- return dir
31
- } catch { }
32
- }
33
- throw new Error('No writable tmp directory found')
34
- })()
35
-
36
- export const tmpdir = () => BAILEYS_TMP_DIR
37
- const _tmpFile = (ext = '') => temporaryFile({ rootDirectory: BAILEYS_TMP_DIR, ...(ext && { extension: ext.replace('.', '') }) })
38
- const _tmpDir = (prefix = '') => temporaryDirectory({ rootDirectory: BAILEYS_TMP_DIR, ...(prefix && { prefix }) })
39
- const _cleanupFiles = async (...paths) => Promise.all(paths.map(p => p ? fs.unlink(p).catch(() => { }) : Promise.resolve()))
40
-
41
- // ─── FFMPEG ───────────────────────────────────────────────────────────────────
42
-
43
- let _ffmpegPath = null
44
- const getFfmpegPath = async () => {
45
- if (_ffmpegPath) return _ffmpegPath
46
- try { const { default: p } = await import('ffmpeg-static'); if (p) return (_ffmpegPath = p) } catch { }
47
- return (_ffmpegPath = 'ffmpeg')
48
- }
49
-
50
- const _spawnFfmpeg = (ffmpegPath, args) => new Promise((resolve, reject) => {
51
- const ff = spawn(ffmpegPath, args, { stdio: ['ignore', 'ignore', 'pipe'] })
52
- let stderr = ''
53
- ff.stderr.on('data', d => { stderr += d })
54
- ff.on('close', code => code === 0 ? resolve() : reject(new Error(`FFmpeg exited ${code}: ${stderr.slice(-500)}`)))
55
- ff.on('error', reject)
56
- })
57
-
58
- const _tmpConvert = async (buffer, inSuffix, outSuffix, ffmpegArgs) => {
59
- const inputPath = _tmpFile(inSuffix)
60
- const outputPath = _tmpFile(outSuffix)
61
- await fs.writeFile(inputPath, buffer)
62
- try { await _spawnFfmpeg(await getFfmpegPath(), ['-y', '-i', inputPath, ...ffmpegArgs, outputPath]); return await fs.readFile(outputPath) }
63
- finally { await _cleanupFiles(inputPath, outputPath) }
64
- }
65
-
66
- const _animatedWebpToMp4 = async (buffer, ffmpegPath) => {
67
- const { default: sharp } = await import('sharp')
68
- const meta = await sharp(buffer, { animated: true }).metadata()
69
- const pages = meta.pages ?? 1, pageH = meta.pageHeight ?? Math.round(meta.height / pages)
70
- const delays = meta.delay?.length === pages ? meta.delay : Array(pages).fill(100)
71
- const frameDir = _tmpDir('webp-frames'), concatFile = _tmpFile('txt'), outputPath = _tmpFile('mp4')
72
- await fs.mkdir(frameDir, { recursive: true })
73
- try {
74
- const { data, info } = await sharp(buffer, { animated: true }).raw().toBuffer({ resolveWithObject: true })
75
- const frameSize = info.width * pageH * info.channels
76
- const framePaths = []
77
- for (let i = 0; i < pages; i++) {
78
- const fp = join(frameDir, `f${i}.png`)
79
- await sharp(data.subarray(i * frameSize, (i + 1) * frameSize), { raw: { width: info.width, height: pageH, channels: info.channels } }).png().toFile(fp)
80
- framePaths.push(fp)
81
- }
82
- const lines = framePaths.flatMap((p, i) => [`file '${p}'`, `duration ${(delays[i] / 1000).toFixed(6)}`])
83
- lines.push(`file '${framePaths[framePaths.length - 1]}'`)
84
- await fs.writeFile(concatFile, lines.join('\n'))
85
- await _spawnFfmpeg(ffmpegPath, ['-y', '-f', 'concat', '-safe', '0', '-i', concatFile, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '18', '-pix_fmt', 'yuv420p', '-vf', 'scale=trunc(iw/2)*2:trunc(ih/2)*2', '-movflags', '+faststart', '-map_metadata', '-1', outputPath])
86
- return await fs.readFile(outputPath)
87
- } finally {
88
- const files = await fs.readdir(frameDir).catch(() => [])
89
- await Promise.all(files.map(f => fs.unlink(join(frameDir, f)).catch(() => { })))
90
- await fs.rmdir(frameDir).catch(() => { })
91
- await _cleanupFiles(concatFile, outputPath)
92
- }
93
- }
94
-
95
- const convertToOpusBuffer = async (buffer, logger) => {
96
- const detected = await fileTypeFromBuffer(buffer)
97
- if (detected?.ext === 'opus') return buffer
98
- return _tmpConvert(buffer, detected?.ext ? `.${detected.ext}` : '', '.ogg', ['-vn', '-c:a', 'libopus', '-b:a', '128k', '-ar', '48000', '-ac', '1', '-vbr', 'on', '-compression_level', '10', '-frame_duration', '20', '-application', 'audio', '-map_metadata', '-1'])
99
- }
100
-
101
- const convertToMp4Buffer = async (buffer, logger) => {
102
- try {
103
- const { default: sharp } = await import('sharp')
104
- const meta = await sharp(buffer, { animated: true }).metadata()
105
- if (meta.format === 'webp' && (meta.pages ?? 1) > 1) return await _animatedWebpToMp4(buffer, await getFfmpegPath())
106
- } catch { }
107
- const detected = await fileTypeFromBuffer(buffer)
108
- return _tmpConvert(buffer, detected?.ext ? `.${detected.ext}` : '', '.mp4', ['-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-pix_fmt', 'yuv420p', '-vf', 'scale=trunc(iw/2)*2:trunc(ih/2)*2', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', '-map_metadata', '-1'])
109
- }
110
-
111
- // ─── IMAGE ────────────────────────────────────────────────────────────────────
112
-
113
- export const getImageProcessingLibrary = async () => {
114
- const [jimp, sharp] = await Promise.all([import('jimp').catch(() => null), import('sharp').catch(() => null)])
115
- if (sharp) return { sharp }
116
- if (jimp) return { jimp }
117
- throw new Boom('No image processing library available')
118
- }
119
-
120
- export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
121
- if (!Buffer.isBuffer(bufferOrFilePath)) bufferOrFilePath = await normalizeToBuffer(bufferOrFilePath)
122
- const lib = await getImageProcessingLibrary()
123
- if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
124
- const img = lib.sharp.default(bufferOrFilePath)
125
- const { width: w, height: h } = await img.metadata()
126
- return { buffer: await img.resize(width).jpeg({ quality: 95 }).toBuffer(), original: { width: w, height: h } }
127
- }
128
- if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
129
- const jimp = await lib.jimp.Jimp.read(bufferOrFilePath)
130
- return { buffer: await jimp.resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 95 }), original: { width: jimp.width, height: jimp.height } }
131
- }
132
- throw new Boom('No image processing library available')
133
- }
134
-
135
- export const generateProfilePicture = async mediaUpload => {
136
- const src = await normalizeToBuffer(mediaUpload)
137
- const lib = await getImageProcessingLibrary()
138
- if ('sharp' in lib && typeof lib.sharp?.default === 'function') return { img: await lib.sharp.default(src).resize(720, 720, { fit: 'inside' }).jpeg({ quality: 80 }).toBuffer() }
139
- if ('jimp' in lib && typeof lib.jimp?.read === 'function') {
140
- const { read, MIME_JPEG } = lib.jimp
141
- const image = await read(src)
142
- return { img: await image.crop(0, 0, image.getWidth(), image.getHeight()).scaleToFit(720, 720).getBufferAsync(MIME_JPEG) }
143
- }
144
- throw new Boom('No image processing library available')
145
- }
146
-
147
- export const generateThumbnail = async (file, mediaType, options) => {
148
- if (mediaType === 'image') {
149
- const { buffer, original } = await extractImageThumb(file)
150
- return { thumbnail: buffer.toString('base64'), originalImageDimensions: (original.width && original.height) ? original : undefined }
151
- }
152
- if (mediaType === 'video') {
153
- const imgFilename = join(tmpdir(), generateMessageIDV2() + '.jpg')
154
- try {
155
- const ff = await getFfmpegPath()
156
- await new Promise((resolve, reject) => {
157
- const proc = spawn(ff, ['-ss', '00:00:00', '-i', file, '-y', '-vf', 'scale=32:-1', '-vframes', '1', '-f', 'image2', imgFilename])
158
- proc.on('close', code => code === 0 ? resolve() : reject(new Error(`FFmpeg thumb exit ${code}`)))
159
- proc.on('error', reject)
160
- })
161
- const thumbnail = (await fs.readFile(imgFilename)).toString('base64')
162
- await fs.unlink(imgFilename).catch(() => { })
163
- return { thumbnail, originalImageDimensions: undefined }
164
- } catch (err) { options.logger?.debug('could not generate video thumb: ' + err) }
165
- }
166
- return { thumbnail: undefined, originalImageDimensions: undefined }
167
- }
168
-
169
- // ─── STREAM ───────────────────────────────────────────────────────────────────
170
-
171
- export const toReadable = input => intoStream(input)
172
- export const getHttpStream = (url, options = {}) => got.stream(url.toString(), { headers: { ...(options.headers ?? {}), Origin: DEFAULT_ORIGIN } })
173
- export const isHttpUrl = (() => {
174
- const r = urlRegexSafe({ exact: true, auth: true })
175
- return str => typeof str === 'string' && r.test(str)
176
- })()
177
-
178
- export const getStream = async (item, opts) => {
179
- if (!item) throw new Boom('Item is required for getStream', { statusCode: 400 })
180
- if (Buffer.isBuffer(item)) return { stream: intoStream(item), type: 'buffer' }
181
- if (item?.type === 'Buffer' && Array.isArray(item?.data)) return { stream: intoStream(Buffer.from(item.data)), type: 'buffer' }
182
- if (ArrayBuffer.isView(item)) return { stream: intoStream(Buffer.from(item.buffer, item.byteOffset, item.byteLength)), type: 'buffer' }
183
- if (item instanceof ArrayBuffer) return { stream: intoStream(Buffer.from(item)), type: 'buffer' }
184
- if (Array.isArray(item)) return { stream: intoStream(Buffer.from(item)), type: 'buffer' }
185
- if (typeof item?.pipe === 'function' || typeof item?.[Symbol.asyncIterator] === 'function') return { stream: intoStream(await getStreamAsBuffer(item)), type: 'buffer' }
186
- if (item?.url && Buffer.isBuffer(item.url)) return { stream: intoStream(item.url), type: 'buffer' }
187
- if (item?.url && typeof item.url === 'string' && item.url.startsWith('data:')) return { stream: intoStream(Buffer.from(item.url.split(',')[1], 'base64')), type: 'buffer' }
188
- const u = item?.url ? item.url.toString() : typeof item === 'string' ? item : null
189
- if (u) {
190
- if (u.startsWith('data:')) return { stream: intoStream(Buffer.from(u.split(',')[1], 'base64')), type: 'buffer' }
191
- if (isHttpUrl(u)) return { stream: intoStream(await getStreamAsBuffer(got.stream(u, { headers: { ...(opts?.headers ?? {}), Origin: DEFAULT_ORIGIN } }))), type: 'remote' }
192
- if (/^(?:[A-Za-z0-9+/]{4})+(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(u)) return { stream: intoStream(Buffer.from(u, 'base64')), type: 'buffer' }
193
- return { stream: createReadStream(u), type: 'file' }
194
- }
195
- try {
196
- return { stream: intoStream(item), type: 'buffer' }
197
- } catch {
198
- throw new Boom(`Invalid input type for getStream: ${typeof item}`, { statusCode: 400 })
199
- }
200
- }
201
-
202
- export const toBuffer = async stream => {
203
- if (Buffer.isBuffer(stream)) return stream
204
- const { stream: resolved } = await getStream(stream)
205
- return getStreamAsBuffer(resolved)
206
- }
207
-
208
- export const normalizeToBuffer = async input => {
209
- if (!input) return undefined
210
- return toBuffer(input)
211
- }
212
-
213
- export const resolveToMediaUrl = async input => {
214
- if (isHttpUrl(input)) return input
215
- if (isHttpUrl(input?.url)) return input.url
216
- const buf = await normalizeToBuffer(input)
217
- if (!buf) throw new TypeError('Could not resolve input to buffer')
218
- const { Catbox, Pomf, Quax, Cloudku, Litterbox } = await import('@zanixongroup/uploader')
219
- const providers = [Catbox, Pomf, Quax, Cloudku, Litterbox].sort(() => Math.random() - 0.5)
220
- let lastError
221
- for (const provider of providers) {
222
- try { const url = await provider(buf); if (url) return url } catch (err) { lastError = err }
223
- }
224
- throw new TypeError(`All providers failed: ${lastError?.message}`)
225
- }
226
-
227
- // ─── HKDF ─────────────────────────────────────────────────────────────────────
228
-
229
- export const hkdfInfoKey = type => `WhatsApp ${MEDIA_HKDF_KEY_MAPPING[type]} Keys`
230
-
231
- export const getMediaKeys = async (buffer, mediaType) => {
232
- if (!buffer) throw new Boom('Cannot derive from empty media key')
233
- buffer = await normalizeToBuffer(buffer)
234
- if (!buffer?.length) throw new Boom('Cannot derive from empty media key')
235
- const k = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) })
236
- return { iv: k.subarray(0, 16), cipherKey: k.subarray(16, 48), macKey: k.subarray(48, 80) }
237
- }
238
-
239
- // ─── AUDIO ────────────────────────────────────────────────────────────────────
240
-
241
- export const mediaMessageSHA256B64 = message => { const media = Object.values(message)[0]; return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64') }
242
-
243
- export const getAudioDuration = async (buffer, logger) => {
244
- try {
245
- const mm = await import('music-metadata')
246
- if (Buffer.isBuffer(buffer)) return (await mm.parseBuffer(buffer, undefined, { duration: true })).format.duration
247
- if (typeof buffer === 'string') return (await mm.parseFile(buffer, { duration: true })).format.duration
248
- return (await mm.parseStream(buffer, undefined, { duration: true })).format.duration
249
- } catch (e) { logger?.debug({ trace: e?.stack || e }, 'failed to determine audio duration'); return undefined }
250
- }
251
-
252
- export const getAudioWaveform = async (buffer, logger) => {
253
- const fallback = new Uint8Array([0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99])
254
- try {
255
- const rawPCM = await new Promise(async (resolve, reject) => {
256
- const chunks = [], ff = spawn(await getFfmpegPath(), ['-i', 'pipe:0', '-f', 's16le', '-ac', '1', '-ar', '16000', 'pipe:1'], { stdio: ['pipe', 'pipe', 'pipe'] })
257
- let stderr = ''
258
- ff.stdout.on('data', d => chunks.push(d))
259
- ff.stderr.on('data', d => { stderr += d })
260
- ff.on('close', code => code === 0 ? resolve(Buffer.concat(chunks)) : reject(new Error(`FFmpeg waveform exit ${code}: ${stderr.slice(-300)}`)))
261
- ff.on('error', reject)
262
- ff.stdin.end(Buffer.isBuffer(buffer) ? buffer : typeof buffer === 'string' ? await fs.readFile(buffer) : await toBuffer(buffer))
263
- })
264
- if (!rawPCM.length) throw new Error('empty PCM output')
265
- const samples = rawPCM.length >> 1
266
- const blockSize = Math.max(1, Math.floor(samples / 64))
267
- const blockSums = new Float64Array(64)
268
- for (let i = 0; i < samples; i++) blockSums[Math.min(63, Math.floor(i / blockSize))] += Math.abs(rawPCM.readInt16LE(i * 2))
269
- const avg = Array.from(blockSums, sum => sum / blockSize / 32768)
270
- const max = Math.max(...avg, 0.0001)
271
- return new Uint8Array(avg.map(v => Math.max(0, Math.min(100, Math.round((v / max) * 100)))))
272
- } catch (e) { logger?.debug({ trace: e?.stack || e }, 'failed to generate waveform, using fallback'); return fallback }
273
- }
274
-
275
- // ─── PREPARE / ENCRYPT ────────────────────────────────────────────────────────
276
-
277
- export const prepareStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts, convertVideo } = {}) => {
278
- const { stream, type } = await getStream(media, opts)
279
- let buffer = await toBuffer(stream)
280
- if (mediaType === 'video' && convertVideo) {
281
- try { buffer = await convertToMp4Buffer(buffer, logger) } catch (e) { logger?.error('failed to convert video:', e) }
282
- }
283
- let bodyPath, didSaveToTmpPath = false
284
- try {
285
- if (type === 'file') bodyPath = typeof media === 'string' ? media : media.url
286
- else if (saveOriginalFileIfRequired) { bodyPath = join(tmpdir(), mediaType + generateMessageIDV2()); await fs.writeFile(bodyPath, buffer); didSaveToTmpPath = true }
287
- return {
288
- mediaKey: undefined, encWriteStream: buffer, fileLength: buffer.length,
289
- fileSha256: Crypto.createHash('sha256').update(buffer).digest(),
290
- fileEncSha256: undefined, bodyPath, didSaveToTmpPath,
291
- cleanup: async () => { if (didSaveToTmpPath && bodyPath) await fs.unlink(bodyPath).catch(() => { }) },
292
- }
293
- } catch (error) {
294
- if (didSaveToTmpPath && bodyPath) await fs.unlink(bodyPath).catch(() => { })
295
- throw error
296
- }
297
- }
298
-
299
- export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts, mediaKey: providedMediaKey, isPtt, forceOpus, convertVideo } = {}) => {
300
- const { stream, type } = await getStream(media, opts)
301
- let finalStream = stream, opusConverted = false
302
- if (mediaType === 'audio' && (isPtt === true || forceOpus === true)) {
303
- try { finalStream = toReadable(await convertToOpusBuffer(await toBuffer(stream), logger)); opusConverted = true }
304
- catch { finalStream = (await getStream(media, opts)).stream }
305
- }
306
- if (mediaType === 'video' && convertVideo === true) finalStream = toReadable(await convertToMp4Buffer(await toBuffer(finalStream), logger))
307
-
308
- const mediaKey = providedMediaKey || Crypto.randomBytes(32)
309
- const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType)
310
- const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv)
311
- const hmac = Crypto.createHmac('sha256', macKey).update(iv)
312
- const sha256Plain = Crypto.createHash('sha256'), sha256Enc = Crypto.createHash('sha256')
313
- const encChunks = [], plainChunks = saveOriginalFileIfRequired ? [] : null
314
- let fileLength = 0, encFilePath = null, originalFilePath = null
315
-
316
- try {
317
- for await (const data of finalStream) {
318
- fileLength += data.length
319
- if (type === 'remote' && opts?.maxContentLength && fileLength > opts.maxContentLength) throw new Boom('content length exceeded', { data: { media, type } })
320
- plainChunks?.push(data)
321
- sha256Plain.update(data)
322
- const encrypted = aes.update(data)
323
- sha256Enc.update(encrypted); hmac.update(encrypted); encChunks.push(encrypted)
324
- }
325
- const finalData = aes.final()
326
- sha256Enc.update(finalData); hmac.update(finalData); encChunks.push(finalData)
327
- const mac = hmac.digest().subarray(0, 10)
328
- sha256Enc.update(mac); encChunks.push(mac)
329
- finalStream.destroy()
330
-
331
- const encBuffer = Buffer.concat(encChunks)
332
- const fileEncSha256 = sha256Enc.digest()
333
- const fileSha256 = sha256Plain.digest()
334
-
335
- if (plainChunks) {
336
- try { originalFilePath = join(tmpdir(), mediaType + generateMessageIDV2() + '-original'); await fs.writeFile(originalFilePath, Buffer.concat(plainChunks)) }
337
- catch { originalFilePath = null }
338
- }
339
- let useMemory = false
340
- try { encFilePath = join(tmpdir(), mediaType + generateMessageIDV2() + '-enc'); await fs.writeFile(encFilePath, encBuffer) }
341
- catch { encFilePath = null; useMemory = true }
342
-
343
- return { mediaKey, bodyPath: originalFilePath, encFilePath, encBuffer: useMemory ? encBuffer : null, mac, fileEncSha256, fileSha256, fileLength, opusConverted, cleanup: async () => _cleanupFiles(encFilePath, originalFilePath) }
344
- } catch (error) {
345
- aes.destroy(); hmac.destroy(); sha256Plain.destroy(); sha256Enc.destroy(); finalStream.destroy()
346
- await _cleanupFiles(encFilePath, originalFilePath)
347
- throw error
348
- }
349
- }
350
-
351
- // ─── RAW UPLOAD ───────────────────────────────────────────────────────────────
352
-
353
- export const getRawMediaUploadData = async (media, mediaType) => {
354
- const { stream } = await getStream(media)
355
- const hasher = Crypto.createHash('sha256')
356
- const filePath = join(tmpdir(), mediaType + generateMessageIDV2())
357
- const fileWriteStream = createWriteStream(filePath)
358
- let fileLength = 0
359
- try {
360
- for await (const data of stream) { fileLength += data.length; hasher.update(data); if (!fileWriteStream.write(data)) await once(fileWriteStream, 'drain') }
361
- fileWriteStream.end()
362
- await once(fileWriteStream, 'finish')
363
- stream.destroy()
364
- return { filePath, fileSha256: hasher.digest(), fileLength }
365
- } catch (error) {
366
- fileWriteStream.destroy(); stream.destroy()
367
- await fs.unlink(filePath).catch(() => { })
368
- throw error
369
- }
370
- }
371
-
372
- // ─── DOWNLOAD ─────────────────────────────────────────────────────────────────
373
-
374
- const DEF_HOST = 'mmg.whatsapp.net'
375
- const AES_CHUNK_SIZE = 16
376
- const toSmallestChunkSize = num => Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE
377
-
378
- export const getUrlFromDirectPath = directPath => directPath ? (directPath.startsWith('http') ? directPath : `https://${DEF_HOST}${directPath.startsWith('/') ? '' : '/'}${directPath}`) : undefined
379
-
380
- export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
381
- const downloadUrl = url?.startsWith('https://mmg.whatsapp.net/') ? url : getUrlFromDirectPath(directPath)
382
- if (!downloadUrl) throw new Boom('No valid media URL or directPath present', { statusCode: 400 })
383
- return downloadEncryptedContent(downloadUrl, await getMediaKeys(mediaKey, type), opts)
384
- }
385
-
386
- export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
387
- let bytesFetched = 0, startChunk = 0, firstBlockIsIV = false
388
- if (startByte) {
389
- const chunk = toSmallestChunkSize(startByte || 0)
390
- if (chunk) { startChunk = chunk - AES_CHUNK_SIZE; bytesFetched = chunk; firstBlockIsIV = true }
391
- }
392
- const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined
393
- const headers = { ...(options?.headers ? (Array.isArray(options.headers) ? Object.fromEntries(options.headers) : options.headers) : {}), Origin: DEFAULT_ORIGIN }
394
- if (startChunk || endChunk) headers.Range = `bytes=${startChunk}-${endChunk || ''}`
395
- const fetched = getHttpStream(downloadUrl, { ...(options || {}), headers })
396
- let remainingBytes = Buffer.from([]), aes
397
- const pushBytes = (bytes, push) => {
398
- if (startByte || endByte) {
399
- const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0)
400
- const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0)
401
- push(bytes.subarray(start, end)); bytesFetched += bytes.length
402
- } else push(bytes)
403
- }
404
- return fetched.pipe(new Transform({
405
- transform(chunk, _, callback) {
406
- let data = Buffer.concat([remainingBytes, chunk])
407
- const decryptLength = toSmallestChunkSize(data.length)
408
- remainingBytes = data.subarray(decryptLength); data = data.subarray(0, decryptLength)
409
- if (!aes) {
410
- let ivValue = iv
411
- if (firstBlockIsIV) { ivValue = data.subarray(0, AES_CHUNK_SIZE); data = data.subarray(AES_CHUNK_SIZE) }
412
- aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue)
413
- if (endByte) aes.setAutoPadding(false)
414
- }
415
- try { pushBytes(aes.update(data), b => this.push(b)); callback() } catch (error) { callback(error) }
416
- },
417
- final(callback) { try { pushBytes(aes.final(), b => this.push(b)); callback() } catch (error) { callback(error) } }
418
- }), { end: true })
419
- }
420
-
421
- // ─── UPLOAD ───────────────────────────────────────────────────────────────────
422
-
423
- export const encodeBase64EncodedStringForUpload = b64 => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''))
424
-
425
- export const extensionForMediaMessage = message => {
426
- const type = Object.keys(message)[0]
427
- if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') return '.jpeg'
428
- return message[type].mimetype.split(';')[0]?.split('/')[1]
429
- }
430
-
431
- const httpsPost = async (url, body, headers, signal) => {
432
- const response = await got.post(url, { body: Buffer.isBuffer(body) ? body : await getStreamAsBuffer(body), headers: { ...headers, Origin: DEFAULT_ORIGIN }, signal, throwHttpErrors: false })
433
- let json = null
434
- try { json = JSON.parse(response.body) } catch { }
435
- return { status: response.statusCode, ok: response.statusCode >= 200 && response.statusCode < 300, json: async () => json }
436
- }
437
-
438
- export const getWAUploadToServer = ({ customUploadHosts, logger, options }, refreshMediaConn) => async (stream, { mediaType, fileEncSha256B64, newsletter, timeoutMs }) => {
439
- let reqBody
440
- try { reqBody = await toBuffer(stream) } catch (err) { logger?.error({ err: err.message }, 'failed to prepare upload body'); throw err }
441
- fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64)
442
- let media = MEDIA_PATH_MAP[mediaType]
443
- if (newsletter) media = media?.replace('/mms/', '/newsletter/newsletter-')
444
- if (!media) throw new Boom(`No media path found for type: ${mediaType}`, { statusCode: 400 })
445
- let uploadInfo = await refreshMediaConn(false)
446
- const hosts = [...(customUploadHosts ?? []), ...(uploadInfo.hosts ?? [])]
447
- if (!hosts.length) throw new Boom('No upload hosts available', { statusCode: 503 })
448
- let urls, lastError
449
- for (const { hostname, maxContentLengthBytes } of hosts) {
450
- for (let attempt = 1; attempt <= 2; attempt++) {
451
- try {
452
- if (attempt > 1) { uploadInfo = await refreshMediaConn(true); reqBody = await toBuffer(stream) }
453
- if (maxContentLengthBytes && Buffer.isBuffer(reqBody) && reqBody.length > maxContentLengthBytes) break
454
- const auth = encodeURIComponent(uploadInfo.auth)
455
- const url = `https://${hostname}${media}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`
456
- const controller = new AbortController()
457
- const timer = timeoutMs ? setTimeout(() => controller.abort(), timeoutMs) : null
458
- let response
459
- try { response = await httpsPost(url, reqBody, { ...(Array.isArray(options?.headers) ? Object.fromEntries(options.headers) : (options?.headers ?? {})), 'Content-Type': 'application/octet-stream', Origin: DEFAULT_ORIGIN }, controller.signal) }
460
- finally { if (timer) clearTimeout(timer) }
461
- const result = await response.json().catch(() => null)
462
- if (result?.url || result?.directPath) { urls = { mediaUrl: result.url, directPath: result.direct_path, handle: result.handle }; break }
463
- lastError = new Error(`${hostname} rejected upload (HTTP ${response.status}): ${JSON.stringify(result)}`)
464
- } catch (err) { lastError = err; if (attempt < 2) await new Promise(r => setTimeout(r, 500 * attempt)) }
465
- }
466
- if (urls) break
467
- }
468
- if (!urls) throw new Boom(`Media upload failed on all hosts. Last error: ${lastError?.message ?? 'unknown'}`, { statusCode: 500, data: { lastError: lastError?.message } })
469
- return urls
470
- }
471
-
472
- // ─── MEDIA RETRY ──────────────────────────────────────────────────────────────
473
-
474
- const getMediaRetryKey = mediaKey => hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' })
475
-
476
- export const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
477
- const iv = Crypto.randomBytes(12)
478
- const ciphertext = aesEncryptGCM(proto.ServerErrorReceipt.encode({ stanzaId: key.id }).finish(), await getMediaRetryKey(mediaKey), iv, Buffer.from(key.id))
479
- return { tag: 'receipt', attrs: { id: key.id, to: jidNormalizedUser(meId), type: 'server-error' }, content: [{ tag: 'encrypt', attrs: {}, content: [{ tag: 'enc_p', attrs: {}, content: ciphertext }, { tag: 'enc_iv', attrs: {}, content: iv }] }, { tag: 'rmr', attrs: { jid: key.remoteJid, from_me: (!!key.fromMe).toString(), participant: key.participant } }] }
480
- }
481
-
482
- export const decodeMediaRetryNode = node => {
483
- const rmrNode = getBinaryNodeChild(node, 'rmr')
484
- const event = { key: { id: node.attrs.id, remoteJid: rmrNode.attrs.jid, fromMe: rmrNode.attrs.from_me === 'true', participant: rmrNode.attrs.participant } }
485
- const errorNode = getBinaryNodeChild(node, 'error')
486
- if (errorNode) { event.error = new Boom(`Failed to re-upload media (${+errorNode.attrs.code})`, { data: errorNode.attrs, statusCode: getStatusCodeForMediaRetry(+errorNode.attrs.code) }); return event }
487
- const encNode = getBinaryNodeChild(node, 'encrypt')
488
- const ciphertext = getBinaryNodeChildBuffer(encNode, 'enc_p')
489
- const iv = getBinaryNodeChildBuffer(encNode, 'enc_iv')
490
- event[ciphertext && iv ? 'media' : 'error'] = ciphertext && iv ? { ciphertext, iv } : new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 })
491
- return event
492
- }
493
-
494
- export const decryptMediaRetryData = async ({ ciphertext, iv }, mediaKey, msgId) => proto.MediaRetryNotification.decode(aesDecryptGCM(ciphertext, await getMediaRetryKey(mediaKey), iv, Buffer.from(msgId)))
495
-
496
- export const getStatusCodeForMediaRetry = code => MEDIA_RETRY_STATUS_MAP[code]
497
- const MEDIA_RETRY_STATUS_MAP = {
498
- [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
499
- [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
500
- [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
501
- [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
1
+ import { Boom } from '@hapi/boom'
2
+ import { spawn } from 'child_process'
3
+ import * as Crypto from 'crypto'
4
+ import { once } from 'events'
5
+ import { createWriteStream, createReadStream, mkdirSync, promises as fs } from 'fs'
6
+ import { join } from 'path'
7
+ import { Transform } from 'stream'
8
+ import urlRegexSafe from 'url-regex-safe'
9
+ import { tmpdir as osTmpdir } from 'os'
10
+ import { fileTypeFromBuffer } from 'file-type'
11
+ import intoStream from 'into-stream'
12
+ import { getStreamAsBuffer } from 'get-stream'
13
+ import got from 'got'
14
+ import { temporaryFile, temporaryDirectory } from 'tempy'
15
+ import { proto } from '../../WAProto/index.js'
16
+ import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP } from '../Defaults/index.js'
17
+ import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary/index.js'
18
+ import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto.js'
19
+ import { generateMessageIDV2 } from './generics.js'
20
+
21
+ // ─── TMP ──────────────────────────────────────────────────────────────────────
22
+
23
+ const BAILEYS_TMP_DIR = (() => {
24
+ for (const dir of [join(process.cwd(), '.b-tmp'), join(osTmpdir(), '.b-tmp')]) {
25
+ try {
26
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
27
+ process.env.TMPDIR = dir
28
+ process.env.VIPS_TMPDIR = dir
29
+ process.env.VIPS_DISC_THRESHOLD = '999999999999'
30
+ return dir
31
+ } catch { }
32
+ }
33
+ throw new Error('No writable tmp directory found')
34
+ })()
35
+
36
+ export const tmpdir = () => BAILEYS_TMP_DIR
37
+ const _tmpFile = (ext = '') => temporaryFile({ rootDirectory: BAILEYS_TMP_DIR, ...(ext && { extension: ext.replace('.', '') }) })
38
+ const _tmpDir = (prefix = '') => temporaryDirectory({ rootDirectory: BAILEYS_TMP_DIR, ...(prefix && { prefix }) })
39
+ const _cleanupFiles = async (...paths) => Promise.all(paths.map(p => p ? fs.unlink(p).catch(() => { }) : Promise.resolve()))
40
+
41
+ // ─── FFMPEG ───────────────────────────────────────────────────────────────────
42
+
43
+ let _ffmpegPath = null
44
+ const getFfmpegPath = async () => {
45
+ if (_ffmpegPath) return _ffmpegPath
46
+ try { const { default: p } = await import('ffmpeg-static'); if (p) return (_ffmpegPath = p) } catch { }
47
+ return (_ffmpegPath = 'ffmpeg')
48
+ }
49
+
50
+ const _spawnFfmpeg = (ffmpegPath, args) => new Promise((resolve, reject) => {
51
+ const ff = spawn(ffmpegPath, args, { stdio: ['ignore', 'ignore', 'pipe'] })
52
+ let stderr = ''
53
+ ff.stderr.on('data', d => { stderr += d })
54
+ ff.on('close', code => code === 0 ? resolve() : reject(new Error(`FFmpeg exited ${code}: ${stderr.slice(-500)}`)))
55
+ ff.on('error', reject)
56
+ })
57
+
58
+ const _tmpConvert = async (buffer, inSuffix, outSuffix, ffmpegArgs) => {
59
+ const inputPath = _tmpFile(inSuffix)
60
+ const outputPath = _tmpFile(outSuffix)
61
+ await fs.writeFile(inputPath, buffer)
62
+ try { await _spawnFfmpeg(await getFfmpegPath(), ['-y', '-i', inputPath, ...ffmpegArgs, outputPath]); return await fs.readFile(outputPath) }
63
+ finally { await _cleanupFiles(inputPath, outputPath) }
64
+ }
65
+
66
+ const _animatedWebpToMp4 = async (buffer, ffmpegPath) => {
67
+ const { default: sharp } = await import('sharp')
68
+ const meta = await sharp(buffer, { animated: true }).metadata()
69
+ const pages = meta.pages ?? 1, pageH = meta.pageHeight ?? Math.round(meta.height / pages)
70
+ const delays = meta.delay?.length === pages ? meta.delay : Array(pages).fill(100)
71
+ const frameDir = _tmpDir('webp-frames'), concatFile = _tmpFile('txt'), outputPath = _tmpFile('mp4')
72
+ await fs.mkdir(frameDir, { recursive: true })
73
+ try {
74
+ const { data, info } = await sharp(buffer, { animated: true }).raw().toBuffer({ resolveWithObject: true })
75
+ const frameSize = info.width * pageH * info.channels
76
+ const framePaths = []
77
+ for (let i = 0; i < pages; i++) {
78
+ const fp = join(frameDir, `f${i}.png`)
79
+ await sharp(data.subarray(i * frameSize, (i + 1) * frameSize), { raw: { width: info.width, height: pageH, channels: info.channels } }).png().toFile(fp)
80
+ framePaths.push(fp)
81
+ }
82
+ const lines = framePaths.flatMap((p, i) => [`file '${p}'`, `duration ${(delays[i] / 1000).toFixed(6)}`])
83
+ lines.push(`file '${framePaths[framePaths.length - 1]}'`)
84
+ await fs.writeFile(concatFile, lines.join('\n'))
85
+ await _spawnFfmpeg(ffmpegPath, ['-y', '-f', 'concat', '-safe', '0', '-i', concatFile, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '18', '-pix_fmt', 'yuv420p', '-vf', 'scale=trunc(iw/2)*2:trunc(ih/2)*2', '-movflags', '+faststart', '-map_metadata', '-1', outputPath])
86
+ return await fs.readFile(outputPath)
87
+ } finally {
88
+ const files = await fs.readdir(frameDir).catch(() => [])
89
+ await Promise.all(files.map(f => fs.unlink(join(frameDir, f)).catch(() => { })))
90
+ await fs.rmdir(frameDir).catch(() => { })
91
+ await _cleanupFiles(concatFile, outputPath)
92
+ }
93
+ }
94
+
95
+ const convertToOpusBuffer = async (buffer, logger) => {
96
+ const detected = await fileTypeFromBuffer(buffer)
97
+ if (detected?.ext === 'opus') return buffer
98
+ return _tmpConvert(buffer, detected?.ext ? `.${detected.ext}` : '', '.ogg', ['-vn', '-c:a', 'libopus', '-b:a', '128k', '-ar', '48000', '-ac', '1', '-vbr', 'on', '-compression_level', '10', '-frame_duration', '20', '-application', 'audio', '-map_metadata', '-1'])
99
+ }
100
+
101
+ const convertToMp4Buffer = async (buffer, logger) => {
102
+ try {
103
+ const { default: sharp } = await import('sharp')
104
+ const meta = await sharp(buffer, { animated: true }).metadata()
105
+ if (meta.format === 'webp' && (meta.pages ?? 1) > 1) return await _animatedWebpToMp4(buffer, await getFfmpegPath())
106
+ } catch { }
107
+ const detected = await fileTypeFromBuffer(buffer)
108
+ return _tmpConvert(buffer, detected?.ext ? `.${detected.ext}` : '', '.mp4', ['-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-pix_fmt', 'yuv420p', '-vf', 'scale=trunc(iw/2)*2:trunc(ih/2)*2', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', '-map_metadata', '-1'])
109
+ }
110
+
111
+ // ─── IMAGE ────────────────────────────────────────────────────────────────────
112
+
113
+ export const getImageProcessingLibrary = async () => {
114
+ const [jimp, sharp] = await Promise.all([import('jimp').catch(() => null), import('sharp').catch(() => null)])
115
+ if (sharp) return { sharp }
116
+ if (jimp) return { jimp }
117
+ throw new Boom('No image processing library available')
118
+ }
119
+
120
+ export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
121
+ if (!Buffer.isBuffer(bufferOrFilePath)) bufferOrFilePath = await normalizeToBuffer(bufferOrFilePath)
122
+ const lib = await getImageProcessingLibrary()
123
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
124
+ const img = lib.sharp.default(bufferOrFilePath)
125
+ const { width: w, height: h } = await img.metadata()
126
+ return { buffer: await img.resize(width).jpeg({ quality: 95 }).toBuffer(), original: { width: w, height: h } }
127
+ }
128
+ if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
129
+ const jimp = await lib.jimp.Jimp.read(bufferOrFilePath)
130
+ return { buffer: await jimp.resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 95 }), original: { width: jimp.width, height: jimp.height } }
131
+ }
132
+ throw new Boom('No image processing library available')
133
+ }
134
+
135
+ export const generateProfilePicture = async mediaUpload => {
136
+ const src = await normalizeToBuffer(mediaUpload)
137
+ const lib = await getImageProcessingLibrary()
138
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') return { img: await lib.sharp.default(src).resize(720, 720, { fit: 'inside' }).jpeg({ quality: 80 }).toBuffer() }
139
+ if ('jimp' in lib && typeof lib.jimp?.read === 'function') {
140
+ const { read, MIME_JPEG } = lib.jimp
141
+ const image = await read(src)
142
+ return { img: await image.crop(0, 0, image.getWidth(), image.getHeight()).scaleToFit(720, 720).getBufferAsync(MIME_JPEG) }
143
+ }
144
+ throw new Boom('No image processing library available')
145
+ }
146
+
147
+ export const generateThumbnail = async (file, mediaType, options) => {
148
+ if (mediaType === 'image') {
149
+ const { buffer, original } = await extractImageThumb(file)
150
+ return { thumbnail: buffer.toString('base64'), originalImageDimensions: (original.width && original.height) ? original : undefined }
151
+ }
152
+ if (mediaType === 'video') {
153
+ const imgFilename = join(tmpdir(), generateMessageIDV2() + '.jpg')
154
+ try {
155
+ const ff = await getFfmpegPath()
156
+ await new Promise((resolve, reject) => {
157
+ const proc = spawn(ff, ['-ss', '00:00:00', '-i', file, '-y', '-vf', 'scale=32:-1', '-vframes', '1', '-f', 'image2', imgFilename])
158
+ proc.on('close', code => code === 0 ? resolve() : reject(new Error(`FFmpeg thumb exit ${code}`)))
159
+ proc.on('error', reject)
160
+ })
161
+ const thumbnail = (await fs.readFile(imgFilename)).toString('base64')
162
+ await fs.unlink(imgFilename).catch(() => { })
163
+ return { thumbnail, originalImageDimensions: undefined }
164
+ } catch (err) { options.logger?.debug('could not generate video thumb: ' + err) }
165
+ }
166
+ return { thumbnail: undefined, originalImageDimensions: undefined }
167
+ }
168
+
169
+ // ─── STREAM ───────────────────────────────────────────────────────────────────
170
+
171
+ export const toReadable = input => intoStream(input)
172
+ export const getHttpStream = (url, options = {}) => got.stream(url.toString(), { headers: { ...(options.headers ?? {}), Origin: DEFAULT_ORIGIN } })
173
+ export const isHttpUrl = (() => {
174
+ const r = urlRegexSafe({ exact: true, auth: true })
175
+ return str => typeof str === 'string' && r.test(str)
176
+ })()
177
+
178
+ export const getStream = async (item, opts) => {
179
+ if (!item) throw new Boom('Item is required for getStream', { statusCode: 400 })
180
+ if (Buffer.isBuffer(item)) return { stream: intoStream(item), type: 'buffer' }
181
+ if (item?.type === 'Buffer' && Array.isArray(item?.data)) return { stream: intoStream(Buffer.from(item.data)), type: 'buffer' }
182
+ if (ArrayBuffer.isView(item)) return { stream: intoStream(Buffer.from(item.buffer, item.byteOffset, item.byteLength)), type: 'buffer' }
183
+ if (item instanceof ArrayBuffer) return { stream: intoStream(Buffer.from(item)), type: 'buffer' }
184
+ if (Array.isArray(item)) return { stream: intoStream(Buffer.from(item)), type: 'buffer' }
185
+ if (typeof item?.pipe === 'function' || typeof item?.[Symbol.asyncIterator] === 'function') return { stream: intoStream(await getStreamAsBuffer(item)), type: 'buffer' }
186
+ if (item?.url && Buffer.isBuffer(item.url)) return { stream: intoStream(item.url), type: 'buffer' }
187
+ if (item?.url && typeof item.url === 'string' && item.url.startsWith('data:')) return { stream: intoStream(Buffer.from(item.url.split(',')[1], 'base64')), type: 'buffer' }
188
+ const u = item?.url ? item.url.toString() : typeof item === 'string' ? item : null
189
+ if (u) {
190
+ if (u.startsWith('data:')) return { stream: intoStream(Buffer.from(u.split(',')[1], 'base64')), type: 'buffer' }
191
+ if (isHttpUrl(u)) return { stream: intoStream(await getStreamAsBuffer(got.stream(u, { headers: { ...(opts?.headers ?? {}), Origin: DEFAULT_ORIGIN } }))), type: 'remote' }
192
+ if (/^(?:[A-Za-z0-9+/]{4})+(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(u)) return { stream: intoStream(Buffer.from(u, 'base64')), type: 'buffer' }
193
+ return { stream: createReadStream(u), type: 'file' }
194
+ }
195
+ try {
196
+ return { stream: intoStream(item), type: 'buffer' }
197
+ } catch {
198
+ throw new Boom(`Invalid input type for getStream: ${typeof item}`, { statusCode: 400 })
199
+ }
200
+ }
201
+
202
+ export const toBuffer = async stream => {
203
+ if (Buffer.isBuffer(stream)) return stream
204
+ const { stream: resolved } = await getStream(stream)
205
+ return getStreamAsBuffer(resolved)
206
+ }
207
+
208
+ export const normalizeToBuffer = async input => {
209
+ if (!input) return undefined
210
+ return toBuffer(input)
211
+ }
212
+
213
+ export const resolveToMediaUrl = async input => {
214
+ if (isHttpUrl(input)) return input
215
+ if (isHttpUrl(input?.url)) return input.url
216
+ const buf = await normalizeToBuffer(input)
217
+ if (!buf) throw new TypeError('Could not resolve input to buffer')
218
+ const { Catbox, Pomf, Quax, Cloudku, Litterbox } = await import('@zanixongroup/uploader')
219
+ const providers = [Catbox, Pomf, Quax, Cloudku, Litterbox].sort(() => Math.random() - 0.5)
220
+ let lastError
221
+ for (const provider of providers) {
222
+ try { const url = await provider(buf); if (url) return url } catch (err) { lastError = err }
223
+ }
224
+ throw new TypeError(`All providers failed: ${lastError?.message}`)
225
+ }
226
+
227
+ // ─── HKDF ─────────────────────────────────────────────────────────────────────
228
+
229
+ export const hkdfInfoKey = type => `WhatsApp ${MEDIA_HKDF_KEY_MAPPING[type]} Keys`
230
+
231
+ export const getMediaKeys = async (buffer, mediaType) => {
232
+ if (!buffer) throw new Boom('Cannot derive from empty media key')
233
+ buffer = await normalizeToBuffer(buffer)
234
+ if (!buffer?.length) throw new Boom('Cannot derive from empty media key')
235
+ const k = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) })
236
+ return { iv: k.subarray(0, 16), cipherKey: k.subarray(16, 48), macKey: k.subarray(48, 80) }
237
+ }
238
+
239
+ // ─── AUDIO ────────────────────────────────────────────────────────────────────
240
+
241
+ export const mediaMessageSHA256B64 = message => { const media = Object.values(message)[0]; return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64') }
242
+
243
+ export const getAudioDuration = async (buffer, logger) => {
244
+ try {
245
+ const mm = await import('music-metadata')
246
+ if (Buffer.isBuffer(buffer)) return (await mm.parseBuffer(buffer, undefined, { duration: true })).format.duration
247
+ if (typeof buffer === 'string') return (await mm.parseFile(buffer, { duration: true })).format.duration
248
+ return (await mm.parseStream(buffer, undefined, { duration: true })).format.duration
249
+ } catch (e) { logger?.debug({ trace: e?.stack || e }, 'failed to determine audio duration'); return undefined }
250
+ }
251
+
252
+ export const getAudioWaveform = async (buffer, logger) => {
253
+ const fallback = new Uint8Array([0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99])
254
+ try {
255
+ const rawPCM = await new Promise(async (resolve, reject) => {
256
+ const chunks = [], ff = spawn(await getFfmpegPath(), ['-i', 'pipe:0', '-f', 's16le', '-ac', '1', '-ar', '16000', 'pipe:1'], { stdio: ['pipe', 'pipe', 'pipe'] })
257
+ let stderr = ''
258
+ ff.stdout.on('data', d => chunks.push(d))
259
+ ff.stderr.on('data', d => { stderr += d })
260
+ ff.on('close', code => code === 0 ? resolve(Buffer.concat(chunks)) : reject(new Error(`FFmpeg waveform exit ${code}: ${stderr.slice(-300)}`)))
261
+ ff.on('error', reject)
262
+ ff.stdin.end(Buffer.isBuffer(buffer) ? buffer : typeof buffer === 'string' ? await fs.readFile(buffer) : await toBuffer(buffer))
263
+ })
264
+ if (!rawPCM.length) throw new Error('empty PCM output')
265
+ const samples = rawPCM.length >> 1
266
+ const blockSize = Math.max(1, Math.floor(samples / 64))
267
+ const blockSums = new Float64Array(64)
268
+ for (let i = 0; i < samples; i++) blockSums[Math.min(63, Math.floor(i / blockSize))] += Math.abs(rawPCM.readInt16LE(i * 2))
269
+ const avg = Array.from(blockSums, sum => sum / blockSize / 32768)
270
+ const max = Math.max(...avg, 0.0001)
271
+ return new Uint8Array(avg.map(v => Math.max(0, Math.min(100, Math.round((v / max) * 100)))))
272
+ } catch (e) { logger?.debug({ trace: e?.stack || e }, 'failed to generate waveform, using fallback'); return fallback }
273
+ }
274
+
275
+ // ─── PREPARE / ENCRYPT ────────────────────────────────────────────────────────
276
+
277
+ export const prepareStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts, convertVideo } = {}) => {
278
+ const { stream, type } = await getStream(media, opts)
279
+ let buffer = await toBuffer(stream)
280
+ if (mediaType === 'video' && convertVideo) {
281
+ try { buffer = await convertToMp4Buffer(buffer, logger) } catch (e) { logger?.error('failed to convert video:', e) }
282
+ }
283
+ let bodyPath, didSaveToTmpPath = false
284
+ try {
285
+ if (type === 'file') bodyPath = typeof media === 'string' ? media : media.url
286
+ else if (saveOriginalFileIfRequired) { bodyPath = join(tmpdir(), mediaType + generateMessageIDV2()); await fs.writeFile(bodyPath, buffer); didSaveToTmpPath = true }
287
+ return {
288
+ mediaKey: undefined, encWriteStream: buffer, fileLength: buffer.length,
289
+ fileSha256: Crypto.createHash('sha256').update(buffer).digest(),
290
+ fileEncSha256: undefined, bodyPath, didSaveToTmpPath,
291
+ cleanup: async () => { if (didSaveToTmpPath && bodyPath) await fs.unlink(bodyPath).catch(() => { }) },
292
+ }
293
+ } catch (error) {
294
+ if (didSaveToTmpPath && bodyPath) await fs.unlink(bodyPath).catch(() => { })
295
+ throw error
296
+ }
297
+ }
298
+
299
+ export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts, mediaKey: providedMediaKey, isPtt, forceOpus, convertVideo } = {}) => {
300
+ const { stream, type } = await getStream(media, opts)
301
+ let finalStream = stream, opusConverted = false
302
+ if (mediaType === 'audio' && (isPtt === true || forceOpus === true)) {
303
+ try { finalStream = toReadable(await convertToOpusBuffer(await toBuffer(stream), logger)); opusConverted = true }
304
+ catch { finalStream = (await getStream(media, opts)).stream }
305
+ }
306
+ if (mediaType === 'video' && convertVideo === true) finalStream = toReadable(await convertToMp4Buffer(await toBuffer(finalStream), logger))
307
+
308
+ const mediaKey = providedMediaKey || Crypto.randomBytes(32)
309
+ const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType)
310
+ const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv)
311
+ const hmac = Crypto.createHmac('sha256', macKey).update(iv)
312
+ const sha256Plain = Crypto.createHash('sha256'), sha256Enc = Crypto.createHash('sha256')
313
+ const encChunks = [], plainChunks = saveOriginalFileIfRequired ? [] : null
314
+ let fileLength = 0, encFilePath = null, originalFilePath = null
315
+
316
+ try {
317
+ for await (const data of finalStream) {
318
+ fileLength += data.length
319
+ if (type === 'remote' && opts?.maxContentLength && fileLength > opts.maxContentLength) throw new Boom('content length exceeded', { data: { media, type } })
320
+ plainChunks?.push(data)
321
+ sha256Plain.update(data)
322
+ const encrypted = aes.update(data)
323
+ sha256Enc.update(encrypted); hmac.update(encrypted); encChunks.push(encrypted)
324
+ }
325
+ const finalData = aes.final()
326
+ sha256Enc.update(finalData); hmac.update(finalData); encChunks.push(finalData)
327
+ const mac = hmac.digest().subarray(0, 10)
328
+ sha256Enc.update(mac); encChunks.push(mac)
329
+ finalStream.destroy()
330
+
331
+ const encBuffer = Buffer.concat(encChunks)
332
+ const fileEncSha256 = sha256Enc.digest()
333
+ const fileSha256 = sha256Plain.digest()
334
+
335
+ if (plainChunks) {
336
+ try { originalFilePath = join(tmpdir(), mediaType + generateMessageIDV2() + '-original'); await fs.writeFile(originalFilePath, Buffer.concat(plainChunks)) }
337
+ catch { originalFilePath = null }
338
+ }
339
+ let useMemory = false
340
+ try { encFilePath = join(tmpdir(), mediaType + generateMessageIDV2() + '-enc'); await fs.writeFile(encFilePath, encBuffer) }
341
+ catch { encFilePath = null; useMemory = true }
342
+
343
+ return { mediaKey, bodyPath: originalFilePath, encFilePath, encBuffer: useMemory ? encBuffer : null, mac, fileEncSha256, fileSha256, fileLength, opusConverted, cleanup: async () => _cleanupFiles(encFilePath, originalFilePath) }
344
+ } catch (error) {
345
+ aes.destroy(); hmac.destroy(); sha256Plain.destroy(); sha256Enc.destroy(); finalStream.destroy()
346
+ await _cleanupFiles(encFilePath, originalFilePath)
347
+ throw error
348
+ }
349
+ }
350
+
351
+ // ─── RAW UPLOAD ───────────────────────────────────────────────────────────────
352
+
353
+ export const getRawMediaUploadData = async (media, mediaType) => {
354
+ const { stream } = await getStream(media)
355
+ const hasher = Crypto.createHash('sha256')
356
+ const filePath = join(tmpdir(), mediaType + generateMessageIDV2())
357
+ const fileWriteStream = createWriteStream(filePath)
358
+ let fileLength = 0
359
+ try {
360
+ for await (const data of stream) { fileLength += data.length; hasher.update(data); if (!fileWriteStream.write(data)) await once(fileWriteStream, 'drain') }
361
+ fileWriteStream.end()
362
+ await once(fileWriteStream, 'finish')
363
+ stream.destroy()
364
+ return { filePath, fileSha256: hasher.digest(), fileLength }
365
+ } catch (error) {
366
+ fileWriteStream.destroy(); stream.destroy()
367
+ await fs.unlink(filePath).catch(() => { })
368
+ throw error
369
+ }
370
+ }
371
+
372
+ // ─── DOWNLOAD ─────────────────────────────────────────────────────────────────
373
+
374
+ const DEF_HOST = 'mmg.whatsapp.net'
375
+ const AES_CHUNK_SIZE = 16
376
+ const toSmallestChunkSize = num => Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE
377
+
378
+ export const getUrlFromDirectPath = directPath => directPath ? (directPath.startsWith('http') ? directPath : `https://${DEF_HOST}${directPath.startsWith('/') ? '' : '/'}${directPath}`) : undefined
379
+
380
+ export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
381
+ const downloadUrl = url?.startsWith('https://mmg.whatsapp.net/') ? url : getUrlFromDirectPath(directPath)
382
+ if (!downloadUrl) throw new Boom('No valid media URL or directPath present', { statusCode: 400 })
383
+ return downloadEncryptedContent(downloadUrl, await getMediaKeys(mediaKey, type), opts)
384
+ }
385
+
386
+ export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
387
+ let bytesFetched = 0, startChunk = 0, firstBlockIsIV = false
388
+ if (startByte) {
389
+ const chunk = toSmallestChunkSize(startByte || 0)
390
+ if (chunk) { startChunk = chunk - AES_CHUNK_SIZE; bytesFetched = chunk; firstBlockIsIV = true }
391
+ }
392
+ const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined
393
+ const headers = { ...(options?.headers ? (Array.isArray(options.headers) ? Object.fromEntries(options.headers) : options.headers) : {}), Origin: DEFAULT_ORIGIN }
394
+ if (startChunk || endChunk) headers.Range = `bytes=${startChunk}-${endChunk || ''}`
395
+ const fetched = getHttpStream(downloadUrl, { ...(options || {}), headers })
396
+ let remainingBytes = Buffer.from([]), aes
397
+ const pushBytes = (bytes, push) => {
398
+ if (startByte || endByte) {
399
+ const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0)
400
+ const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0)
401
+ push(bytes.subarray(start, end)); bytesFetched += bytes.length
402
+ } else push(bytes)
403
+ }
404
+ return fetched.pipe(new Transform({
405
+ transform(chunk, _, callback) {
406
+ let data = Buffer.concat([remainingBytes, chunk])
407
+ const decryptLength = toSmallestChunkSize(data.length)
408
+ remainingBytes = data.subarray(decryptLength); data = data.subarray(0, decryptLength)
409
+ if (!aes) {
410
+ let ivValue = iv
411
+ if (firstBlockIsIV) { ivValue = data.subarray(0, AES_CHUNK_SIZE); data = data.subarray(AES_CHUNK_SIZE) }
412
+ aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue)
413
+ if (endByte) aes.setAutoPadding(false)
414
+ }
415
+ try { pushBytes(aes.update(data), b => this.push(b)); callback() } catch (error) { callback(error) }
416
+ },
417
+ final(callback) { try { pushBytes(aes.final(), b => this.push(b)); callback() } catch (error) { callback(error) } }
418
+ }), { end: true })
419
+ }
420
+
421
+ // ─── UPLOAD ───────────────────────────────────────────────────────────────────
422
+
423
+ export const encodeBase64EncodedStringForUpload = b64 => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''))
424
+
425
+ export const extensionForMediaMessage = message => {
426
+ const type = Object.keys(message)[0]
427
+ if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') return '.jpeg'
428
+ return message[type].mimetype.split(';')[0]?.split('/')[1]
429
+ }
430
+
431
+ const httpsPost = async (url, body, headers, signal) => {
432
+ const response = await got.post(url, { body: Buffer.isBuffer(body) ? body : await getStreamAsBuffer(body), headers: { ...headers, Origin: DEFAULT_ORIGIN }, signal, throwHttpErrors: false })
433
+ let json = null
434
+ try { json = JSON.parse(response.body) } catch { }
435
+ return { status: response.statusCode, ok: response.statusCode >= 200 && response.statusCode < 300, json: async () => json }
436
+ }
437
+
438
+ export const getWAUploadToServer = ({ customUploadHosts, logger, options }, refreshMediaConn) => async (stream, { mediaType, fileEncSha256B64, newsletter, timeoutMs }) => {
439
+ let reqBody
440
+ try { reqBody = await toBuffer(stream) } catch (err) { logger?.error({ err: err.message }, 'failed to prepare upload body'); throw err }
441
+ fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64)
442
+ let media = MEDIA_PATH_MAP[mediaType]
443
+ if (newsletter) media = media?.replace('/mms/', '/newsletter/newsletter-')
444
+ if (!media) throw new Boom(`No media path found for type: ${mediaType}`, { statusCode: 400 })
445
+ let uploadInfo = await refreshMediaConn(false)
446
+ const hosts = [...(customUploadHosts ?? []), ...(uploadInfo.hosts ?? [])]
447
+ if (!hosts.length) throw new Boom('No upload hosts available', { statusCode: 503 })
448
+ let urls, lastError
449
+ for (const { hostname, maxContentLengthBytes } of hosts) {
450
+ for (let attempt = 1; attempt <= 2; attempt++) {
451
+ try {
452
+ if (attempt > 1) { uploadInfo = await refreshMediaConn(true); reqBody = await toBuffer(stream) }
453
+ if (maxContentLengthBytes && Buffer.isBuffer(reqBody) && reqBody.length > maxContentLengthBytes) break
454
+ const auth = encodeURIComponent(uploadInfo.auth)
455
+ const url = `https://${hostname}${media}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`
456
+ const controller = new AbortController()
457
+ const timer = timeoutMs ? setTimeout(() => controller.abort(), timeoutMs) : null
458
+ let response
459
+ try { response = await httpsPost(url, reqBody, { ...(Array.isArray(options?.headers) ? Object.fromEntries(options.headers) : (options?.headers ?? {})), 'Content-Type': 'application/octet-stream', Origin: DEFAULT_ORIGIN }, controller.signal) }
460
+ finally { if (timer) clearTimeout(timer) }
461
+ const result = await response.json().catch(() => null)
462
+ if (result?.url || result?.directPath) { urls = { mediaUrl: result.url, directPath: result.direct_path, handle: result.handle }; break }
463
+ lastError = new Error(`${hostname} rejected upload (HTTP ${response.status}): ${JSON.stringify(result)}`)
464
+ } catch (err) { lastError = err; if (attempt < 2) await new Promise(r => setTimeout(r, 500 * attempt)) }
465
+ }
466
+ if (urls) break
467
+ }
468
+ if (!urls) throw new Boom(`Media upload failed on all hosts. Last error: ${lastError?.message ?? 'unknown'}`, { statusCode: 500, data: { lastError: lastError?.message } })
469
+ return urls
470
+ }
471
+
472
+ // ─── MEDIA RETRY ──────────────────────────────────────────────────────────────
473
+
474
+ const getMediaRetryKey = mediaKey => hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' })
475
+
476
+ export const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
477
+ const iv = Crypto.randomBytes(12)
478
+ const ciphertext = aesEncryptGCM(proto.ServerErrorReceipt.encode({ stanzaId: key.id }).finish(), await getMediaRetryKey(mediaKey), iv, Buffer.from(key.id))
479
+ return { tag: 'receipt', attrs: { id: key.id, to: jidNormalizedUser(meId), type: 'server-error' }, content: [{ tag: 'encrypt', attrs: {}, content: [{ tag: 'enc_p', attrs: {}, content: ciphertext }, { tag: 'enc_iv', attrs: {}, content: iv }] }, { tag: 'rmr', attrs: { jid: key.remoteJid, from_me: (!!key.fromMe).toString(), participant: key.participant } }] }
480
+ }
481
+
482
+ export const decodeMediaRetryNode = node => {
483
+ const rmrNode = getBinaryNodeChild(node, 'rmr')
484
+ const event = { key: { id: node.attrs.id, remoteJid: rmrNode.attrs.jid, fromMe: rmrNode.attrs.from_me === 'true', participant: rmrNode.attrs.participant } }
485
+ const errorNode = getBinaryNodeChild(node, 'error')
486
+ if (errorNode) { event.error = new Boom(`Failed to re-upload media (${+errorNode.attrs.code})`, { data: errorNode.attrs, statusCode: getStatusCodeForMediaRetry(+errorNode.attrs.code) }); return event }
487
+ const encNode = getBinaryNodeChild(node, 'encrypt')
488
+ const ciphertext = getBinaryNodeChildBuffer(encNode, 'enc_p')
489
+ const iv = getBinaryNodeChildBuffer(encNode, 'enc_iv')
490
+ event[ciphertext && iv ? 'media' : 'error'] = ciphertext && iv ? { ciphertext, iv } : new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 })
491
+ return event
492
+ }
493
+
494
+ export const decryptMediaRetryData = async ({ ciphertext, iv }, mediaKey, msgId) => proto.MediaRetryNotification.decode(aesDecryptGCM(ciphertext, await getMediaRetryKey(mediaKey), iv, Buffer.from(msgId)))
495
+
496
+ export const getStatusCodeForMediaRetry = code => MEDIA_RETRY_STATUS_MAP[code]
497
+ const MEDIA_RETRY_STATUS_MAP = {
498
+ [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
499
+ [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
500
+ [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
501
+ [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
502
502
  }