@codexverified/baileys 2.7.5

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 (139) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +233 -0
  3. package/WAProto/V +1 -0
  4. package/WAProto/WAProto.proto +8051 -0
  5. package/WAProto/index.js +289292 -0
  6. package/engine-requirements.js +13 -0
  7. package/lib/Defaults/index.js +158 -0
  8. package/lib/Signal/Group/ciphertext-message.js +11 -0
  9. package/lib/Signal/Group/group-session-builder.js +29 -0
  10. package/lib/Signal/Group/group_cipher.js +81 -0
  11. package/lib/Signal/Group/index.js +11 -0
  12. package/lib/Signal/Group/keyhelper.js +17 -0
  13. package/lib/Signal/Group/sender-chain-key.js +25 -0
  14. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  15. package/lib/Signal/Group/sender-key-message.js +65 -0
  16. package/lib/Signal/Group/sender-key-name.js +47 -0
  17. package/lib/Signal/Group/sender-key-record.js +40 -0
  18. package/lib/Signal/Group/sender-key-state.js +83 -0
  19. package/lib/Signal/Group/sender-message-key.js +25 -0
  20. package/lib/Signal/libsignal.js +428 -0
  21. package/lib/Signal/lid-mapping.js +280 -0
  22. package/lib/Socket/Client/index.js +2 -0
  23. package/lib/Socket/Client/types.js +10 -0
  24. package/lib/Socket/Client/websocket.js +53 -0
  25. package/lib/Socket/aigroups.js +315 -0
  26. package/lib/Socket/business.js +407 -0
  27. package/lib/Socket/chats.js +1831 -0
  28. package/lib/Socket/communities.js +431 -0
  29. package/lib/Socket/graphql.js +899 -0
  30. package/lib/Socket/groups.js +549 -0
  31. package/lib/Socket/index.js +79 -0
  32. package/lib/Socket/interactive-handler.js +600 -0
  33. package/lib/Socket/interop.js +563 -0
  34. package/lib/Socket/managed-account.js +208 -0
  35. package/lib/Socket/messages-recv.js +2144 -0
  36. package/lib/Socket/messages-send.js +2030 -0
  37. package/lib/Socket/mex.js +41 -0
  38. package/lib/Socket/newsletter.js +226 -0
  39. package/lib/Socket/privacy.js +446 -0
  40. package/lib/Socket/registration.js +428 -0
  41. package/lib/Socket/socket.js +1017 -0
  42. package/lib/Socket/username.js +229 -0
  43. package/lib/Store/index.js +4 -0
  44. package/lib/Store/make-cache-manager-store.js +89 -0
  45. package/lib/Store/make-in-memory-store.js +420 -0
  46. package/lib/Store/make-ordered-dictionary.js +78 -0
  47. package/lib/Store/object-repository.js +23 -0
  48. package/lib/Types/Auth.js +1 -0
  49. package/lib/Types/Bussines.js +1 -0
  50. package/lib/Types/Call.js +1 -0
  51. package/lib/Types/Chat.js +7 -0
  52. package/lib/Types/Contact.js +1 -0
  53. package/lib/Types/Events.js +1 -0
  54. package/lib/Types/GroupMetadata.js +1 -0
  55. package/lib/Types/Label.js +24 -0
  56. package/lib/Types/LabelAssociation.js +6 -0
  57. package/lib/Types/Message.js +17 -0
  58. package/lib/Types/Mex.js +39 -0
  59. package/lib/Types/Product.js +1 -0
  60. package/lib/Types/RichType.js +22 -0
  61. package/lib/Types/Signal.js +1 -0
  62. package/lib/Types/Socket.js +2 -0
  63. package/lib/Types/State.js +48 -0
  64. package/lib/Types/USync.js +1 -0
  65. package/lib/Types/index.js +25 -0
  66. package/lib/Utils/auth-utils.js +301 -0
  67. package/lib/Utils/bot-planning-replay.js +169 -0
  68. package/lib/Utils/browser-utils.js +28 -0
  69. package/lib/Utils/business.js +230 -0
  70. package/lib/Utils/chat-utils.js +885 -0
  71. package/lib/Utils/companion-reg-client-utils.js +32 -0
  72. package/lib/Utils/consumer-application.js +102 -0
  73. package/lib/Utils/crypto.js +117 -0
  74. package/lib/Utils/decode-wa-message.js +484 -0
  75. package/lib/Utils/event-buffer.js +589 -0
  76. package/lib/Utils/generics.js +388 -0
  77. package/lib/Utils/group-history.js +56 -0
  78. package/lib/Utils/history.js +130 -0
  79. package/lib/Utils/identity-change-handler.js +48 -0
  80. package/lib/Utils/index.js +34 -0
  81. package/lib/Utils/jid-display-normalization.js +209 -0
  82. package/lib/Utils/link-preview.js +84 -0
  83. package/lib/Utils/logger.js +2 -0
  84. package/lib/Utils/lt-hash.js +7 -0
  85. package/lib/Utils/make-mutex.js +32 -0
  86. package/lib/Utils/message-composer.js +467 -0
  87. package/lib/Utils/message-inspect.js +67 -0
  88. package/lib/Utils/message-retry-manager.js +241 -0
  89. package/lib/Utils/messages-media.js +1006 -0
  90. package/lib/Utils/messages.js +1851 -0
  91. package/lib/Utils/meta-ai-msmsg.js +130 -0
  92. package/lib/Utils/meta-compositing.js +194 -0
  93. package/lib/Utils/noise-handler.js +200 -0
  94. package/lib/Utils/offline-node-processor.js +39 -0
  95. package/lib/Utils/pre-key-manager.js +105 -0
  96. package/lib/Utils/process-message.js +527 -0
  97. package/lib/Utils/reporting-utils.js +257 -0
  98. package/lib/Utils/rich-message-utils.js +439 -0
  99. package/lib/Utils/signal.js +200 -0
  100. package/lib/Utils/stanza-ack.js +37 -0
  101. package/lib/Utils/sync-action-utils.js +47 -0
  102. package/lib/Utils/tc-token-utils.js +162 -0
  103. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  104. package/lib/Utils/use-single-file-auth-state.js +96 -0
  105. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  106. package/lib/Utils/validate-connection.js +206 -0
  107. package/lib/Utils/voip-rekey.js +20 -0
  108. package/lib/Utils/welcome-flow.js +217 -0
  109. package/lib/WABinary/constants.js +1463 -0
  110. package/lib/WABinary/decode.js +261 -0
  111. package/lib/WABinary/encode.js +219 -0
  112. package/lib/WABinary/generic-utils.js +227 -0
  113. package/lib/WABinary/index.js +5 -0
  114. package/lib/WABinary/jid-utils.js +95 -0
  115. package/lib/WABinary/types.js +1 -0
  116. package/lib/WAM/BinaryInfo.js +9 -0
  117. package/lib/WAM/constants.js +22852 -0
  118. package/lib/WAM/encode.js +149 -0
  119. package/lib/WAM/index.js +3 -0
  120. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +96 -0
  121. package/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
  122. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  123. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  124. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +70 -0
  125. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  126. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +25 -0
  127. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  128. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +34 -0
  129. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  130. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  131. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  132. package/lib/WAUSync/Protocols/index.js +12 -0
  133. package/lib/WAUSync/USyncQuery.js +201 -0
  134. package/lib/WAUSync/USyncUser.js +54 -0
  135. package/lib/WAUSync/index.js +3 -0
  136. package/lib/antiban.cjs +4726 -0
  137. package/lib/index.d.ts +286 -0
  138. package/lib/index.js +18 -0
  139. package/package.json +121 -0
@@ -0,0 +1,1006 @@
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 { createReadStream, createWriteStream, promises as fs, WriteStream } from 'fs';
6
+ import { tmpdir } from 'os';
7
+ import { join } from 'path';
8
+ import { Readable, Transform } from 'stream';
9
+ import { URL } from 'url';
10
+ import { proto } from '../../WAProto/index.js';
11
+ import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP, NEWSLETTER_MEDIA_PATH_MAP } from '../Defaults/index.js';
12
+ import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary/index.js';
13
+ import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto.js';
14
+ import { generateMessageIDV2 } from './generics.js';
15
+ const getTmpFilesDirectory = () => tmpdir();
16
+ let imageProcessingLibrary;
17
+ export const getImageProcessingLibrary = async () => {
18
+ if (imageProcessingLibrary) {
19
+ return imageProcessingLibrary;
20
+ }
21
+ //@ts-ignore
22
+ const [sharp, image, jimp] = await Promise.all([
23
+ import('sharp').catch(() => { }),
24
+ import('@napi-rs/image').catch(() => { }),
25
+ import('jimp').catch(() => { })
26
+ ]);
27
+ if (sharp) {
28
+ imageProcessingLibrary = { sharp };
29
+ }
30
+ else if (image) {
31
+ imageProcessingLibrary = { image };
32
+ }
33
+ else if (jimp) {
34
+ imageProcessingLibrary = { jimp };
35
+ }
36
+ else {
37
+ throw new Boom('No image processing library available');
38
+ }
39
+ return imageProcessingLibrary;
40
+ };
41
+ export const hkdfInfoKey = (type) => {
42
+ const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type];
43
+ return `WhatsApp ${hkdfInfo} Keys`;
44
+ };
45
+ export const getRawMediaUploadData = async (media, mediaType, logger) => {
46
+ const { stream } = await getStream(media);
47
+ logger?.debug('got stream for raw upload');
48
+ const hasher = Crypto.createHash('sha256');
49
+ const filePath = join(tmpdir(), mediaType + generateMessageIDV2());
50
+ const fileWriteStream = createWriteStream(filePath);
51
+ let fileLength = 0;
52
+ try {
53
+ for await (const data of stream) {
54
+ fileLength += data.length;
55
+ hasher.update(data);
56
+ if (!fileWriteStream.write(data)) {
57
+ await once(fileWriteStream, 'drain');
58
+ }
59
+ }
60
+ fileWriteStream.end();
61
+ await once(fileWriteStream, 'finish');
62
+ stream.destroy();
63
+ const fileSha256 = hasher.digest();
64
+ logger?.debug('hashed data for raw upload');
65
+ return {
66
+ filePath: filePath,
67
+ fileSha256,
68
+ fileLength
69
+ };
70
+ }
71
+ catch (error) {
72
+ fileWriteStream.destroy();
73
+ stream.destroy();
74
+ try {
75
+ await fs.unlink(filePath);
76
+ }
77
+ catch {
78
+ //
79
+ }
80
+ throw error;
81
+ }
82
+ };
83
+ /** generates all the keys required to encrypt/decrypt & sign a media message */
84
+ export async function getMediaKeys(buffer, mediaType) {
85
+ if (!buffer) {
86
+ throw new Boom('Cannot derive from empty media key');
87
+ }
88
+ if (typeof buffer === 'string') {
89
+ buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
90
+ }
91
+ // expand using HKDF to 112 bytes, also pass in the relevant app info
92
+ const expandedMediaKey = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) });
93
+ return {
94
+ iv: expandedMediaKey.slice(0, 16),
95
+ cipherKey: expandedMediaKey.slice(16, 48),
96
+ macKey: expandedMediaKey.slice(48, 80)
97
+ };
98
+ }
99
+ /** Extracts video thumb using FFMPEG */
100
+ export const extractVideoThumb = async (path, time, size) => {
101
+ const ffmpeg = spawn('ffmpeg', [
102
+ '-loglevel', 'error',
103
+ '-ss', String(time),
104
+ '-i', path,
105
+ '-an', '-sn', '-dn',
106
+ '-map_metadata', '-1',
107
+ '-vf', `scale=${size.width}:-1`,
108
+ '-frames:v', '1',
109
+ '-c:v', 'mjpeg',
110
+ '-f', 'image2pipe',
111
+ 'pipe:1'
112
+ ], {
113
+ stdio: ['ignore', 'pipe', 'pipe']
114
+ });
115
+ let buffer = Buffer.alloc(0);
116
+ const stderrChunks = [];
117
+ ffmpeg.stdout.on('data', (chunk) => {
118
+ buffer = Buffer.concat([buffer, chunk]);
119
+ });
120
+ ffmpeg.stderr.on('data', (chunk) => stderrChunks.push(chunk));
121
+ const [code] = await once(ffmpeg, 'close');
122
+ if (code !== 0) {
123
+ throw new Boom(`FFmpeg failed (code ${code}):\n` +
124
+ Buffer.concat(stderrChunks).toString('utf8'));
125
+ }
126
+ return buffer;
127
+ };
128
+ export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
129
+ // TODO: Move entirely to sharp, removing jimp as it supports readable streams
130
+ // This will have positive speed and performance impacts as well as minimizing RAM usage.
131
+ if (bufferOrFilePath instanceof Readable) {
132
+ bufferOrFilePath = await toBuffer(bufferOrFilePath);
133
+ }
134
+ const lib = await getImageProcessingLibrary();
135
+ if ('sharp' in lib && lib.sharp?.default) {
136
+ const img = lib.sharp.default(bufferOrFilePath);
137
+ const dimensions = await img.metadata();
138
+ const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
139
+ return {
140
+ buffer,
141
+ original: {
142
+ width: dimensions.width,
143
+ height: dimensions.height
144
+ }
145
+ };
146
+ }
147
+ else if ('image' in lib && lib.image?.Transformer) {
148
+ if (!Buffer.isBuffer(bufferOrFilePath)) {
149
+ bufferOrFilePath = await fs.readFile(bufferOrFilePath);
150
+ }
151
+ const img = new lib.image.Transformer(bufferOrFilePath);
152
+ const dimensions = await img.metadata();
153
+ const buffer = await img.resize(width, undefined, 0).jpeg(50);
154
+ return {
155
+ buffer,
156
+ original: {
157
+ width: dimensions.width,
158
+ height: dimensions.height
159
+ }
160
+ };
161
+ }
162
+ else if ('jimp' in lib && lib.jimp?.Jimp) {
163
+ const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
164
+ const dimensions = {
165
+ width: jimp.width,
166
+ height: jimp.height
167
+ };
168
+ const buffer = await jimp
169
+ .resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
170
+ .getBuffer('image/jpeg', { quality: 50 });
171
+ return {
172
+ buffer,
173
+ original: dimensions
174
+ };
175
+ }
176
+ else {
177
+ throw new Boom('No image processing library available');
178
+ }
179
+ };
180
+ export const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
181
+ export const generateProfilePicture = async (mediaUpload, dimensions) => {
182
+ let buffer;
183
+ const { width: w = 720, height: h = 720 } = dimensions || {};
184
+ if (Buffer.isBuffer(mediaUpload)) {
185
+ buffer = mediaUpload;
186
+ }
187
+ else {
188
+ // Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
189
+ const { stream } = await getStream(mediaUpload);
190
+ // Convert the resulting stream to a buffer
191
+ buffer = await toBuffer(stream);
192
+ }
193
+ const lib = await getImageProcessingLibrary();
194
+ let img;
195
+ if ('sharp' in lib && lib.sharp?.default) {
196
+ img = lib.sharp
197
+ .default(buffer)
198
+ .resize(w, h)
199
+ .jpeg({
200
+ quality: 80
201
+ })
202
+ .toBuffer();
203
+ }
204
+ else if ('image' in lib && lib.image?.Transformer) {
205
+ img = new lib.image
206
+ .Transformer(buffer)
207
+ .resize(w, h, 0)
208
+ .jpeg(80);
209
+ }
210
+ else if ('jimp' in lib && lib.jimp?.Jimp) {
211
+ const jimp = await lib.jimp.Jimp.read(buffer);
212
+ const min = Math.min(jimp.width, jimp.height);
213
+ const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
214
+ img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 80 });
215
+ }
216
+ else {
217
+ throw new Boom('No image processing library available');
218
+ }
219
+ return {
220
+ img: await img
221
+ };
222
+ };
223
+ // codex@HD-Profile --- Like generateProfilePicture but skips resize/crop.
224
+ // Re-encodes to JPEG so WA always gets valid image bytes.
225
+ // codex@HD-Profile --- HD mode: preserves original aspect ratio, no crop.
226
+ // WhatsApp server accepts max 720px on any side. Images under 720px pass through
227
+ // unchanged. Larger images are scaled down proportionally to fit within 720px.
228
+ export const generateProfilePictureHD = async (mediaUpload) => {
229
+ let buffer;
230
+ if (Buffer.isBuffer(mediaUpload)) {
231
+ buffer = mediaUpload;
232
+ }
233
+ else {
234
+ const { stream } = await getStream(mediaUpload);
235
+ buffer = await toBuffer(stream);
236
+ }
237
+
238
+ const lib = await getImageProcessingLibrary();
239
+ let img;
240
+
241
+ if ('sharp' in lib && lib.sharp?.default) {
242
+ const metadata = await lib.sharp.default(buffer).metadata();
243
+ const origWidth = metadata.width || 720;
244
+ const origHeight = metadata.height || 720;
245
+ const maxDim = Math.max(origWidth, origHeight);
246
+
247
+ // WhatsApp server limit: 720px max dimension
248
+ // If already under 720, send as-is. If larger, scale down proportionally.
249
+ const needsResize = maxDim > 720;
250
+
251
+ let pipeline = lib.sharp.default(buffer);
252
+
253
+ if (needsResize) {
254
+ pipeline = pipeline.resize(720, 720, {
255
+ fit: 'inside',
256
+ withoutEnlargement: true
257
+ });
258
+ }
259
+
260
+ img = pipeline
261
+ .jpeg({ quality: 85, mozjpeg: true })
262
+ .toBuffer();
263
+ }
264
+ else if ('image' in lib && lib.image?.Transformer) {
265
+ // @napi-rs/image cap at 720 via resize
266
+ img = new lib.image
267
+ .Transformer(buffer)
268
+ .resize(720, 720)
269
+ .jpeg(85);
270
+ }
271
+ else if ('jimp' in lib && lib.jimp?.Jimp) {
272
+ const jimp = await lib.jimp.Jimp.read(buffer);
273
+ const origWidth = jimp.width;
274
+ const origHeight = jimp.height;
275
+ const maxDim = Math.max(origWidth, origHeight);
276
+
277
+ let processed = jimp;
278
+ if (maxDim > 720) {
279
+ const scale = 720 / maxDim;
280
+ processed = jimp.resize({
281
+ w: Math.round(origWidth * scale),
282
+ h: Math.round(origHeight * scale),
283
+ mode: lib.jimp.ResizeStrategy.BILINEAR
284
+ });
285
+ }
286
+
287
+ img = processed.getBuffer('image/jpeg', { quality: 85 });
288
+ }
289
+ else {
290
+ throw new Boom('No image processing library available');
291
+ }
292
+
293
+ const result = await img;
294
+ console.log(`[HD-Profile] Output: ${result.length} bytes, dims preserved (max 720px)`);
295
+ return { img: result };
296
+ };
297
+ // codex@LinkPreview --- Helper functions for building rich link previews
298
+ // Used internally by the richPreview flag in messages-send.js
299
+ // Can be imported directly for custom preview building in bot commands
300
+ const PREVIEW_USER_AGENTS = [
301
+ 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)',
302
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
303
+ 'Twitterbot/1.0'
304
+ ];
305
+ export const decodeHtmlEntities = (str = '') => str
306
+ .replace(/&/g, '&')
307
+ .replace(/&lt;/g, '<')
308
+ .replace(/&gt;/g, '>')
309
+ .replace(/&quot;/g, '"')
310
+ .replace(/&#39;/g, "'")
311
+ .replace(/&nbsp;/g, ' ')
312
+ .replace(/&#xa0;/gi, ' ')
313
+ .replace(/&#xb7;/gi, '')
314
+ .replace(/&#(\d+);/g, (_, dec) => String.fromCharCode(Number(dec)))
315
+ .replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)))
316
+ .trim();
317
+ export const fetchLinkMeta = async (url) => {
318
+ for (const ua of PREVIEW_USER_AGENTS) {
319
+ try {
320
+ const controller = new AbortController();
321
+ const t = setTimeout(() => controller.abort(), 5000);
322
+ const res = await fetch(url, { headers: { 'User-Agent': ua }, signal: controller.signal });
323
+ clearTimeout(t);
324
+ if (!res.ok) continue;
325
+ const html = await res.text();
326
+ const ogTitle = html.match(/<meta[^>]*property=["']og:title["'][^>]*content=["']([^"']*)["'][^>]*>/i);
327
+ const titleTag = html.match(/<title[^>]*>([^<]*)<\/title>/i);
328
+ const ogDesc = html.match(/<meta[^>]*property=["']og:description["'][^>]*content=["']([^"']*)["'][^>]*>/i);
329
+ const metaDesc = html.match(/<meta[^>]*name=["']description["'][^>]*content=["']([^"']*)["'][^>]*>/i);
330
+ const ogImg = html.match(/<meta[^>]*property=["']og:image(?::secure_url)?["'][^>]*content=["']([^"']*)["'][^>]*>/i);
331
+ return {
332
+ title: decodeHtmlEntities(ogTitle?.[1] || titleTag?.[1] || ''),
333
+ description: decodeHtmlEntities(ogDesc?.[1] || metaDesc?.[1] || ''),
334
+ imageUrl: decodeHtmlEntities(ogImg?.[1] || '')
335
+ };
336
+ } catch {}
337
+ }
338
+ return { title: '', description: '', imageUrl: '' };
339
+ };
340
+ export const resolvePreviewImage = async (imageUrl) => {
341
+ if (!imageUrl) return null;
342
+ for (const ua of PREVIEW_USER_AGENTS) {
343
+ try {
344
+ const res = await fetch(imageUrl, { headers: { 'User-Agent': ua } });
345
+ if (res.ok) return Buffer.from(await res.arrayBuffer());
346
+ } catch {}
347
+ }
348
+ return null;
349
+ };
350
+ export const resolvePreviewMeta = async (url, sock, customTitle, customDesc) => {
351
+ if (customTitle && customDesc) return { title: customTitle, description: customDesc };
352
+ if (url.includes('chat.whatsapp.com')) {
353
+ try {
354
+ const code = url.split('chat.whatsapp.com/')[1]?.split('?')[0];
355
+ const info = await sock?.groupGetInviteInfo(code);
356
+ return {
357
+ title: customTitle || info?.subject || '',
358
+ description: customDesc || `${info?.size || 0} members WhatsApp Group`
359
+ };
360
+ } catch {}
361
+ return { title: customTitle || '', description: customDesc || 'WhatsApp Group Invite' };
362
+ }
363
+ const meta = await fetchLinkMeta(url);
364
+ return { title: customTitle || meta.title, description: customDesc || meta.description };
365
+ };
366
+ export const buildLinkPreview = async (url, sock, options = {}) => {
367
+ const { customTitle = '', customDesc = '', customImage } = options;
368
+ const { title, description } = await resolvePreviewMeta(url, sock, customTitle, customDesc);
369
+ let imageBuffer = Buffer.isBuffer(customImage) ? customImage : null;
370
+ if (!imageBuffer) {
371
+ if (url.includes('chat.whatsapp.com')) {
372
+ try {
373
+ const code = url.split('chat.whatsapp.com/')[1]?.split('?')[0];
374
+ const info = await sock?.groupGetInviteInfo(code);
375
+ if (info?.id) {
376
+ const ppUrl = await sock?.profilePictureUrl(info.id, 'image');
377
+ imageBuffer = await resolvePreviewImage(ppUrl);
378
+ }
379
+ } catch {}
380
+ } else {
381
+ const meta = await fetchLinkMeta(url);
382
+ if (meta.imageUrl) imageBuffer = await resolvePreviewImage(meta.imageUrl);
383
+ }
384
+ }
385
+ return { url, title, description, imageBuffer };
386
+ };
387
+ /** gets the SHA256 of the given media message */
388
+ export const mediaMessageSHA256B64 = (message) => {
389
+ const media = Object.values(message)[0];
390
+ return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
391
+ };
392
+ export async function getAudioDuration(buffer) {
393
+ const musicMetadata = await import('music-metadata');
394
+ let metadata;
395
+ const options = {
396
+ duration: true
397
+ };
398
+ if (Buffer.isBuffer(buffer)) {
399
+ metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
400
+ }
401
+ else if (typeof buffer === 'string') {
402
+ metadata = await musicMetadata.parseFile(buffer, options);
403
+ }
404
+ else {
405
+ metadata = await musicMetadata.parseStream(buffer, undefined, options);
406
+ }
407
+ return metadata.format.duration;
408
+ }
409
+ /**
410
+ referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
411
+ */
412
+ export async function getAudioWaveform(buffer, logger) {
413
+ try {
414
+ // @ts-ignore
415
+ const { default: decoder } = await import('audio-decode');
416
+ let audioData;
417
+ if (Buffer.isBuffer(buffer)) {
418
+ audioData = buffer;
419
+ }
420
+ else if (typeof buffer === 'string') {
421
+ const rStream = createReadStream(buffer);
422
+ audioData = await toBuffer(rStream);
423
+ }
424
+ else {
425
+ audioData = await toBuffer(buffer);
426
+ }
427
+ const audioBuffer = await decoder(audioData);
428
+ const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
429
+ const samples = 64; // Number of samples we want to have in our final data set
430
+ const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
431
+ const filteredData = [];
432
+ for (let i = 0; i < samples; i++) {
433
+ const blockStart = blockSize * i; // the location of the first sample in the block
434
+ let sum = 0;
435
+ for (let j = 0; j < blockSize; j++) {
436
+ sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
437
+ }
438
+ filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
439
+ }
440
+ // This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
441
+ const multiplier = Math.pow(Math.max(...filteredData), -1);
442
+ const normalizedData = filteredData.map(n => n * multiplier);
443
+ // Generate waveform like WhatsApp
444
+ const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
445
+ return waveform;
446
+ }
447
+ catch (e) {
448
+ logger?.debug('Failed to generate waveform: ' + e);
449
+ }
450
+ }
451
+ export const toReadable = (buffer) => {
452
+ const readable = new Readable({ read: () => { } });
453
+ readable.push(buffer);
454
+ readable.push(null);
455
+ return readable;
456
+ };
457
+ export const toBuffer = async (stream) => {
458
+ const chunks = [];
459
+ for await (const chunk of stream) {
460
+ chunks.push(chunk);
461
+ }
462
+ stream.destroy();
463
+ return Buffer.concat(chunks);
464
+ };
465
+ export const getStream = async (item, opts) => {
466
+ if (Buffer.isBuffer(item)) {
467
+ return { stream: toReadable(item), type: 'buffer' };
468
+ }
469
+ if ('stream' in item) {
470
+ return { stream: item.stream, type: 'readable' };
471
+ }
472
+ const urlStr = item.url.toString();
473
+ if (urlStr.startsWith('data:')) {
474
+ const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
475
+ return { stream: toReadable(buffer), type: 'buffer' };
476
+ }
477
+ if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
478
+ return { stream: await getHttpStream(item.url, opts), type: 'remote' };
479
+ }
480
+ return { stream: createReadStream(item.url), type: 'file' };
481
+ };
482
+ /** generates a thumbnail for a given media, if required */
483
+ export async function generateThumbnail(file, mediaType, options) {
484
+ let thumbnail;
485
+ let originalImageDimensions;
486
+ if (mediaType === 'image') {
487
+ const { buffer, original } = await extractImageThumb(file);
488
+ thumbnail = buffer.toString('base64');
489
+ if (original.width && original.height) {
490
+ originalImageDimensions = {
491
+ width: original.width,
492
+ height: original.height
493
+ };
494
+ }
495
+ }
496
+ else if (mediaType === 'video') {
497
+ try {
498
+ const buff = await extractVideoThumb(file, '00:00:00', { width: 32, height: 32 });
499
+ thumbnail = buff.toString('base64');
500
+ }
501
+ catch (err) {
502
+ options.logger?.debug('could not generate video thumb: ' + err);
503
+ }
504
+ }
505
+ return {
506
+ thumbnail,
507
+ originalImageDimensions
508
+ };
509
+ }
510
+ export const getHttpStream = async (url, options = {}) => {
511
+ const response = await fetch(url.toString(), {
512
+ dispatcher: options.dispatcher,
513
+ method: 'GET',
514
+ headers: options.headers
515
+ });
516
+ if (!response.ok) {
517
+ throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
518
+ }
519
+ // @ts-ignore Node18+ Readable.fromWeb exists
520
+ return response.body instanceof Readable ? response.body : Readable.fromWeb(response.body);
521
+ };
522
+ export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
523
+ const { stream, type } = await getStream(media, opts);
524
+ logger?.debug('fetched media stream');
525
+ const mediaKey = Crypto.randomBytes(32);
526
+ const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
527
+ const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-enc');
528
+ const encFileWriteStream = createWriteStream(encFilePath);
529
+ let originalFileStream;
530
+ let originalFilePath;
531
+ if (saveOriginalFileIfRequired) {
532
+ originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-original');
533
+ originalFileStream = createWriteStream(originalFilePath);
534
+ }
535
+ let fileLength = 0;
536
+ const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
537
+ const hmac = Crypto.createHmac('sha256', macKey).update(iv);
538
+ const sha256Plain = Crypto.createHash('sha256');
539
+ const sha256Enc = Crypto.createHash('sha256');
540
+ const onChunk = async (buff) => {
541
+ sha256Enc.update(buff);
542
+ hmac.update(buff);
543
+ // Handle backpressure: if write returns false, wait for drain
544
+ if (!encFileWriteStream.write(buff)) {
545
+ await once(encFileWriteStream, 'drain');
546
+ }
547
+ };
548
+ try {
549
+ for await (const data of stream) {
550
+ fileLength += data.length;
551
+ if (type === 'remote' &&
552
+ opts?.maxContentLength &&
553
+ fileLength + data.length > opts.maxContentLength) {
554
+ throw new Boom(`content length exceeded when encrypting "${type}"`, {
555
+ data: { media, type }
556
+ });
557
+ }
558
+ if (originalFileStream) {
559
+ if (!originalFileStream.write(data)) {
560
+ await once(originalFileStream, 'drain');
561
+ }
562
+ }
563
+ sha256Plain.update(data);
564
+ await onChunk(aes.update(data));
565
+ }
566
+ await onChunk(aes.final());
567
+ const mac = hmac.digest().slice(0, 10);
568
+ sha256Enc.update(mac);
569
+ const fileSha256 = sha256Plain.digest();
570
+ const fileEncSha256 = sha256Enc.digest();
571
+ encFileWriteStream.write(mac);
572
+ const encFinishPromise = once(encFileWriteStream, 'finish');
573
+ const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve();
574
+ encFileWriteStream.end();
575
+ originalFileStream?.end?.();
576
+ stream.destroy();
577
+ // Wait for write streams to fully flush to disk
578
+ // This helps reduce memory pressure by allowing OS to release buffers
579
+ await encFinishPromise;
580
+ await originalFinishPromise;
581
+ logger?.debug('encrypted data successfully');
582
+ return {
583
+ mediaKey,
584
+ originalFilePath,
585
+ encFilePath,
586
+ mac,
587
+ fileEncSha256,
588
+ fileSha256,
589
+ fileLength
590
+ };
591
+ }
592
+ catch (error) {
593
+ // destroy all streams with error
594
+ encFileWriteStream.destroy();
595
+ originalFileStream?.destroy?.();
596
+ aes.destroy();
597
+ hmac.destroy();
598
+ sha256Plain.destroy();
599
+ sha256Enc.destroy();
600
+ stream.destroy();
601
+ try {
602
+ await fs.unlink(encFilePath);
603
+ if (originalFilePath) {
604
+ await fs.unlink(originalFilePath);
605
+ }
606
+ }
607
+ catch (err) {
608
+ logger?.error({ err }, 'failed deleting tmp files');
609
+ }
610
+ throw error;
611
+ }
612
+ };
613
+ export const DEF_MEDIA_HOST = 'mmg.whatsapp.net';
614
+ const AES_CHUNK_SIZE = 16;
615
+ const toSmallestChunkSize = (num) => {
616
+ return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
617
+ };
618
+ export const getUrlFromDirectPath = (directPath, host = DEF_MEDIA_HOST) => `https://${host}${directPath}`;
619
+ const extractHost = (url) => {
620
+ if (!url)
621
+ return undefined;
622
+ try {
623
+ return new URL(url).host;
624
+ }
625
+ catch {
626
+ return undefined;
627
+ }
628
+ };
629
+ export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
630
+ // Fallback host: explicit opt > host parsed from `url` > DEF_MEDIA_HOST.
631
+ // Lets us honor a non-default host carried by the proto without forcing callers to thread it through.
632
+ const fallbackHost = opts.host ?? extractHost(url);
633
+ const downloadUrl = directPath ? getUrlFromDirectPath(directPath, fallbackHost) : url;
634
+ if (!downloadUrl) {
635
+ throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 });
636
+ }
637
+ const keys = await getMediaKeys(mediaKey, type);
638
+ return downloadEncryptedContent(downloadUrl, keys, opts);
639
+ };
640
+ /**
641
+ * Decrypts and downloads an AES256-CBC encrypted file given the keys.
642
+ * Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
643
+ * */
644
+ export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
645
+ let bytesFetched = 0;
646
+ let startChunk = 0;
647
+ let firstBlockIsIV = false;
648
+ // if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
649
+ if (startByte) {
650
+ const chunk = toSmallestChunkSize(startByte || 0);
651
+ if (chunk) {
652
+ startChunk = chunk - AES_CHUNK_SIZE;
653
+ bytesFetched = chunk;
654
+ firstBlockIsIV = true;
655
+ }
656
+ }
657
+ const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
658
+ const headersInit = options?.headers ? options.headers : undefined;
659
+ const headers = {
660
+ ...(headersInit
661
+ ? Array.isArray(headersInit)
662
+ ? Object.fromEntries(headersInit)
663
+ : headersInit
664
+ : {}),
665
+ Origin: DEFAULT_ORIGIN
666
+ };
667
+ if (startChunk || endChunk) {
668
+ headers.Range = `bytes=${startChunk}-`;
669
+ if (endChunk) {
670
+ headers.Range += endChunk;
671
+ }
672
+ }
673
+ // download the message
674
+ const fetched = await getHttpStream(downloadUrl, {
675
+ ...(options || {}),
676
+ headers
677
+ });
678
+ let remainingBytes = Buffer.from([]);
679
+ let aes;
680
+ const pushBytes = (bytes, push) => {
681
+ if (startByte || endByte) {
682
+ const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
683
+ const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
684
+ push(bytes.slice(start, end));
685
+ bytesFetched += bytes.length;
686
+ }
687
+ else {
688
+ push(bytes);
689
+ }
690
+ };
691
+ const output = new Transform({
692
+ transform(chunk, _, callback) {
693
+ let data = remainingBytes.length ? Buffer.concat([remainingBytes, chunk]) : chunk;
694
+ const decryptLength = toSmallestChunkSize(data.length);
695
+ remainingBytes = data.slice(decryptLength);
696
+ data = data.slice(0, decryptLength);
697
+ if (!aes) {
698
+ let ivValue = iv;
699
+ if (firstBlockIsIV) {
700
+ ivValue = data.slice(0, AES_CHUNK_SIZE);
701
+ data = data.slice(AES_CHUNK_SIZE);
702
+ }
703
+ aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
704
+ // if an end byte that is not EOF is specified
705
+ // stop auto padding (PKCS7) -- otherwise throws an error for decryption
706
+ if (endByte) {
707
+ aes.setAutoPadding(false);
708
+ }
709
+ }
710
+ try {
711
+ pushBytes(aes.update(data), b => this.push(b));
712
+ callback();
713
+ }
714
+ catch (error) {
715
+ callback(error);
716
+ }
717
+ },
718
+ final(callback) {
719
+ try {
720
+ pushBytes(aes.final(), b => this.push(b));
721
+ callback();
722
+ }
723
+ catch (error) {
724
+ callback(error);
725
+ }
726
+ }
727
+ });
728
+ return fetched.pipe(output, { end: true });
729
+ };
730
+ export function extensionForMediaMessage(message) {
731
+ const getExtension = (mimetype) => mimetype.split(';')[0]?.split('/')[1];
732
+ const type = Object.keys(message)[0];
733
+ let extension;
734
+ if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
735
+ extension = '.jpeg';
736
+ }
737
+ else {
738
+ const messageContent = message[type];
739
+ extension = getExtension(messageContent.mimetype);
740
+ }
741
+ return extension;
742
+ }
743
+ const isNodeRuntime = () => {
744
+ return (typeof process !== 'undefined' &&
745
+ process.versions?.node !== null &&
746
+ typeof process.versions.bun === 'undefined' &&
747
+ typeof globalThis.Deno === 'undefined');
748
+ };
749
+ export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
750
+ if (redirectCount > 5) {
751
+ throw new Error('Too many redirects');
752
+ }
753
+ const parsedUrl = new URL(url);
754
+ const httpModule = parsedUrl.protocol === 'https:' ? await import('https') : await import('http');
755
+ // Get file size for Content-Length header (required for Node.js streaming)
756
+ const fileStats = await fs.stat(filePath);
757
+ const fileSize = fileStats.size;
758
+ return new Promise((resolve, reject) => {
759
+ const req = httpModule.request({
760
+ hostname: parsedUrl.hostname,
761
+ port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
762
+ path: parsedUrl.pathname + parsedUrl.search,
763
+ method: 'POST',
764
+ headers: {
765
+ ...headers,
766
+ 'Content-Length': fileSize
767
+ },
768
+ agent,
769
+ timeout: timeoutMs
770
+ }, res => {
771
+ // Handle redirects (3xx)
772
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
773
+ res.resume(); // Consume response to free resources
774
+ const newUrl = new URL(res.headers.location, url).toString();
775
+ resolve(uploadWithNodeHttp({
776
+ url: newUrl,
777
+ filePath,
778
+ headers,
779
+ timeoutMs,
780
+ agent
781
+ }, redirectCount + 1));
782
+ return;
783
+ }
784
+ let body = '';
785
+ res.on('data', chunk => (body += chunk));
786
+ res.on('end', () => {
787
+ try {
788
+ resolve(JSON.parse(body));
789
+ }
790
+ catch {
791
+ resolve(undefined);
792
+ }
793
+ });
794
+ });
795
+ req.on('error', reject);
796
+ req.on('timeout', () => {
797
+ req.destroy();
798
+ reject(new Error('Upload timeout'));
799
+ });
800
+ const stream = createReadStream(filePath);
801
+ stream.pipe(req);
802
+ stream.on('error', err => {
803
+ req.destroy();
804
+ reject(err);
805
+ });
806
+ });
807
+ };
808
+ const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
809
+ // Convert Node.js Readable to Web ReadableStream
810
+ const nodeStream = createReadStream(filePath);
811
+ const webStream = Readable.toWeb(nodeStream);
812
+ // Native fetch only accepts Undici-style dispatchers, not generic https Agents.
813
+ const dispatcher = typeof agent?.dispatch === 'function' ? agent : undefined;
814
+ const response = await fetch(url, {
815
+ ...(dispatcher ? { dispatcher } : {}),
816
+ method: 'POST',
817
+ body: webStream,
818
+ headers,
819
+ duplex: 'half',
820
+ signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
821
+ });
822
+ try {
823
+ return (await response.json());
824
+ }
825
+ catch {
826
+ return undefined;
827
+ }
828
+ };
829
+ /**
830
+ * Uploads media to WhatsApp servers.
831
+ *
832
+ * ## Why we have two upload implementations:
833
+ *
834
+ * Node.js's native `fetch` (powered by undici) has a known bug where it buffers
835
+ * the entire request body in memory before sending, even when using streams.
836
+ * This causes memory issues with large files (e.g., 1GB file = 1GB+ memory usage).
837
+ * See: https://github.com/nodejs/undici/issues/4058
838
+ *
839
+ * Other runtimes (Bun, Deno, browsers) correctly stream the request body without
840
+ * buffering, so we can use the web-standard Fetch API there.
841
+ *
842
+ * ## Future considerations:
843
+ * Once the undici bug is fixed, we can simplify this to use only the Fetch API
844
+ * across all runtimes. Monitor the GitHub issue for updates.
845
+ */
846
+ const uploadMedia = async (params, logger) => {
847
+ if (isNodeRuntime()) {
848
+ logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)');
849
+ return uploadWithNodeHttp(params);
850
+ }
851
+ else {
852
+ logger?.debug('Using web-standard Fetch API for upload');
853
+ return uploadWithFetch(params);
854
+ }
855
+ };
856
+ export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
857
+ return async (filePath, { mediaType, fileEncSha256B64, timeoutMs, newsletter }) => {
858
+ // send a query JSON to obtain the url & auth token to upload our media
859
+ let uploadInfo = await refreshMediaConn(false);
860
+ let urls;
861
+ const hosts = [...customUploadHosts, ...uploadInfo.hosts];
862
+ fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64);
863
+ // Prepare common headers
864
+ const customHeaders = (() => {
865
+ const hdrs = options?.headers;
866
+ if (!hdrs)
867
+ return {};
868
+ return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
869
+ })();
870
+ const headers = {
871
+ ...customHeaders,
872
+ 'Content-Type': 'application/octet-stream',
873
+ Origin: DEFAULT_ORIGIN
874
+ };
875
+ for (const { hostname } of hosts) {
876
+ logger.debug(`uploading to "${hostname}"`);
877
+ const auth = encodeURIComponent(uploadInfo.auth);
878
+ // Lia@Changes 06-02-26 --- Switch media path map for newsletter uploads
879
+ const mediaPathMap = newsletter ? NEWSLETTER_MEDIA_PATH_MAP : MEDIA_PATH_MAP;
880
+ // Lia@Changes 20-03-26 --- Add server thumb for newsletter media
881
+ const serverThumb = newsletter ? '&server_thumb_gen=1' : '';
882
+ const url = `https://${hostname}${mediaPathMap[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}${serverThumb}`;
883
+ let result;
884
+ try {
885
+ result = await uploadMedia({
886
+ url,
887
+ filePath,
888
+ headers,
889
+ timeoutMs,
890
+ agent: fetchAgent
891
+ }, logger);
892
+ if (result?.url || result?.direct_path) {
893
+ urls = {
894
+ mediaUrl: result.url,
895
+ directPath: result.direct_path,
896
+ meta_hmac: result.meta_hmac,
897
+ fbid: result.fbid,
898
+ ts: result.ts,
899
+ thumbnailDirectPath: result.thumbnail_info?.thumbnail_direct_path,
900
+ thumbnailSha256: result.thumbnail_info?.thumbnail_sha256
901
+ };
902
+ break;
903
+ }
904
+ else {
905
+ uploadInfo = await refreshMediaConn(true);
906
+ throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
907
+ }
908
+ }
909
+ catch (error) {
910
+ const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
911
+ logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
912
+ }
913
+ }
914
+ if (!urls) {
915
+ throw new Boom('Media upload failed on all hosts', { statusCode: 500 });
916
+ }
917
+ return urls;
918
+ };
919
+ };
920
+ const getMediaRetryKey = (mediaKey) => {
921
+ return hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
922
+ };
923
+ /**
924
+ * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
925
+ */
926
+ export const encryptMediaRetryRequest = (key, mediaKey, meId) => {
927
+ const recp = { stanzaId: key.id };
928
+ const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish();
929
+ const iv = Crypto.randomBytes(12);
930
+ const retryKey = getMediaRetryKey(mediaKey);
931
+ const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id));
932
+ const req = {
933
+ tag: 'receipt',
934
+ attrs: {
935
+ id: key.id,
936
+ to: jidNormalizedUser(meId),
937
+ type: 'server-error'
938
+ },
939
+ content: [
940
+ // this encrypt node is actually pretty useless
941
+ // the media is returned even without this node
942
+ // keeping it here to maintain parity with WA Web
943
+ {
944
+ tag: 'encrypt',
945
+ attrs: {},
946
+ content: [
947
+ { tag: 'enc_p', attrs: {}, content: ciphertext },
948
+ { tag: 'enc_iv', attrs: {}, content: iv }
949
+ ]
950
+ },
951
+ {
952
+ tag: 'rmr',
953
+ attrs: {
954
+ jid: key.remoteJid,
955
+ from_me: (!!key.fromMe).toString(),
956
+ // @ts-ignore
957
+ participant: key.participant || undefined
958
+ }
959
+ }
960
+ ]
961
+ };
962
+ return req;
963
+ };
964
+ export const decodeMediaRetryNode = (node) => {
965
+ const rmrNode = getBinaryNodeChild(node, 'rmr');
966
+ const event = {
967
+ key: {
968
+ id: node.attrs.id,
969
+ remoteJid: rmrNode.attrs.jid,
970
+ fromMe: rmrNode.attrs.from_me === 'true',
971
+ participant: rmrNode.attrs.participant
972
+ }
973
+ };
974
+ const errorNode = getBinaryNodeChild(node, 'error');
975
+ if (errorNode) {
976
+ const errorCode = +errorNode.attrs.code;
977
+ event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
978
+ data: errorNode.attrs,
979
+ statusCode: getStatusCodeForMediaRetry(errorCode)
980
+ });
981
+ }
982
+ else {
983
+ const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt');
984
+ const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p');
985
+ const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv');
986
+ if (ciphertext && iv) {
987
+ event.media = { ciphertext, iv };
988
+ }
989
+ else {
990
+ event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
991
+ }
992
+ }
993
+ return event;
994
+ };
995
+ export const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
996
+ const retryKey = getMediaRetryKey(mediaKey);
997
+ const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
998
+ return proto.MediaRetryNotification.decode(plaintext);
999
+ };
1000
+ export const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
1001
+ const MEDIA_RETRY_STATUS_MAP = {
1002
+ [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
1003
+ [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
1004
+ [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
1005
+ [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
1006
+ };