@genuxofficial/baileys 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/LICENSE +1 -1
  2. package/WAProto/WAProto.proto +4633 -0
  3. package/engine-requirements.js +1 -1
  4. package/lib/Defaults/index.d.ts +5 -3
  5. package/lib/Defaults/index.js +7 -7
  6. package/lib/Signal/libsignal.js +9 -18
  7. package/lib/Socket/Client/types.d.ts +2 -0
  8. package/lib/Socket/Client/websocket.js +1 -1
  9. package/lib/Socket/business.d.ts +40 -38
  10. package/lib/Socket/chats.d.ts +17 -20
  11. package/lib/Socket/chats.js +1 -85
  12. package/lib/Socket/groups.d.ts +25 -28
  13. package/lib/Socket/groups.js +9 -10
  14. package/lib/Socket/index.d.ts +46 -44
  15. package/lib/Socket/messages-recv.d.ts +37 -36
  16. package/lib/Socket/messages-recv.js +14 -26
  17. package/lib/Socket/messages-send.d.ts +35 -33
  18. package/lib/Socket/messages-send.js +10 -8
  19. package/lib/Socket/newsletter.d.ts +28 -31
  20. package/lib/Socket/newsletter.js +21 -17
  21. package/lib/Socket/socket.d.ts +7 -5
  22. package/lib/Socket/socket.js +1 -1
  23. package/lib/Socket/usync.d.ts +11 -9
  24. package/lib/Socket/usync.js +15 -10
  25. package/lib/Store/make-in-memory-store.d.ts +1 -1
  26. package/lib/Store/make-ordered-dictionary.d.ts +1 -1
  27. package/lib/Types/Auth.d.ts +2 -0
  28. package/lib/Types/Chat.d.ts +2 -8
  29. package/lib/Types/Contact.d.ts +0 -5
  30. package/lib/Types/GroupMetadata.d.ts +4 -5
  31. package/lib/Types/Label.d.ts +0 -11
  32. package/lib/Types/Label.js +1 -1
  33. package/lib/Types/LabelAssociation.js +1 -1
  34. package/lib/Types/Message.d.ts +27 -2
  35. package/lib/Types/Newsletter.js +2 -2
  36. package/lib/Types/Socket.d.ts +2 -0
  37. package/lib/Types/index.js +1 -1
  38. package/lib/Utils/auth-utils.js +3 -3
  39. package/lib/Utils/business.js +17 -5
  40. package/lib/Utils/chat-utils.d.ts +10 -8
  41. package/lib/Utils/chat-utils.js +0 -27
  42. package/lib/Utils/crypto.d.ts +16 -14
  43. package/lib/Utils/crypto.js +22 -34
  44. package/lib/Utils/decode-wa-message.d.ts +1 -1
  45. package/lib/Utils/decode-wa-message.js +16 -31
  46. package/lib/Utils/generics.d.ts +8 -33
  47. package/lib/Utils/generics.js +12 -98
  48. package/lib/Utils/link-preview.js +1 -34
  49. package/lib/Utils/make-mutex.d.ts +2 -2
  50. package/lib/Utils/messages-media.d.ts +19 -29
  51. package/lib/Utils/messages-media.js +87 -151
  52. package/lib/Utils/messages.d.ts +8 -5
  53. package/lib/Utils/messages.js +20 -28
  54. package/lib/Utils/noise-handler.d.ts +6 -4
  55. package/lib/Utils/process-message.js +2 -2
  56. package/lib/Utils/validate-connection.d.ts +2 -2
  57. package/lib/WABinary/decode.d.ts +4 -2
  58. package/lib/WABinary/decode.js +7 -17
  59. package/lib/WABinary/encode.d.ts +3 -1
  60. package/lib/WABinary/encode.js +7 -17
  61. package/lib/WABinary/generic-utils.d.ts +6 -6
  62. package/lib/WABinary/generic-utils.js +36 -21
  63. package/lib/WABinary/jid-utils.d.ts +6 -2
  64. package/lib/WABinary/jid-utils.js +5 -1
  65. package/lib/WAM/BinaryInfo.d.ts +12 -2
  66. package/lib/WAM/encode.d.ts +3 -1
  67. package/lib/WAUSync/Protocols/USyncContactProtocol.js +2 -2
  68. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +23 -14
  69. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +2 -2
  70. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +2 -2
  71. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +1 -1
  72. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +1 -1
  73. package/lib/WAUSync/USyncQuery.js +13 -17
  74. package/package.json +59 -53
  75. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  76. package/lib/Store/make-cache-manager-store.js +0 -83
@@ -1,3 +1,7 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ /// <reference types="node" />
4
+ /// <reference types="node" />
1
5
  import { Boom } from '@hapi/boom';
2
6
  import { AxiosRequestConfig } from 'axios';
3
7
  import { Readable, Transform } from 'stream';
@@ -10,7 +14,7 @@ export declare const hkdfInfoKey: (type: MediaType) => string;
10
14
  /** generates all the keys required to encrypt/decrypt & sign a media message */
11
15
  export declare function getMediaKeys(buffer: Uint8Array | string | null | undefined, mediaType: MediaType): Promise<MediaDecryptionKeyInfo>;
12
16
  export declare const extractImageThumb: (bufferOrFilePath: Readable | Buffer | string, width?: number) => Promise<{
13
- buffer: Buffer<ArrayBufferLike>;
17
+ buffer: Buffer;
14
18
  original: {
15
19
  width: number | undefined;
16
20
  height: number | undefined;
@@ -18,21 +22,7 @@ export declare const extractImageThumb: (bufferOrFilePath: Readable | Buffer | s
18
22
  }>;
19
23
  export declare const encodeBase64EncodedStringForUpload: (b64: string) => string;
20
24
  export declare const generateProfilePicture: (mediaUpload: WAMediaUpload) => Promise<{
21
- img: Buffer<ArrayBufferLike>;
22
- }>;
23
- export declare const generateProfilePictureFull: (img: any) => Promise<{
24
- img: any;
25
- }>;
26
- export declare const generateProfilePictureFP: (buffer: any) => Promise<{
27
- img: any;
28
- preview: any;
29
- }>;
30
- export declare const generatePP: (buffer: any) => Promise<{
31
- img: any;
32
- preview: any;
33
- }>;
34
- export declare const changeprofileFull: (img: any) => Promise<{
35
- img: any;
25
+ img: Buffer;
36
26
  }>;
37
27
  /** gets the SHA256 of the given media message */
38
28
  export declare const mediaMessageSHA256B64: (message: WAMessageContent) => string | null | undefined;
@@ -40,9 +30,9 @@ export declare function getAudioDuration(buffer: Buffer | string | Readable): Pr
40
30
  /**
41
31
  referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
42
32
  */
43
- export declare function getAudioWaveform(buffer: Buffer | string | Readable, logger?: ILogger): Promise<Uint8Array<ArrayBuffer> | undefined>;
33
+ export declare function getAudioWaveform(buffer: Buffer | string | Readable, logger?: ILogger): Promise<Uint8Array | undefined>;
44
34
  export declare const toReadable: (buffer: Buffer) => Readable;
45
- export declare const toBuffer: (stream: Readable) => Promise<Buffer<ArrayBuffer>>;
35
+ export declare const toBuffer: (stream: Readable) => Promise<Buffer>;
46
36
  export declare const getStream: (item: WAMediaUpload, opts?: AxiosRequestConfig) => Promise<{
47
37
  readonly stream: Readable;
48
38
  readonly type: "buffer";
@@ -76,22 +66,22 @@ type EncryptedStreamOptions = {
76
66
  };
77
67
  export declare const prepareStream: (media: WAMediaUpload, mediaType: MediaType, { logger, saveOriginalFileIfRequired, opts }?: EncryptedStreamOptions) => Promise<{
78
68
  mediaKey: undefined;
79
- encWriteStream: Buffer<ArrayBuffer>;
69
+ encFilePath: string;
70
+ originalFilePath: string | undefined;
80
71
  fileLength: number;
81
- fileSha256: Buffer<ArrayBufferLike>;
72
+ fileSha256: Buffer;
82
73
  fileEncSha256: undefined;
83
74
  bodyPath: string | undefined;
84
75
  didSaveToTmpPath: boolean;
85
76
  }>;
86
77
  export declare const encryptedStream: (media: WAMediaUpload, mediaType: MediaType, { logger, saveOriginalFileIfRequired, opts }?: EncryptedStreamOptions) => Promise<{
87
- mediaKey: Buffer<ArrayBufferLike>;
88
- encWriteStream: Readable;
89
- bodyPath: string | undefined;
90
- mac: Buffer<ArrayBuffer>;
91
- fileEncSha256: Buffer<ArrayBufferLike>;
92
- fileSha256: Buffer<ArrayBufferLike>;
78
+ mediaKey: Buffer;
79
+ originalFilePath: string | undefined;
80
+ encFilePath: string;
81
+ mac: Buffer;
82
+ fileEncSha256: Buffer;
83
+ fileSha256: Buffer;
93
84
  fileLength: number;
94
- didSaveToTmpPath: boolean;
95
85
  }>;
96
86
  export type MediaDownloadOptions = {
97
87
  startByte?: number;
@@ -116,8 +106,8 @@ export declare const decodeMediaRetryNode: (node: BinaryNode) => {
116
106
  media?: {
117
107
  ciphertext: Uint8Array;
118
108
  iv: Uint8Array;
119
- };
120
- error?: Boom;
109
+ } | undefined;
110
+ error?: Boom<any> | undefined;
121
111
  };
122
112
  export declare const decryptMediaRetryData: ({ ciphertext, iv }: {
123
113
  ciphertext: Uint8Array;
@@ -15,33 +15,18 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
35
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
36
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
27
  };
38
28
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.getStatusCodeForMediaRetry = exports.decryptMediaRetryData = exports.decodeMediaRetryNode = exports.encryptMediaRetryRequest = exports.getWAUploadToServer = exports.downloadEncryptedContent = exports.downloadContentFromMessage = exports.getUrlFromDirectPath = exports.encryptedStream = exports.prepareStream = exports.getHttpStream = exports.getStream = exports.toBuffer = exports.toReadable = exports.mediaMessageSHA256B64 = exports.changeprofileFull = exports.generatePP = exports.generateProfilePictureFP = exports.generateProfilePictureFull = exports.generateProfilePicture = exports.encodeBase64EncodedStringForUpload = exports.extractImageThumb = exports.hkdfInfoKey = void 0;
40
- exports.getMediaKeys = getMediaKeys;
41
- exports.getAudioDuration = getAudioDuration;
42
- exports.getAudioWaveform = getAudioWaveform;
43
- exports.generateThumbnail = generateThumbnail;
44
- exports.extensionForMediaMessage = extensionForMediaMessage;
29
+ exports.getStatusCodeForMediaRetry = exports.decryptMediaRetryData = exports.decodeMediaRetryNode = exports.encryptMediaRetryRequest = exports.getWAUploadToServer = exports.extensionForMediaMessage = exports.downloadEncryptedContent = exports.downloadContentFromMessage = exports.getUrlFromDirectPath = exports.encryptedStream = exports.prepareStream = exports.getHttpStream = exports.generateThumbnail = exports.getStream = exports.toBuffer = exports.toReadable = exports.getAudioWaveform = exports.getAudioDuration = exports.mediaMessageSHA256B64 = exports.generateProfilePicture = exports.encodeBase64EncodedStringForUpload = exports.extractImageThumb = exports.getMediaKeys = exports.hkdfInfoKey = void 0;
45
30
  const boom_1 = require("@hapi/boom");
46
31
  const axios_1 = __importDefault(require("axios"));
47
32
  const child_process_1 = require("child_process");
@@ -61,11 +46,13 @@ const getTmpFilesDirectory = () => (0, os_1.tmpdir)();
61
46
  const getImageProcessingLibrary = async () => {
62
47
  const [_jimp, sharp] = await Promise.all([
63
48
  (async () => {
64
- const jimp = await (Promise.resolve().then(() => __importStar(require('jimp'))).catch(() => { }));
49
+ const jimp = await (import('jimp')
50
+ .catch(() => { }));
65
51
  return jimp;
66
52
  })(),
67
53
  (async () => {
68
- const sharp = await (Promise.resolve().then(() => __importStar(require('sharp'))).catch(() => { }));
54
+ const sharp = await (import('sharp')
55
+ .catch(() => { }));
69
56
  return sharp;
70
57
  })()
71
58
  ]);
@@ -99,6 +86,7 @@ async function getMediaKeys(buffer, mediaType) {
99
86
  macKey: expandedMediaKey.slice(48, 80),
100
87
  };
101
88
  }
89
+ exports.getMediaKeys = getMediaKeys;
102
90
  /** Extracts video thumb using FFMPEG */
103
91
  const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
104
92
  const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`;
@@ -180,76 +168,6 @@ const generateProfilePicture = async (mediaUpload) => {
180
168
  };
181
169
  };
182
170
  exports.generateProfilePicture = generateProfilePicture;
183
- const generateProfilePictureFull = async (img) => {
184
- const Jimp = require('jimp');
185
- const { read, MIME_JPEG, RESIZE_BILINEAR } = require('jimp');
186
- const jimp = await read(img);
187
- const min = Math.min(jimp.getWidth(), jimp.getHeight());
188
- const cropped = jimp.crop(0, 0, jimp.getWidth(), jimp.getHeight());
189
- let width = jimp.getWidth(), hight = jimp.getHeight(), ratio;
190
- if (width > hight) {
191
- ratio = jimp.getWidth() / 720;
192
- }
193
- else {
194
- ratio = jimp.getWidth() / 324;
195
- }
196
- ;
197
- width = width / ratio;
198
- hight = hight / ratio;
199
- img = cropped.quality(100).resize(width, hight).getBufferAsync(MIME_JPEG);
200
- return {
201
- img: await cropped.quality(100).resize(width, hight).getBufferAsync(MIME_JPEG),
202
- };
203
- };
204
- exports.generateProfilePictureFull = generateProfilePictureFull;
205
- const generateProfilePictureFP = async (buffer) => {
206
- const Jimp = require('jimp');
207
- const { read, MIME_JPEG, RESIZE_BILINEAR } = require('jimp');
208
- const jimp = await Jimp.read(buffer);
209
- const min = jimp.getWidth();
210
- const max = jimp.getHeight();
211
- const cropped = jimp.crop(0, 0, min, max);
212
- return {
213
- img: await cropped.scaleToFit(720, 720).getBufferAsync(Jimp.MIME_JPEG),
214
- preview: await cropped.normalize().getBufferAsync(Jimp.MIME_JPEG),
215
- };
216
- };
217
- exports.generateProfilePictureFP = generateProfilePictureFP;
218
- const generatePP = async (buffer) => {
219
- const Jimp = require('jimp');
220
- const { read, MIME_JPEG, RESIZE_BILINEAR } = require('jimp');
221
- const jimp = await Jimp.read(buffer);
222
- const min = jimp.getWidth();
223
- const max = jimp.getHeight();
224
- const cropped = jimp.crop(0, 0, min, max);
225
- return {
226
- img: await cropped.scaleToFit(720, 720).getBufferAsync(Jimp.MIME_JPEG),
227
- preview: await cropped.normalize().getBufferAsync(Jimp.MIME_JPEG),
228
- };
229
- };
230
- exports.generatePP = generatePP;
231
- const changeprofileFull = async (img) => {
232
- const Jimp = require('jimp');
233
- const { read, MIME_JPEG, RESIZE_BILINEAR } = require('jimp');
234
- const jimp = await read(img);
235
- const min = Math.min(jimp.getWidth(), jimp.getHeight());
236
- const cropped = jimp.crop(0, 0, jimp.getWidth(), jimp.getHeight());
237
- let width = jimp.getWidth(), hight = jimp.getHeight(), ratio;
238
- if (width > hight) {
239
- ratio = jimp.getWidth() / 720;
240
- }
241
- else {
242
- ratio = jimp.getWidth() / 324;
243
- }
244
- ;
245
- width = width / ratio;
246
- hight = hight / ratio;
247
- img = cropped.quality(100).resize(width, hight).getBufferAsync(MIME_JPEG);
248
- return {
249
- img: await cropped.quality(100).resize(width, hight).getBufferAsync(MIME_JPEG),
250
- };
251
- };
252
- exports.changeprofileFull = changeprofileFull;
253
171
  /** gets the SHA256 of the given media message */
254
172
  const mediaMessageSHA256B64 = (message) => {
255
173
  const media = Object.values(message)[0];
@@ -257,7 +175,7 @@ const mediaMessageSHA256B64 = (message) => {
257
175
  };
258
176
  exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
259
177
  async function getAudioDuration(buffer) {
260
- const musicMetadata = await Promise.resolve().then(() => __importStar(require('music-metadata')));
178
+ const musicMetadata = await import('music-metadata');
261
179
  let metadata;
262
180
  if (Buffer.isBuffer(buffer)) {
263
181
  metadata = await musicMetadata.parseBuffer(buffer, undefined, { duration: true });
@@ -276,6 +194,7 @@ async function getAudioDuration(buffer) {
276
194
  }
277
195
  return metadata.format.duration;
278
196
  }
197
+ exports.getAudioDuration = getAudioDuration;
279
198
  /**
280
199
  referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
281
200
  */
@@ -317,6 +236,7 @@ async function getAudioWaveform(buffer, logger) {
317
236
  logger === null || logger === void 0 ? void 0 : logger.debug('Failed to generate waveform: ' + e);
318
237
  }
319
238
  }
239
+ exports.getAudioWaveform = getAudioWaveform;
320
240
  const toReadable = (buffer) => {
321
241
  const readable = new stream_1.Readable({ read: () => { } });
322
242
  readable.push(buffer);
@@ -378,6 +298,7 @@ async function generateThumbnail(file, mediaType, options) {
378
298
  originalImageDimensions
379
299
  };
380
300
  }
301
+ exports.generateThumbnail = generateThumbnail;
381
302
  const getHttpStream = async (url, options = {}) => {
382
303
  const fetched = await axios_1.default.get(url.toString(), { ...options, responseType: 'stream' });
383
304
  return fetched.data;
@@ -386,25 +307,34 @@ exports.getHttpStream = getHttpStream;
386
307
  const prepareStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
387
308
  const { stream, type } = await (0, exports.getStream)(media, opts);
388
309
  logger === null || logger === void 0 ? void 0 : logger.debug('fetched media stream');
389
- let bodyPath;
310
+ const encFilePath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)() + '-enc');
311
+ const encFileWriteStream = (0, fs_1.createWriteStream)(encFilePath);
312
+ let originalFilePath;
390
313
  let didSaveToTmpPath = false;
314
+ let bodyPath;
391
315
  try {
392
316
  const buffer = await (0, exports.toBuffer)(stream);
393
- if (type === 'file') {
394
- bodyPath = media.url;
395
- }
396
- else if (saveOriginalFileIfRequired) {
397
- bodyPath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)());
398
- (0, fs_1.writeFileSync)(bodyPath, buffer);
317
+ // Write encrypted data
318
+ encFileWriteStream.write(buffer);
319
+ encFileWriteStream.end();
320
+ // Save original file if required
321
+ if (saveOriginalFileIfRequired) {
322
+ originalFilePath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)() + '-original');
323
+ (0, fs_1.writeFileSync)(originalFilePath, buffer);
324
+ bodyPath = originalFilePath;
399
325
  didSaveToTmpPath = true;
400
326
  }
327
+ else if (type === 'file' && typeof media.url === 'string') {
328
+ bodyPath = media.url;
329
+ }
401
330
  const fileLength = buffer.length;
402
331
  const fileSha256 = Crypto.createHash('sha256').update(buffer).digest();
403
332
  stream === null || stream === void 0 ? void 0 : stream.destroy();
404
- logger === null || logger === void 0 ? void 0 : logger.debug('prepare stream data successfully');
333
+ logger === null || logger === void 0 ? void 0 : logger.debug('prepared stream data successfully');
405
334
  return {
406
335
  mediaKey: undefined,
407
- encWriteStream: buffer,
336
+ encFilePath,
337
+ originalFilePath,
408
338
  fileLength,
409
339
  fileSha256,
410
340
  fileEncSha256: undefined,
@@ -413,14 +343,17 @@ const prepareStream = async (media, mediaType, { logger, saveOriginalFileIfRequi
413
343
  };
414
344
  }
415
345
  catch (error) {
416
- // destroy all streams with error
417
346
  stream.destroy();
418
- if (didSaveToTmpPath) {
347
+ try {
348
+ await fs_1.promises.unlink(encFilePath);
349
+ }
350
+ catch (_) { }
351
+ if (didSaveToTmpPath && bodyPath) {
419
352
  try {
420
353
  await fs_1.promises.unlink(bodyPath);
421
354
  }
422
355
  catch (err) {
423
- logger === null || logger === void 0 ? void 0 : logger.error({ err }, 'failed to save to tmp path');
356
+ logger === null || logger === void 0 ? void 0 : logger.error({ err }, 'failed to delete tmp bodyPath');
424
357
  }
425
358
  }
426
359
  throw error;
@@ -428,27 +361,29 @@ const prepareStream = async (media, mediaType, { logger, saveOriginalFileIfRequi
428
361
  };
429
362
  exports.prepareStream = prepareStream;
430
363
  const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
364
+ var _a, _b;
431
365
  const { stream, type } = await (0, exports.getStream)(media, opts);
432
366
  logger === null || logger === void 0 ? void 0 : logger.debug('fetched media stream');
433
367
  const mediaKey = Crypto.randomBytes(32);
434
368
  const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
435
- const encWriteStream = new stream_1.Readable({ read: () => { } });
436
- let bodyPath;
437
- let writeStream;
438
- let didSaveToTmpPath = false;
439
- if (type === 'file') {
440
- bodyPath = media.url.toString();
441
- }
442
- else if (saveOriginalFileIfRequired) {
443
- bodyPath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)());
444
- writeStream = (0, fs_1.createWriteStream)(bodyPath);
445
- didSaveToTmpPath = true;
369
+ const encFilePath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)() + '-enc');
370
+ const encFileWriteStream = (0, fs_1.createWriteStream)(encFilePath);
371
+ let originalFileStream;
372
+ let originalFilePath;
373
+ if (saveOriginalFileIfRequired) {
374
+ originalFilePath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)() + '-original');
375
+ originalFileStream = (0, fs_1.createWriteStream)(originalFilePath);
446
376
  }
447
377
  let fileLength = 0;
448
378
  const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
449
379
  let hmac = Crypto.createHmac('sha256', macKey).update(iv);
450
380
  let sha256Plain = Crypto.createHash('sha256');
451
381
  let sha256Enc = Crypto.createHash('sha256');
382
+ const onChunk = (buff) => {
383
+ sha256Enc.update(buff);
384
+ hmac.update(buff);
385
+ encFileWriteStream.write(buff);
386
+ };
452
387
  try {
453
388
  for await (const data of stream) {
454
389
  fileLength += data.length;
@@ -459,10 +394,12 @@ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfReq
459
394
  data: { media, type }
460
395
  });
461
396
  }
462
- sha256Plain = sha256Plain.update(data);
463
- if (writeStream && !writeStream.write(data)) {
464
- await (0, events_1.once)(writeStream, 'drain');
397
+ if (originalFileStream) {
398
+ if (!originalFileStream.write(data)) {
399
+ await (0, events_1.once)(originalFileStream, 'drain');
400
+ }
465
401
  }
402
+ sha256Plain.update(data);
466
403
  onChunk(aes.update(data));
467
404
  }
468
405
  onChunk(aes.final());
@@ -470,46 +407,43 @@ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfReq
470
407
  sha256Enc = sha256Enc.update(mac);
471
408
  const fileSha256 = sha256Plain.digest();
472
409
  const fileEncSha256 = sha256Enc.digest();
473
- encWriteStream.push(mac);
474
- encWriteStream.push(null);
475
- writeStream === null || writeStream === void 0 ? void 0 : writeStream.end();
410
+ //encWriteStream.push(mac)
411
+ //encWriteStream.push(null)
412
+ encFileWriteStream.write(mac);
413
+ encFileWriteStream.end();
414
+ (_a = originalFileStream === null || originalFileStream === void 0 ? void 0 : originalFileStream.end) === null || _a === void 0 ? void 0 : _a.call(originalFileStream);
476
415
  stream.destroy();
477
416
  logger === null || logger === void 0 ? void 0 : logger.debug('encrypted data successfully');
478
417
  return {
479
418
  mediaKey,
480
- encWriteStream,
481
- bodyPath,
419
+ originalFilePath,
420
+ encFilePath,
482
421
  mac,
483
422
  fileEncSha256,
484
423
  fileSha256,
485
- fileLength,
486
- didSaveToTmpPath
424
+ fileLength
487
425
  };
488
426
  }
489
427
  catch (error) {
490
428
  // destroy all streams with error
491
- encWriteStream.destroy();
492
- writeStream === null || writeStream === void 0 ? void 0 : writeStream.destroy();
429
+ encFileWriteStream.destroy();
430
+ (_b = originalFileStream === null || originalFileStream === void 0 ? void 0 : originalFileStream.destroy) === null || _b === void 0 ? void 0 : _b.call(originalFileStream);
493
431
  aes.destroy();
494
432
  hmac.destroy();
495
433
  sha256Plain.destroy();
496
434
  sha256Enc.destroy();
497
435
  stream.destroy();
498
- if (didSaveToTmpPath) {
499
- try {
500
- await fs_1.promises.unlink(bodyPath);
501
- }
502
- catch (err) {
503
- logger === null || logger === void 0 ? void 0 : logger.error({ err }, 'failed to save to tmp path');
436
+ try {
437
+ await fs_1.promises.unlink(encFilePath);
438
+ if (originalFilePath) {
439
+ await fs_1.promises.unlink(originalFilePath);
504
440
  }
505
441
  }
442
+ catch (err) {
443
+ logger === null || logger === void 0 ? void 0 : logger.error({ err }, 'failed deleting tmp files');
444
+ }
506
445
  throw error;
507
446
  }
508
- function onChunk(buff) {
509
- sha256Enc = sha256Enc.update(buff);
510
- hmac = hmac.update(buff);
511
- encWriteStream.push(buff);
512
- }
513
447
  };
514
448
  exports.encryptedStream = encryptedStream;
515
449
  const DEF_HOST = 'mmg.whatsapp.net';
@@ -628,20 +562,21 @@ function extensionForMediaMessage(message) {
628
562
  }
629
563
  return extension;
630
564
  }
565
+ exports.extensionForMediaMessage = extensionForMediaMessage;
631
566
  const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
632
- return async (stream, { mediaType, fileEncSha256B64, newsletter, timeoutMs }) => {
567
+ return async (filePath, { mediaType, fileEncSha256B64, newsletter, timeoutMs }) => {
633
568
  var _a, _b;
634
569
  // send a query JSON to obtain the url & auth token to upload our media
635
570
  let uploadInfo = await refreshMediaConn(false);
636
571
  let urls;
637
572
  const hosts = [...customUploadHosts, ...uploadInfo.hosts];
638
- const chunks = [];
573
+ /*const chunks: Buffer[] | Buffer = []
639
574
  if (!Buffer.isBuffer(stream)) {
640
575
  for await (const chunk of stream) {
641
- chunks.push(chunk);
576
+ chunks.push(chunk)
642
577
  }
643
- }
644
- const reqBody = Buffer.isBuffer(stream) ? stream : Buffer.concat(chunks);
578
+ }*/
579
+ //const reqBody = Buffer.isBuffer(stream) ? stream : Buffer.concat(chunks)
645
580
  fileEncSha256B64 = (0, exports.encodeBase64EncodedStringForUpload)(fileEncSha256B64);
646
581
  let media = Defaults_1.MEDIA_PATH_MAP[mediaType];
647
582
  if (newsletter) {
@@ -653,11 +588,12 @@ const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options },
653
588
  const url = `https://${hostname}${media}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
654
589
  let result;
655
590
  try {
656
- if (maxContentLengthBytes && reqBody.length > maxContentLengthBytes) {
657
- throw new boom_1.Boom(`Body too large for "${hostname}"`, { statusCode: 413 });
658
- }
659
- const body = await axios_1.default.post(url, reqBody, {
591
+ //if(maxContentLengthBytes && reqBody.length > maxContentLengthBytes) {
592
+ // throw new Boom(`Body too large for "${hostname}"`, { statusCode: 413 })
593
+ //}
594
+ const body = await axios_1.default.post(url, (0, fs_1.createReadStream)(filePath), {
660
595
  ...options,
596
+ maxRedirects: 0,
661
597
  headers: {
662
598
  ...options.headers || {},
663
599
  'Content-Type': 'application/octet-stream',
@@ -1,3 +1,6 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ /// <reference types="node" />
1
4
  import { type Transform } from 'stream';
2
5
  import { proto } from '../../WAProto';
3
6
  import { ILogger } from './logger';
@@ -9,7 +12,7 @@ import { MediaDownloadOptions } from './messages-media';
9
12
  * @returns the URL, eg. https://google.com
10
13
  */
11
14
  export declare const extractUrlFromText: (text: string) => string | undefined;
12
- export declare const generateLinkPreviewIfRequired: (text: string, getUrlInfo: MessageGenerationOptions["getUrlInfo"], logger: MessageGenerationOptions["logger"]) => Promise<import("../Types").WAUrlInfo | undefined>;
15
+ export declare const generateLinkPreviewIfRequired: (text: string, getUrlInfo: MessageGenerationOptions['getUrlInfo'], logger: MessageGenerationOptions['logger']) => Promise<import("../Types").WAUrlInfo | undefined>;
13
16
  export declare const prepareWAMessageMedia: (message: AnyMediaMessageContent, options: MediaGenerationOptions) => Promise<proto.Message>;
14
17
  export declare const prepareDisappearingMessageSettingContent: (ephemeralExpiration?: number) => proto.Message;
15
18
  /**
@@ -40,11 +43,11 @@ export declare const extractMessageContent: (content: WAMessageContent | undefin
40
43
  */
41
44
  export declare const getDevice: (id: string) => "android" | "unknown" | "web" | "ios" | "desktop";
42
45
  /** Upserts a receipt in the message */
43
- export declare const updateMessageWithReceipt: (msg: Pick<WAMessage, "userReceipt">, receipt: MessageUserReceipt) => void;
46
+ export declare const updateMessageWithReceipt: (msg: Pick<WAMessage, 'userReceipt'>, receipt: MessageUserReceipt) => void;
44
47
  /** Update the message with a new reaction */
45
- export declare const updateMessageWithReaction: (msg: Pick<WAMessage, "reactions">, reaction: proto.IReaction) => void;
48
+ export declare const updateMessageWithReaction: (msg: Pick<WAMessage, 'reactions'>, reaction: proto.IReaction) => void;
46
49
  /** Update the message with a new poll update */
47
- export declare const updateMessageWithPollUpdate: (msg: Pick<WAMessage, "pollUpdates">, update: proto.IPollUpdate) => void;
50
+ export declare const updateMessageWithPollUpdate: (msg: Pick<WAMessage, 'pollUpdates'>, update: proto.IPollUpdate) => void;
48
51
  type VoteAggregation = {
49
52
  name: string;
50
53
  voters: string[];
@@ -69,7 +72,7 @@ type DownloadMediaMessageContext = {
69
72
  /**
70
73
  * Downloads the given message. Throws an error if it's not a media message
71
74
  */
72
- export declare const downloadMediaMessage: <Type extends "buffer" | "stream">(message: WAMessage, type: Type, options: MediaDownloadOptions, ctx?: DownloadMediaMessageContext) => Promise<Type extends "buffer" ? Buffer<ArrayBufferLike> : Transform>;
75
+ export declare const downloadMediaMessage: <Type extends "stream" | "buffer">(message: WAMessage, type: Type, options: MediaDownloadOptions, ctx?: DownloadMediaMessageContext) => Promise<Type extends "buffer" ? Buffer : Transform>;
73
76
  /** Checks whether the given message is a media message; if it is returns the inner content */
74
77
  export declare const assertMediaContent: (content: proto.IMessage | null | undefined) => proto.Message.IVideoMessage | proto.Message.IImageMessage | proto.Message.IAudioMessage | proto.Message.IDocumentMessage | proto.Message.IStickerMessage;
75
78
  export {};