lordceaser-baileys 2.0.39 → 2.0.41

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 (155) hide show
  1. package/index.js +59 -412
  2. package/package.json +8 -3
  3. package/WAProto/GenerateStatics.sh +0 -4
  4. package/WAProto/WAProto.proto +0 -3344
  5. package/WAProto/index.d.ts +0 -37016
  6. package/WAProto/index.js +0 -101044
  7. package/WASignalGroup/GroupProtocol.js +0 -1697
  8. package/WASignalGroup/ciphertext_message.js +0 -16
  9. package/WASignalGroup/group_cipher.js +0 -120
  10. package/WASignalGroup/group_session_builder.js +0 -46
  11. package/WASignalGroup/index.js +0 -5
  12. package/WASignalGroup/keyhelper.js +0 -21
  13. package/WASignalGroup/protobufs.js +0 -3
  14. package/WASignalGroup/queue_job.js +0 -69
  15. package/WASignalGroup/sender_chain_key.js +0 -50
  16. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  17. package/WASignalGroup/sender_key_message.js +0 -92
  18. package/WASignalGroup/sender_key_name.js +0 -70
  19. package/WASignalGroup/sender_key_record.js +0 -56
  20. package/WASignalGroup/sender_key_state.js +0 -129
  21. package/WASignalGroup/sender_message_key.js +0 -39
  22. package/lib/Defaults/baileys-version.json +0 -3
  23. package/lib/Defaults/index.d.ts +0 -283
  24. package/lib/Defaults/index.js +0 -121
  25. package/lib/Defaults/phonenumber-mcc.json +0 -223
  26. package/lib/Signal/libsignal.d.ts +0 -3
  27. package/lib/Signal/libsignal.js +0 -152
  28. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -17
  29. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  30. package/lib/Socket/Client/index.d.ts +0 -3
  31. package/lib/Socket/Client/index.js +0 -19
  32. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  33. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  34. package/lib/Socket/Client/web-socket-client.d.ts +0 -12
  35. package/lib/Socket/Client/web-socket-client.js +0 -62
  36. package/lib/Socket/business.d.ts +0 -148
  37. package/lib/Socket/business.js +0 -260
  38. package/lib/Socket/chats.d.ts +0 -83
  39. package/lib/Socket/chats.js +0 -879
  40. package/lib/Socket/groups.d.ts +0 -123
  41. package/lib/Socket/groups.js +0 -314
  42. package/lib/Socket/index.d.ts +0 -150
  43. package/lib/Socket/index.js +0 -10
  44. package/lib/Socket/messages-recv.d.ts +0 -135
  45. package/lib/Socket/messages-recv.js +0 -867
  46. package/lib/Socket/messages-send.d.ts +0 -128
  47. package/lib/Socket/messages-send.js +0 -677
  48. package/lib/Socket/registration.d.ts +0 -242
  49. package/lib/Socket/registration.js +0 -166
  50. package/lib/Socket/socket.d.ts +0 -43
  51. package/lib/Socket/socket.js +0 -619
  52. package/lib/Store/index.d.ts +0 -3
  53. package/lib/Store/index.js +0 -10
  54. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  55. package/lib/Store/make-cache-manager-store.js +0 -83
  56. package/lib/Store/make-in-memory-store.d.ts +0 -118
  57. package/lib/Store/make-in-memory-store.js +0 -422
  58. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  59. package/lib/Store/make-ordered-dictionary.js +0 -81
  60. package/lib/Store/object-repository.d.ts +0 -10
  61. package/lib/Store/object-repository.js +0 -27
  62. package/lib/Types/Auth.d.ts +0 -110
  63. package/lib/Types/Auth.js +0 -2
  64. package/lib/Types/Call.d.ts +0 -13
  65. package/lib/Types/Call.js +0 -2
  66. package/lib/Types/Chat.d.ts +0 -107
  67. package/lib/Types/Chat.js +0 -4
  68. package/lib/Types/Contact.d.ts +0 -19
  69. package/lib/Types/Contact.js +0 -2
  70. package/lib/Types/Events.d.ts +0 -172
  71. package/lib/Types/Events.js +0 -2
  72. package/lib/Types/GroupMetadata.d.ts +0 -56
  73. package/lib/Types/GroupMetadata.js +0 -2
  74. package/lib/Types/Label.d.ts +0 -46
  75. package/lib/Types/Label.js +0 -27
  76. package/lib/Types/LabelAssociation.d.ts +0 -29
  77. package/lib/Types/LabelAssociation.js +0 -9
  78. package/lib/Types/Message.d.ts +0 -268
  79. package/lib/Types/Message.js +0 -9
  80. package/lib/Types/Product.d.ts +0 -78
  81. package/lib/Types/Product.js +0 -2
  82. package/lib/Types/Signal.d.ts +0 -57
  83. package/lib/Types/Signal.js +0 -2
  84. package/lib/Types/Socket.d.ts +0 -116
  85. package/lib/Types/Socket.js +0 -2
  86. package/lib/Types/State.d.ts +0 -27
  87. package/lib/Types/State.js +0 -2
  88. package/lib/Types/index.d.ts +0 -63
  89. package/lib/Types/index.js +0 -41
  90. package/lib/Utils/auth-utils.d.ts +0 -18
  91. package/lib/Utils/auth-utils.js +0 -206
  92. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  93. package/lib/Utils/baileys-event-stream.js +0 -63
  94. package/lib/Utils/business.d.ts +0 -22
  95. package/lib/Utils/business.js +0 -234
  96. package/lib/Utils/chat-utils.d.ts +0 -71
  97. package/lib/Utils/chat-utils.js +0 -740
  98. package/lib/Utils/crypto.d.ts +0 -41
  99. package/lib/Utils/crypto.js +0 -153
  100. package/lib/Utils/decode-wa-message.d.ts +0 -20
  101. package/lib/Utils/decode-wa-message.js +0 -188
  102. package/lib/Utils/event-buffer.d.ts +0 -35
  103. package/lib/Utils/event-buffer.js +0 -520
  104. package/lib/Utils/generics.d.ts +0 -89
  105. package/lib/Utils/generics.js +0 -394
  106. package/lib/Utils/history.d.ts +0 -19
  107. package/lib/Utils/history.js +0 -94
  108. package/lib/Utils/index.d.ts +0 -17
  109. package/lib/Utils/index.js +0 -33
  110. package/lib/Utils/link-preview.d.ts +0 -21
  111. package/lib/Utils/link-preview.js +0 -93
  112. package/lib/Utils/logger.d.ts +0 -4
  113. package/lib/Utils/logger.js +0 -7
  114. package/lib/Utils/lt-hash.d.ts +0 -12
  115. package/lib/Utils/lt-hash.js +0 -51
  116. package/lib/Utils/make-mutex.d.ts +0 -7
  117. package/lib/Utils/make-mutex.js +0 -43
  118. package/lib/Utils/messages-media.d.ts +0 -107
  119. package/lib/Utils/messages-media.js +0 -674
  120. package/lib/Utils/messages.d.ts +0 -77
  121. package/lib/Utils/messages.js +0 -758
  122. package/lib/Utils/noise-handler.d.ts +0 -21
  123. package/lib/Utils/noise-handler.js +0 -155
  124. package/lib/Utils/process-message.d.ts +0 -42
  125. package/lib/Utils/process-message.js +0 -354
  126. package/lib/Utils/signal.d.ts +0 -32
  127. package/lib/Utils/signal.js +0 -161
  128. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -12
  129. package/lib/Utils/use-multi-file-auth-state.js +0 -93
  130. package/lib/Utils/validate-connection.d.ts +0 -11
  131. package/lib/Utils/validate-connection.js +0 -205
  132. package/lib/WABinary/constants.d.ts +0 -27
  133. package/lib/WABinary/constants.js +0 -40
  134. package/lib/WABinary/decode.d.ts +0 -7
  135. package/lib/WABinary/decode.js +0 -254
  136. package/lib/WABinary/encode.d.ts +0 -3
  137. package/lib/WABinary/encode.js +0 -232
  138. package/lib/WABinary/generic-utils.d.ts +0 -15
  139. package/lib/WABinary/generic-utils.js +0 -110
  140. package/lib/WABinary/index.d.ts +0 -5
  141. package/lib/WABinary/index.js +0 -21
  142. package/lib/WABinary/jid-utils.d.ts +0 -31
  143. package/lib/WABinary/jid-utils.js +0 -62
  144. package/lib/WABinary/types.d.ts +0 -18
  145. package/lib/WABinary/types.js +0 -2
  146. package/lib/WAM/BinaryInfo.d.ts +0 -17
  147. package/lib/WAM/BinaryInfo.js +0 -13
  148. package/lib/WAM/constants.d.ts +0 -38
  149. package/lib/WAM/constants.js +0 -15350
  150. package/lib/WAM/encode.d.ts +0 -3
  151. package/lib/WAM/encode.js +0 -155
  152. package/lib/WAM/index.d.ts +0 -3
  153. package/lib/WAM/index.js +0 -19
  154. package/lib/index.d.ts +0 -11
  155. package/lib/index.js +0 -30
@@ -1,674 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
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
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.getStatusCodeForMediaRetry = exports.decryptMediaRetryData = exports.decodeMediaRetryNode = exports.encryptMediaRetryRequest = exports.getWAUploadToServer = exports.extensionForMediaMessage = exports.downloadEncryptedContent = exports.downloadContentFromMessage = exports.getUrlFromDirectPath = exports.encryptedStream = 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;
30
- const boom_1 = require("@hapi/boom");
31
- const axios_1 = __importDefault(require("axios"));
32
- const child_process_1 = require("child_process");
33
- const Crypto = __importStar(require("crypto"));
34
- const events_1 = require("events");
35
- const fs_1 = require("fs");
36
- const os_1 = require("os");
37
- const path_1 = require("path");
38
- const stream_1 = require("stream");
39
- const WAProto_1 = require("../../WAProto");
40
- const Defaults_1 = require("../Defaults");
41
- const WABinary_1 = require("../WABinary");
42
- const crypto_1 = require("./crypto");
43
- const generics_1 = require("./generics");
44
- const getTmpFilesDirectory = () => (0, os_1.tmpdir)();
45
- const getImageProcessingLibrary = async () => {
46
- const [_jimp, sharp] = await Promise.all([
47
- (async () => {
48
- const jimp = await (import('jimp')
49
- .catch(() => { }));
50
- return jimp;
51
- })(),
52
- (async () => {
53
- const sharp = await (import('sharp')
54
- .catch(() => { }));
55
- return sharp;
56
- })()
57
- ]);
58
- if (sharp) {
59
- return { sharp };
60
- }
61
- const jimp = (_jimp === null || _jimp === void 0 ? void 0 : _jimp.default) || _jimp;
62
- if (jimp) {
63
- return { jimp };
64
- }
65
- throw new boom_1.Boom('No image processing library available');
66
- };
67
- const hkdfInfoKey = (type) => {
68
- const hkdfInfo = Defaults_1.MEDIA_HKDF_KEY_MAPPING[type];
69
- return `WhatsApp ${hkdfInfo} Keys`;
70
- };
71
- exports.hkdfInfoKey = hkdfInfoKey;
72
- /** generates all the keys required to encrypt/decrypt & sign a media message */
73
- function getMediaKeys(buffer, mediaType) {
74
- if (!buffer) {
75
- throw new boom_1.Boom('Cannot derive from empty media key');
76
- }
77
- if (typeof buffer === 'string') {
78
- buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
79
- }
80
- // expand using HKDF to 112 bytes, also pass in the relevant app info
81
- const expandedMediaKey = (0, crypto_1.hkdf)(buffer, 112, { info: (0, exports.hkdfInfoKey)(mediaType) });
82
- return {
83
- iv: expandedMediaKey.slice(0, 16),
84
- cipherKey: expandedMediaKey.slice(16, 48),
85
- macKey: expandedMediaKey.slice(48, 80),
86
- };
87
- }
88
- exports.getMediaKeys = getMediaKeys;
89
- /** Extracts video thumb using FFMPEG */
90
- const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
91
- const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`;
92
- (0, child_process_1.exec)(cmd, (err) => {
93
- if (err) {
94
- reject(err);
95
- }
96
- else {
97
- resolve();
98
- }
99
- });
100
- });
101
- const extractImageThumb = async (bufferOrFilePath, width = 32) => {
102
- var _a, _b;
103
- if (bufferOrFilePath instanceof stream_1.Readable) {
104
- bufferOrFilePath = await (0, exports.toBuffer)(bufferOrFilePath);
105
- }
106
- const lib = await getImageProcessingLibrary();
107
- if ('sharp' in lib && typeof ((_a = lib.sharp) === null || _a === void 0 ? void 0 : _a.default) === 'function') {
108
- const img = lib.sharp.default(bufferOrFilePath);
109
- const dimensions = await img.metadata();
110
- const buffer = await img
111
- .resize(width)
112
- .jpeg({ quality: 50 })
113
- .toBuffer();
114
- return {
115
- buffer,
116
- original: {
117
- width: dimensions.width,
118
- height: dimensions.height,
119
- },
120
- };
121
- }
122
- else if ('jimp' in lib && typeof ((_b = lib.jimp) === null || _b === void 0 ? void 0 : _b.read) === 'function') {
123
- const { read, MIME_JPEG, RESIZE_BILINEAR, AUTO } = lib.jimp;
124
- const jimp = await read(bufferOrFilePath);
125
- const dimensions = {
126
- width: jimp.getWidth(),
127
- height: jimp.getHeight()
128
- };
129
- const buffer = await jimp
130
- .quality(50)
131
- .resize(width, AUTO, RESIZE_BILINEAR)
132
- .getBufferAsync(MIME_JPEG);
133
- return {
134
- buffer,
135
- original: dimensions
136
- };
137
- }
138
- else {
139
- throw new boom_1.Boom('No image processing library available');
140
- }
141
- };
142
- exports.extractImageThumb = extractImageThumb;
143
- const encodeBase64EncodedStringForUpload = (b64) => (encodeURIComponent(b64
144
- .replace(/\+/g, '-')
145
- .replace(/\//g, '_')
146
- .replace(/\=+$/, '')));
147
- exports.encodeBase64EncodedStringForUpload = encodeBase64EncodedStringForUpload;
148
- const generateProfilePicture = async (mediaUpload) => {
149
- var _a, _b;
150
- let bufferOrFilePath;
151
- if (Buffer.isBuffer(mediaUpload)) {
152
- bufferOrFilePath = mediaUpload;
153
- }
154
- else if ('url' in mediaUpload) {
155
- bufferOrFilePath = mediaUpload.url.toString();
156
- }
157
- else {
158
- bufferOrFilePath = await (0, exports.toBuffer)(mediaUpload.stream);
159
- }
160
- const lib = await getImageProcessingLibrary();
161
- let img;
162
- if ('sharp' in lib && typeof ((_a = lib.sharp) === null || _a === void 0 ? void 0 : _a.default) === 'function') {
163
- img = lib.sharp.default(bufferOrFilePath)
164
- .resize(640, 640)
165
- .jpeg({
166
- quality: 50,
167
- })
168
- .toBuffer();
169
- }
170
- else if ('jimp' in lib && typeof ((_b = lib.jimp) === null || _b === void 0 ? void 0 : _b.read) === 'function') {
171
- const { read, MIME_JPEG, RESIZE_BILINEAR } = lib.jimp;
172
- const jimp = await read(bufferOrFilePath);
173
- const min = Math.min(jimp.getWidth(), jimp.getHeight());
174
- const cropped = jimp.crop(0, 0, min, min);
175
- img = cropped
176
- .quality(50)
177
- .resize(640, 640, RESIZE_BILINEAR)
178
- .getBufferAsync(MIME_JPEG);
179
- }
180
- else {
181
- throw new boom_1.Boom('No image processing library available');
182
- }
183
- return {
184
- img: await img,
185
- };
186
- };
187
- exports.generateProfilePicture = generateProfilePicture;
188
- /** gets the SHA256 of the given media message */
189
- const mediaMessageSHA256B64 = (message) => {
190
- const media = Object.values(message)[0];
191
- return (media === null || media === void 0 ? void 0 : media.fileSha256) && Buffer.from(media.fileSha256).toString('base64');
192
- };
193
- exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
194
- async function getAudioDuration(buffer) {
195
- const musicMetadata = await import('music-metadata');
196
- let metadata;
197
- if (Buffer.isBuffer(buffer)) {
198
- metadata = await musicMetadata.parseBuffer(buffer, undefined, { duration: true });
199
- }
200
- else if (typeof buffer === 'string') {
201
- const rStream = (0, fs_1.createReadStream)(buffer);
202
- try {
203
- metadata = await musicMetadata.parseStream(rStream, undefined, { duration: true });
204
- }
205
- finally {
206
- rStream.destroy();
207
- }
208
- }
209
- else {
210
- metadata = await musicMetadata.parseStream(buffer, undefined, { duration: true });
211
- }
212
- return metadata.format.duration;
213
- }
214
- exports.getAudioDuration = getAudioDuration;
215
- /**
216
- referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
217
- */
218
- async function getAudioWaveform(buffer, logger) {
219
- try {
220
- const audioDecode = (buffer) => import('audio-decode').then(({ default: audioDecode }) => audioDecode(buffer));
221
- let audioData;
222
- if (Buffer.isBuffer(buffer)) {
223
- audioData = buffer;
224
- }
225
- else if (typeof buffer === 'string') {
226
- const rStream = (0, fs_1.createReadStream)(buffer);
227
- audioData = await (0, exports.toBuffer)(rStream);
228
- }
229
- else {
230
- audioData = await (0, exports.toBuffer)(buffer);
231
- }
232
- const audioBuffer = await audioDecode(audioData);
233
- const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
234
- const samples = 64; // Number of samples we want to have in our final data set
235
- const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
236
- const filteredData = [];
237
- for (let i = 0; i < samples; i++) {
238
- const blockStart = blockSize * i; // the location of the first sample in the block
239
- let sum = 0;
240
- for (let j = 0; j < blockSize; j++) {
241
- sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
242
- }
243
- filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
244
- }
245
- // This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
246
- const multiplier = Math.pow(Math.max(...filteredData), -1);
247
- const normalizedData = filteredData.map((n) => n * multiplier);
248
- // Generate waveform like WhatsApp
249
- const waveform = new Uint8Array(normalizedData.map((n) => Math.floor(100 * n)));
250
- return waveform;
251
- }
252
- catch (e) {
253
- logger === null || logger === void 0 ? void 0 : logger.debug('Failed to generate waveform: ' + e);
254
- }
255
- }
256
- exports.getAudioWaveform = getAudioWaveform;
257
- const toReadable = (buffer) => {
258
- const readable = new stream_1.Readable({ read: () => { } });
259
- readable.push(buffer);
260
- readable.push(null);
261
- return readable;
262
- };
263
- exports.toReadable = toReadable;
264
- const toBuffer = async (stream) => {
265
- const chunks = [];
266
- for await (const chunk of stream) {
267
- chunks.push(chunk);
268
- }
269
- stream.destroy();
270
- return Buffer.concat(chunks);
271
- };
272
- exports.toBuffer = toBuffer;
273
- const getStream = async (item, opts) => {
274
- if (Buffer.isBuffer(item)) {
275
- return { stream: (0, exports.toReadable)(item), type: 'buffer' };
276
- }
277
- if ('stream' in item) {
278
- return { stream: item.stream, type: 'readable' };
279
- }
280
- if (item.url.toString().startsWith('http://') || item.url.toString().startsWith('https://')) {
281
- return { stream: await (0, exports.getHttpStream)(item.url, opts), type: 'remote' };
282
- }
283
- return { stream: (0, fs_1.createReadStream)(item.url), type: 'file' };
284
- };
285
- exports.getStream = getStream;
286
- /** generates a thumbnail for a given media, if required */
287
- async function generateThumbnail(file, mediaType, options) {
288
- var _a;
289
- let thumbnail;
290
- let originalImageDimensions;
291
- if (mediaType === 'image') {
292
- const { buffer, original } = await (0, exports.extractImageThumb)(file);
293
- thumbnail = buffer.toString('base64');
294
- if (original.width && original.height) {
295
- originalImageDimensions = {
296
- width: original.width,
297
- height: original.height,
298
- };
299
- }
300
- }
301
- else if (mediaType === 'video') {
302
- const imgFilename = (0, path_1.join)(getTmpFilesDirectory(), (0, generics_1.generateMessageID)() + '.jpg');
303
- try {
304
- await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 });
305
- const buff = await fs_1.promises.readFile(imgFilename);
306
- thumbnail = buff.toString('base64');
307
- await fs_1.promises.unlink(imgFilename);
308
- }
309
- catch (err) {
310
- (_a = options.logger) === null || _a === void 0 ? void 0 : _a.debug('could not generate video thumb: ' + err);
311
- }
312
- }
313
- return {
314
- thumbnail,
315
- originalImageDimensions
316
- };
317
- }
318
- exports.generateThumbnail = generateThumbnail;
319
- const getHttpStream = async (url, options = {}) => {
320
- const fetched = await axios_1.default.get(url.toString(), { ...options, responseType: 'stream' });
321
- return fetched.data;
322
- };
323
- exports.getHttpStream = getHttpStream;
324
- const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
325
- const { stream, type } = await (0, exports.getStream)(media, opts);
326
- logger === null || logger === void 0 ? void 0 : logger.debug('fetched media stream');
327
- const mediaKey = Crypto.randomBytes(32);
328
- const { cipherKey, iv, macKey } = getMediaKeys(mediaKey, mediaType);
329
- const encWriteStream = new stream_1.Readable({ read: () => { } });
330
- let bodyPath;
331
- let writeStream;
332
- let didSaveToTmpPath = false;
333
- if (type === 'file') {
334
- bodyPath = media.url;
335
- }
336
- else if (saveOriginalFileIfRequired) {
337
- bodyPath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageID)());
338
- writeStream = (0, fs_1.createWriteStream)(bodyPath);
339
- didSaveToTmpPath = true;
340
- }
341
- let fileLength = 0;
342
- const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
343
- let hmac = Crypto.createHmac('sha256', macKey).update(iv);
344
- let sha256Plain = Crypto.createHash('sha256');
345
- let sha256Enc = Crypto.createHash('sha256');
346
- try {
347
- for await (const data of stream) {
348
- fileLength += data.length;
349
- if (type === 'remote'
350
- && (opts === null || opts === void 0 ? void 0 : opts.maxContentLength)
351
- && fileLength + data.length > opts.maxContentLength) {
352
- throw new boom_1.Boom(`content length exceeded when encrypting "${type}"`, {
353
- data: { media, type }
354
- });
355
- }
356
- sha256Plain = sha256Plain.update(data);
357
- if (writeStream) {
358
- if (!writeStream.write(data)) {
359
- await (0, events_1.once)(writeStream, 'drain');
360
- }
361
- }
362
- onChunk(aes.update(data));
363
- }
364
- onChunk(aes.final());
365
- const mac = hmac.digest().slice(0, 10);
366
- sha256Enc = sha256Enc.update(mac);
367
- const fileSha256 = sha256Plain.digest();
368
- const fileEncSha256 = sha256Enc.digest();
369
- encWriteStream.push(mac);
370
- encWriteStream.push(null);
371
- writeStream === null || writeStream === void 0 ? void 0 : writeStream.end();
372
- stream.destroy();
373
- logger === null || logger === void 0 ? void 0 : logger.debug('encrypted data successfully');
374
- return {
375
- mediaKey,
376
- encWriteStream,
377
- bodyPath,
378
- mac,
379
- fileEncSha256,
380
- fileSha256,
381
- fileLength,
382
- didSaveToTmpPath
383
- };
384
- }
385
- catch (error) {
386
- // destroy all streams with error
387
- encWriteStream.destroy();
388
- writeStream === null || writeStream === void 0 ? void 0 : writeStream.destroy();
389
- aes.destroy();
390
- hmac.destroy();
391
- sha256Plain.destroy();
392
- sha256Enc.destroy();
393
- stream.destroy();
394
- if (didSaveToTmpPath) {
395
- try {
396
- await fs_1.promises.unlink(bodyPath);
397
- }
398
- catch (err) {
399
- logger === null || logger === void 0 ? void 0 : logger.error({ err }, 'failed to save to tmp path');
400
- }
401
- }
402
- throw error;
403
- }
404
- function onChunk(buff) {
405
- sha256Enc = sha256Enc.update(buff);
406
- hmac = hmac.update(buff);
407
- encWriteStream.push(buff);
408
- }
409
- };
410
- exports.encryptedStream = encryptedStream;
411
- const DEF_HOST = 'mmg.whatsapp.net';
412
- const AES_CHUNK_SIZE = 16;
413
- const toSmallestChunkSize = (num) => {
414
- return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
415
- };
416
- const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`;
417
- exports.getUrlFromDirectPath = getUrlFromDirectPath;
418
- const downloadContentFromMessage = ({ mediaKey, directPath, url }, type, opts = {}) => {
419
- const downloadUrl = url || (0, exports.getUrlFromDirectPath)(directPath);
420
- const keys = getMediaKeys(mediaKey, type);
421
- return (0, exports.downloadEncryptedContent)(downloadUrl, keys, opts);
422
- };
423
- exports.downloadContentFromMessage = downloadContentFromMessage;
424
- /**
425
- * Decrypts and downloads an AES256-CBC encrypted file given the keys.
426
- * Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
427
- * */
428
- const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
429
- let bytesFetched = 0;
430
- let startChunk = 0;
431
- let firstBlockIsIV = false;
432
- // if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
433
- if (startByte) {
434
- const chunk = toSmallestChunkSize(startByte || 0);
435
- if (chunk) {
436
- startChunk = chunk - AES_CHUNK_SIZE;
437
- bytesFetched = chunk;
438
- firstBlockIsIV = true;
439
- }
440
- }
441
- const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
442
- const headers = {
443
- ...(options === null || options === void 0 ? void 0 : options.headers) || {},
444
- Origin: Defaults_1.DEFAULT_ORIGIN,
445
- };
446
- if (startChunk || endChunk) {
447
- headers.Range = `bytes=${startChunk}-`;
448
- if (endChunk) {
449
- headers.Range += endChunk;
450
- }
451
- }
452
- // download the message
453
- const fetched = await (0, exports.getHttpStream)(downloadUrl, {
454
- ...options || {},
455
- headers,
456
- maxBodyLength: Infinity,
457
- maxContentLength: Infinity,
458
- });
459
- let remainingBytes = Buffer.from([]);
460
- let aes;
461
- const pushBytes = (bytes, push) => {
462
- if (startByte || endByte) {
463
- const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
464
- const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
465
- push(bytes.slice(start, end));
466
- bytesFetched += bytes.length;
467
- }
468
- else {
469
- push(bytes);
470
- }
471
- };
472
- const output = new stream_1.Transform({
473
- transform(chunk, _, callback) {
474
- let data = Buffer.concat([remainingBytes, chunk]);
475
- const decryptLength = toSmallestChunkSize(data.length);
476
- remainingBytes = data.slice(decryptLength);
477
- data = data.slice(0, decryptLength);
478
- if (!aes) {
479
- let ivValue = iv;
480
- if (firstBlockIsIV) {
481
- ivValue = data.slice(0, AES_CHUNK_SIZE);
482
- data = data.slice(AES_CHUNK_SIZE);
483
- }
484
- aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
485
- // if an end byte that is not EOF is specified
486
- // stop auto padding (PKCS7) -- otherwise throws an error for decryption
487
- if (endByte) {
488
- aes.setAutoPadding(false);
489
- }
490
- }
491
- try {
492
- pushBytes(aes.update(data), b => this.push(b));
493
- callback();
494
- }
495
- catch (error) {
496
- callback(error);
497
- }
498
- },
499
- final(callback) {
500
- try {
501
- pushBytes(aes.final(), b => this.push(b));
502
- callback();
503
- }
504
- catch (error) {
505
- callback(error);
506
- }
507
- },
508
- });
509
- return fetched.pipe(output, { end: true });
510
- };
511
- exports.downloadEncryptedContent = downloadEncryptedContent;
512
- function extensionForMediaMessage(message) {
513
- const getExtension = (mimetype) => mimetype.split(';')[0].split('/')[1];
514
- const type = Object.keys(message)[0];
515
- let extension;
516
- if (type === 'locationMessage' ||
517
- type === 'liveLocationMessage' ||
518
- type === 'productMessage') {
519
- extension = '.jpeg';
520
- }
521
- else {
522
- const messageContent = message[type];
523
- extension = getExtension(messageContent.mimetype);
524
- }
525
- return extension;
526
- }
527
- exports.extensionForMediaMessage = extensionForMediaMessage;
528
- const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
529
- return async (stream, { mediaType, fileEncSha256B64, timeoutMs }) => {
530
- var _a, _b;
531
- // send a query JSON to obtain the url & auth token to upload our media
532
- let uploadInfo = await refreshMediaConn(false);
533
- let urls;
534
- const hosts = [...customUploadHosts, ...uploadInfo.hosts];
535
- fileEncSha256B64 = (0, exports.encodeBase64EncodedStringForUpload)(fileEncSha256B64);
536
- for (const { hostname } of hosts) {
537
- logger.debug(`uploading to "${hostname}"`);
538
- const auth = encodeURIComponent(uploadInfo.auth); // the auth token
539
- const url = `https://${hostname}${Defaults_1.MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
540
- let result;
541
- try {
542
- const body = await axios_1.default.post(url, stream, {
543
- ...options,
544
- headers: {
545
- ...options.headers || {},
546
- 'Content-Type': 'application/octet-stream',
547
- 'Origin': Defaults_1.DEFAULT_ORIGIN
548
- },
549
- httpsAgent: fetchAgent,
550
- timeout: timeoutMs,
551
- responseType: 'json',
552
- maxBodyLength: Infinity,
553
- maxContentLength: Infinity,
554
- });
555
- result = body.data;
556
- if ((result === null || result === void 0 ? void 0 : result.url) || (result === null || result === void 0 ? void 0 : result.directPath)) {
557
- urls = {
558
- mediaUrl: result.url,
559
- directPath: result.direct_path
560
- };
561
- break;
562
- }
563
- else {
564
- uploadInfo = await refreshMediaConn(true);
565
- throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
566
- }
567
- }
568
- catch (error) {
569
- if (axios_1.default.isAxiosError(error)) {
570
- result = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data;
571
- }
572
- const isLast = hostname === ((_b = hosts[uploadInfo.hosts.length - 1]) === null || _b === void 0 ? void 0 : _b.hostname);
573
- logger.warn({ trace: error.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
574
- }
575
- }
576
- if (!urls) {
577
- throw new boom_1.Boom('Media upload failed on all hosts', { statusCode: 500 });
578
- }
579
- return urls;
580
- };
581
- };
582
- exports.getWAUploadToServer = getWAUploadToServer;
583
- const getMediaRetryKey = (mediaKey) => {
584
- return (0, crypto_1.hkdf)(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
585
- };
586
- /**
587
- * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
588
- */
589
- const encryptMediaRetryRequest = (key, mediaKey, meId) => {
590
- const recp = { stanzaId: key.id };
591
- const recpBuffer = WAProto_1.proto.ServerErrorReceipt.encode(recp).finish();
592
- const iv = Crypto.randomBytes(12);
593
- const retryKey = getMediaRetryKey(mediaKey);
594
- const ciphertext = (0, crypto_1.aesEncryptGCM)(recpBuffer, retryKey, iv, Buffer.from(key.id));
595
- const req = {
596
- tag: 'receipt',
597
- attrs: {
598
- id: key.id,
599
- to: (0, WABinary_1.jidNormalizedUser)(meId),
600
- type: 'server-error'
601
- },
602
- content: [
603
- // this encrypt node is actually pretty useless
604
- // the media is returned even without this node
605
- // keeping it here to maintain parity with WA Web
606
- {
607
- tag: 'encrypt',
608
- attrs: {},
609
- content: [
610
- { tag: 'enc_p', attrs: {}, content: ciphertext },
611
- { tag: 'enc_iv', attrs: {}, content: iv }
612
- ]
613
- },
614
- {
615
- tag: 'rmr',
616
- attrs: {
617
- jid: key.remoteJid,
618
- 'from_me': (!!key.fromMe).toString(),
619
- // @ts-ignore
620
- participant: key.participant || undefined
621
- }
622
- }
623
- ]
624
- };
625
- return req;
626
- };
627
- exports.encryptMediaRetryRequest = encryptMediaRetryRequest;
628
- const decodeMediaRetryNode = (node) => {
629
- const rmrNode = (0, WABinary_1.getBinaryNodeChild)(node, 'rmr');
630
- const event = {
631
- key: {
632
- id: node.attrs.id,
633
- remoteJid: rmrNode.attrs.jid,
634
- fromMe: rmrNode.attrs.from_me === 'true',
635
- participant: rmrNode.attrs.participant
636
- }
637
- };
638
- const errorNode = (0, WABinary_1.getBinaryNodeChild)(node, 'error');
639
- if (errorNode) {
640
- const errorCode = +errorNode.attrs.code;
641
- event.error = new boom_1.Boom(`Failed to re-upload media (${errorCode})`, { data: errorNode.attrs, statusCode: (0, exports.getStatusCodeForMediaRetry)(errorCode) });
642
- }
643
- else {
644
- const encryptedInfoNode = (0, WABinary_1.getBinaryNodeChild)(node, 'encrypt');
645
- const ciphertext = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_p');
646
- const iv = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_iv');
647
- if (ciphertext && iv) {
648
- event.media = { ciphertext, iv };
649
- }
650
- else {
651
- event.error = new boom_1.Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
652
- }
653
- }
654
- return event;
655
- };
656
- exports.decodeMediaRetryNode = decodeMediaRetryNode;
657
- const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
658
- const retryKey = getMediaRetryKey(mediaKey);
659
- const plaintext = (0, crypto_1.aesDecryptGCM)(ciphertext, retryKey, iv, Buffer.from(msgId));
660
- return WAProto_1.proto.MediaRetryNotification.decode(plaintext);
661
- };
662
- exports.decryptMediaRetryData = decryptMediaRetryData;
663
- const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
664
- exports.getStatusCodeForMediaRetry = getStatusCodeForMediaRetry;
665
- const MEDIA_RETRY_STATUS_MAP = {
666
- [WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
667
- [WAProto_1.proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
668
- [WAProto_1.proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
669
- [WAProto_1.proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418,
670
- };
671
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
672
- function __importStar(arg0) {
673
- throw new Error('Function not implemented.');
674
- }