@mihiranga_mihiranga/mezuka-baileys 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +651 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +4775 -0
  5. package/WAProto/index.js +169661 -0
  6. package/WAProto//342/235/244/357/270/217 +1 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/baileys-version.json +3 -0
  9. package/lib/Defaults/index.js +112 -0
  10. package/lib/Defaults/phonenumber-mcc.json +223 -0
  11. package/lib/Defaults//360/237/222/226 +1 -0
  12. package/lib/Signal/Group/ciphertext-message.js +15 -0
  13. package/lib/Signal/Group/group-session-builder.js +64 -0
  14. package/lib/Signal/Group/group_cipher.js +96 -0
  15. package/lib/Signal/Group/index.js +57 -0
  16. package/lib/Signal/Group/keyhelper.js +55 -0
  17. package/lib/Signal/Group/queue-job.js +57 -0
  18. package/lib/Signal/Group/sender-chain-key.js +34 -0
  19. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  20. package/lib/Signal/Group/sender-key-message.js +69 -0
  21. package/lib/Signal/Group/sender-key-name.js +51 -0
  22. package/lib/Signal/Group/sender-key-record.js +53 -0
  23. package/lib/Signal/Group/sender-key-state.js +99 -0
  24. package/lib/Signal/Group/sender-message-key.js +29 -0
  25. package/lib/Signal/Group//342/235/244/357/270/217 +1 -0
  26. package/lib/Signal/libsignal.js +174 -0
  27. package/lib/Signal//360/237/222/226 +1 -0
  28. package/lib/Socket/Client/index.js +18 -0
  29. package/lib/Socket/Client/types.js +13 -0
  30. package/lib/Socket/Client/websocket.js +72 -0
  31. package/lib/Socket/Client//342/235/244/357/270/217 +1 -0
  32. package/lib/Socket/business.js +260 -0
  33. package/lib/Socket/chats.js +890 -0
  34. package/lib/Socket/groups.js +332 -0
  35. package/lib/Socket/index.js +10 -0
  36. package/lib/Socket/messages-recv.js +1142 -0
  37. package/lib/Socket/messages-send.js +1068 -0
  38. package/lib/Socket/newsletter.js +250 -0
  39. package/lib/Socket/socket.js +654 -0
  40. package/lib/Socket/usync.js +70 -0
  41. package/lib/Socket//360/237/222/236 +1 -0
  42. package/lib/Store/index.js +8 -0
  43. package/lib/Store/make-in-memory-store.js +429 -0
  44. package/lib/Store/make-ordered-dictionary.js +81 -0
  45. package/lib/Store/object-repository.js +27 -0
  46. package/lib/Store//342/235/244/357/270/217 +1 -0
  47. package/lib/Types/Auth.js +2 -0
  48. package/lib/Types/Call.js +2 -0
  49. package/lib/Types/Chat.js +4 -0
  50. package/lib/Types/Contact.js +2 -0
  51. package/lib/Types/Events.js +2 -0
  52. package/lib/Types/GroupMetadata.js +2 -0
  53. package/lib/Types/Label.js +27 -0
  54. package/lib/Types/LabelAssociation.js +9 -0
  55. package/lib/Types/Message.js +7 -0
  56. package/lib/Types/Newsletter.js +18 -0
  57. package/lib/Types/Product.js +2 -0
  58. package/lib/Types/Signal.js +2 -0
  59. package/lib/Types/Socket.js +2 -0
  60. package/lib/Types/State.js +2 -0
  61. package/lib/Types/USync.js +2 -0
  62. package/lib/Types/index.js +42 -0
  63. package/lib/Types//360/237/222/236 +1 -0
  64. package/lib/Utils/auth-utils.js +199 -0
  65. package/lib/Utils/baileys-event-stream.js +63 -0
  66. package/lib/Utils/browser-utils.js +35 -0
  67. package/lib/Utils/business.js +234 -0
  68. package/lib/Utils/chat-utils.js +730 -0
  69. package/lib/Utils/crypto.js +193 -0
  70. package/lib/Utils/decode-wa-message.js +207 -0
  71. package/lib/Utils/event-buffer.js +518 -0
  72. package/lib/Utils/generics.js +473 -0
  73. package/lib/Utils/history.js +95 -0
  74. package/lib/Utils/index.js +33 -0
  75. package/lib/Utils/link-preview.js +126 -0
  76. package/lib/Utils/logger.js +7 -0
  77. package/lib/Utils/lt-hash.js +51 -0
  78. package/lib/Utils/make-mutex.js +43 -0
  79. package/lib/Utils/messages-media.js +880 -0
  80. package/lib/Utils/messages.js +1154 -0
  81. package/lib/Utils/noise-handler.js +150 -0
  82. package/lib/Utils/process-message.js +372 -0
  83. package/lib/Utils/signal.js +153 -0
  84. package/lib/Utils/use-multi-file-auth-state.js +125 -0
  85. package/lib/Utils/validate-connection.js +199 -0
  86. package/lib/Utils//342/235/244/357/270/217 +1 -0
  87. package/lib/WABinary/constants.js +1303 -0
  88. package/lib/WABinary/decode.js +265 -0
  89. package/lib/WABinary/encode.js +250 -0
  90. package/lib/WABinary/generic-utils.js +130 -0
  91. package/lib/WABinary/index.js +21 -0
  92. package/lib/WABinary/jid-utils.js +83 -0
  93. package/lib/WABinary/types.js +2 -0
  94. package/lib/WABinary//360/237/222/226 +1 -0
  95. package/lib/WAM/BinaryInfo.js +13 -0
  96. package/lib/WAM/constants.js +15350 -0
  97. package/lib/WAM/encode.js +155 -0
  98. package/lib/WAM/index.js +19 -0
  99. package/lib/WAM//360/237/222/226 +1 -0
  100. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  101. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  102. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  103. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  104. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  105. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  106. package/lib/WAUSync/Protocols/index.js +20 -0
  107. package/lib/WAUSync/Protocols//342/235/244/357/270/217 +1 -0
  108. package/lib/WAUSync/USyncQuery.js +89 -0
  109. package/lib/WAUSync/USyncUser.js +26 -0
  110. package/lib/WAUSync/index.js +19 -0
  111. package/lib/WAUSync//360/237/222/226 +1 -0
  112. package/lib/index.js +45 -0
  113. package/lib//360/237/222/226 +1 -0
  114. package/package.json +121 -0
@@ -0,0 +1,880 @@
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 () {
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
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ 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.generateProfilePicture = exports.encodeBase64EncodedStringForUpload = exports.extractImageThumb = exports.extractVideoThumb = exports.hkdfInfoKey = void 0;
40
+ exports.getMediaKeys = getMediaKeys;
41
+ exports.uploadFile = uploadFile;
42
+ exports.vid2jpg = vid2jpg;
43
+ exports.getAudioDuration = getAudioDuration;
44
+ exports.getAudioWaveform = getAudioWaveform;
45
+ exports.generateThumbnail = generateThumbnail;
46
+ exports.extensionForMediaMessage = extensionForMediaMessage;
47
+ const boom_1 = require("@hapi/boom");
48
+ const axios_1 = __importDefault(require("axios"));
49
+ const form_data_1 = __importDefault(require("form-data"));
50
+ const cheerio = __importStar(require("cheerio"));
51
+ const Crypto = __importStar(require("crypto"));
52
+ const events_1 = require("events");
53
+ const fs_1 = require("fs");
54
+ const os_1 = require("os");
55
+ const path_1 = require("path");
56
+ const jimp_1 = __importDefault(require("jimp"));
57
+ const stream_1 = require("stream");
58
+ const WAProto_1 = require("../../WAProto");
59
+ const Defaults_1 = require("../Defaults");
60
+ const WABinary_1 = require("../WABinary");
61
+ const crypto_1 = require("./crypto");
62
+ const generics_1 = require("./generics");
63
+ const getTmpFilesDirectory = () => (0, os_1.tmpdir)();
64
+ const getImageProcessingLibrary = async () => {
65
+ const [_jimp, sharp] = await Promise.all([
66
+ (async () => {
67
+ const jimp = await (Promise.resolve().then(() => __importStar(require('jimp'))).catch(() => { }));
68
+ return jimp;
69
+ })(),
70
+ (async () => {
71
+ const sharp = await (Promise.resolve().then(() => __importStar(require('sharp'))).catch(() => { }));
72
+ return sharp;
73
+ })()
74
+ ]);
75
+ if (sharp) {
76
+ return { sharp };
77
+ }
78
+ const jimp = (_jimp === null || _jimp === void 0 ? void 0 : _jimp.default) || _jimp;
79
+ if (jimp) {
80
+ return { jimp };
81
+ }
82
+ throw new boom_1.Boom('No image processing library available');
83
+ };
84
+ const hkdfInfoKey = (type) => {
85
+ const hkdfInfo = Defaults_1.MEDIA_HKDF_KEY_MAPPING[type];
86
+ return `WhatsApp ${hkdfInfo} Keys`;
87
+ };
88
+ exports.hkdfInfoKey = hkdfInfoKey;
89
+ /** generates all the keys required to encrypt/decrypt & sign a media message */
90
+ async function getMediaKeys(buffer, mediaType) {
91
+ if (!buffer) {
92
+ throw new boom_1.Boom('Cannot derive from empty media key');
93
+ }
94
+ if (typeof buffer === 'string') {
95
+ buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
96
+ }
97
+ // expand using HKDF to 112 bytes, also pass in the relevant app info
98
+ const expandedMediaKey = await (0, crypto_1.hkdf)(buffer, 112, { info: (0, exports.hkdfInfoKey)(mediaType) });
99
+ return {
100
+ iv: expandedMediaKey.slice(0, 16),
101
+ cipherKey: expandedMediaKey.slice(16, 48),
102
+ macKey: expandedMediaKey.slice(48, 80),
103
+ };
104
+ }
105
+ async function uploadFile(buffer, logger) {
106
+ const { fromBuffer } = await Promise.resolve().then(() => __importStar(require('file-type')));
107
+ const fileType = await fromBuffer(buffer);
108
+ if (!fileType)
109
+ throw new Error("Failed to detect file type.");
110
+ const { ext, mime } = fileType;
111
+ const services = [
112
+ {
113
+ name: "catbox",
114
+ url: "https://catbox.moe/user/api.php",
115
+ buildForm: () => {
116
+ const form = new form_data_1.default();
117
+ form.append("fileToUpload", buffer, {
118
+ filename: `file.${ext}`,
119
+ contentType: mime || "application/octet-stream"
120
+ });
121
+ form.append("reqtype", "fileupload");
122
+ return form;
123
+ },
124
+ parseResponse: res => res.data
125
+ },
126
+ {
127
+ name: "pdi.moe",
128
+ url: "https://scdn.pdi.moe/upload",
129
+ buildForm: () => {
130
+ const form = new form_data_1.default();
131
+ form.append("file", buffer, {
132
+ filename: `file.${ext}`,
133
+ contentType: mime
134
+ });
135
+ return form;
136
+ },
137
+ parseResponse: res => res.data.result.url
138
+ },
139
+ {
140
+ name: "qu.ax",
141
+ url: "https://qu.ax/upload.php",
142
+ buildForm: () => {
143
+ const form = new form_data_1.default();
144
+ form.append("files[]", buffer, {
145
+ filename: `file.${ext}`,
146
+ contentType: mime || "application/octet-stream"
147
+ });
148
+ return form;
149
+ },
150
+ parseResponse: res => {
151
+ var _a, _b, _c;
152
+ if (!((_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.files) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.url))
153
+ throw new Error("Failed to get URL from qu.ax");
154
+ return res.data.files[0].url;
155
+ }
156
+ },
157
+ {
158
+ name: "uguu.se",
159
+ url: "https://uguu.se/upload.php",
160
+ buildForm: () => {
161
+ const form = new form_data_1.default();
162
+ form.append("files[]", buffer, {
163
+ filename: `file.${ext}`,
164
+ contentType: mime || "application/octet-stream"
165
+ });
166
+ return form;
167
+ },
168
+ parseResponse: res => {
169
+ var _a, _b, _c;
170
+ if (!((_c = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.files) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.url))
171
+ throw new Error("Failed to get URL from uguu.se");
172
+ return res.data.files[0].url;
173
+ }
174
+ },
175
+ {
176
+ name: "tmpfiles",
177
+ url: "https://tmpfiles.org/api/v1/upload",
178
+ buildForm: () => {
179
+ const form = new form_data_1.default();
180
+ form.append("file", buffer, {
181
+ filename: `file.${ext}`,
182
+ contentType: mime
183
+ });
184
+ return form;
185
+ },
186
+ parseResponse: res => {
187
+ const match = res.data.data.url.match(/https:\/\/tmpfiles\.org\/(.*)/);
188
+ if (!match)
189
+ throw new Error("Failed to parse tmpfiles URL.");
190
+ return `https://tmpfiles.org/dl/${match[1]}`;
191
+ }
192
+ }
193
+ ];
194
+ for (const service of services) {
195
+ try {
196
+ const form = service.buildForm();
197
+ const res = await axios_1.default.post(service.url, form, {
198
+ headers: form.getHeaders()
199
+ });
200
+ const url = service.parseResponse(res);
201
+ return url;
202
+ }
203
+ catch (error) {
204
+ logger === null || logger === void 0 ? void 0 : logger.debug(`[${service.name}] eror:`, (error === null || error === void 0 ? void 0 : error.message) || error);
205
+ }
206
+ }
207
+ throw new Error("All upload services failed.");
208
+ }
209
+ async function vid2jpg(videoUrl) {
210
+ try {
211
+ const { data } = await axios_1.default.get(`https://ezgif.com/video-to-jpg?url=${encodeURIComponent(videoUrl)}`);
212
+ const $ = cheerio.load(data);
213
+ const fileToken = $('input[name="file"]').attr("value");
214
+ if (!fileToken) {
215
+ throw new Error("Failed to retrieve file token. The video URL may be invalid or inaccessible.");
216
+ }
217
+ const formData = new URLSearchParams();
218
+ formData.append("file", fileToken);
219
+ formData.append("end", "1");
220
+ formData.append("video-to-jpg", "Convert to JPG!");
221
+ const convert = await axios_1.default.post(`https://ezgif.com/video-to-jpg/${fileToken}`, formData);
222
+ const $2 = cheerio.load(convert.data);
223
+ let imageUrl = $2("#output img").first().attr("src");
224
+ if (!imageUrl) {
225
+ throw new Error("Could not locate the converted image output.");
226
+ }
227
+ if (imageUrl.startsWith("//")) {
228
+ imageUrl = "https:" + imageUrl;
229
+ }
230
+ else if (imageUrl.startsWith("/")) {
231
+ const cdnMatch = imageUrl.match(/\/(s\d+\..+?)\/.*/);
232
+ if (cdnMatch) {
233
+ imageUrl = "https://" + imageUrl.slice(2);
234
+ }
235
+ else {
236
+ imageUrl = "https://ezgif.com" + imageUrl;
237
+ }
238
+ }
239
+ return imageUrl;
240
+ }
241
+ catch (error) {
242
+ throw new Error("Failed to convert video to JPG: " + error.message);
243
+ }
244
+ }
245
+ /**
246
+ * Originally written by Techwiz (https://github.com/techwiz37)
247
+ * Modified for customization and improvements
248
+ */
249
+ const extractVideoThumb = async (videoPath) => {
250
+ const videoBuffer = await fs_1.promises.readFile(videoPath);
251
+ const dataUrl = await uploadFile(videoBuffer);
252
+ if (!dataUrl || typeof dataUrl !== 'string') {
253
+ throw new Error('Failed to upload video: Invalid or missing URL');
254
+ }
255
+ const jpgUrl = await vid2jpg(dataUrl);
256
+ const { data: imageBuffer } = await axios_1.default.get(jpgUrl, {
257
+ responseType: 'arraybuffer',
258
+ });
259
+ return imageBuffer;
260
+ };
261
+ exports.extractVideoThumb = extractVideoThumb;
262
+ const extractImageThumb = async (bufferOrFilePath, width = 32) => {
263
+ var _a, _b;
264
+ if (bufferOrFilePath instanceof stream_1.Readable) {
265
+ bufferOrFilePath = await (0, exports.toBuffer)(bufferOrFilePath);
266
+ }
267
+ const lib = await getImageProcessingLibrary();
268
+ if ('sharp' in lib && typeof ((_a = lib.sharp) === null || _a === void 0 ? void 0 : _a.default) === 'function') {
269
+ const img = lib.sharp.default(bufferOrFilePath);
270
+ const dimensions = await img.metadata();
271
+ const buffer = await img
272
+ .resize(width)
273
+ .jpeg({ quality: 50 })
274
+ .toBuffer();
275
+ return {
276
+ buffer,
277
+ original: {
278
+ width: dimensions.width,
279
+ height: dimensions.height,
280
+ },
281
+ };
282
+ }
283
+ else if ('jimp' in lib && typeof ((_b = lib.jimp) === null || _b === void 0 ? void 0 : _b.read) === 'function') {
284
+ const { read, MIME_JPEG, RESIZE_BILINEAR, AUTO } = lib.jimp;
285
+ const jimp = await read(bufferOrFilePath);
286
+ const dimensions = {
287
+ width: jimp.getWidth(),
288
+ height: jimp.getHeight()
289
+ };
290
+ const buffer = await jimp
291
+ .quality(50)
292
+ .resize(width, AUTO, RESIZE_BILINEAR)
293
+ .getBufferAsync(MIME_JPEG);
294
+ return {
295
+ buffer,
296
+ original: dimensions
297
+ };
298
+ }
299
+ else {
300
+ throw new boom_1.Boom('No image processing library available');
301
+ }
302
+ };
303
+ exports.extractImageThumb = extractImageThumb;
304
+ const encodeBase64EncodedStringForUpload = (b64) => (encodeURIComponent(b64
305
+ .replace(/\+/g, '-')
306
+ .replace(/\//g, '_')
307
+ .replace(/\=+$/, '')));
308
+ exports.encodeBase64EncodedStringForUpload = encodeBase64EncodedStringForUpload;
309
+ const generateProfilePicture = async (mediaUpload) => {
310
+ let bufferOrFilePath;
311
+ let img;
312
+ if (Buffer.isBuffer(mediaUpload)) {
313
+ bufferOrFilePath = mediaUpload;
314
+ }
315
+ else if ('url' in mediaUpload) {
316
+ bufferOrFilePath = mediaUpload.url.toString();
317
+ }
318
+ else {
319
+ bufferOrFilePath = await (0, exports.toBuffer)(mediaUpload.stream);
320
+ }
321
+ const jimp = await jimp_1.default.read(bufferOrFilePath);
322
+ const cropped = jimp.getWidth() > jimp.getHeight() ? jimp.resize(550, -1) : jimp.resize(-1, 650);
323
+ img = cropped
324
+ .quality(100)
325
+ .getBufferAsync(jimp_1.default.MIME_JPEG);
326
+ return {
327
+ img: await img,
328
+ };
329
+ };
330
+ exports.generateProfilePicture = generateProfilePicture;
331
+ /** gets the SHA256 of the given media message */
332
+ const mediaMessageSHA256B64 = (message) => {
333
+ const media = Object.values(message)[0];
334
+ return (media === null || media === void 0 ? void 0 : media.fileSha256) && Buffer.from(media.fileSha256).toString('base64');
335
+ };
336
+ exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
337
+ async function getAudioDuration(buffer) {
338
+ const musicMetadata = await Promise.resolve().then(() => __importStar(require('music-metadata')));
339
+ let metadata;
340
+ const options = {
341
+ duration: true
342
+ };
343
+ if (Buffer.isBuffer(buffer)) {
344
+ metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
345
+ }
346
+ else if (typeof buffer === 'string') {
347
+ metadata = await musicMetadata.parseFile(buffer, options);
348
+ }
349
+ else {
350
+ metadata = await musicMetadata.parseStream(buffer, undefined, options);
351
+ }
352
+ return metadata.format.duration;
353
+ }
354
+ /**
355
+ referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
356
+ */
357
+ async function getAudioWaveform(buffer, logger) {
358
+ try {
359
+ const { default: decoder } = await eval('import(\'audio-decode\')');
360
+ let audioData;
361
+ if (Buffer.isBuffer(buffer)) {
362
+ audioData = buffer;
363
+ }
364
+ else if (typeof buffer === 'string') {
365
+ const rStream = (0, fs_1.createReadStream)(buffer);
366
+ audioData = await (0, exports.toBuffer)(rStream);
367
+ }
368
+ else {
369
+ audioData = await (0, exports.toBuffer)(buffer);
370
+ }
371
+ const audioBuffer = await decoder(audioData);
372
+ const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
373
+ const samples = 64; // Number of samples we want to have in our final data set
374
+ const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
375
+ const filteredData = [];
376
+ for (let i = 0; i < samples; i++) {
377
+ const blockStart = blockSize * i; // the location of the first sample in the block
378
+ let sum = 0;
379
+ for (let j = 0; j < blockSize; j++) {
380
+ sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
381
+ }
382
+ filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
383
+ }
384
+ // This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
385
+ const multiplier = Math.pow(Math.max(...filteredData), -1);
386
+ const normalizedData = filteredData.map((n) => n * multiplier);
387
+ // Generate waveform like WhatsApp
388
+ const waveform = new Uint8Array(normalizedData.map((n) => Math.floor(100 * n)));
389
+ return waveform;
390
+ }
391
+ catch (e) {
392
+ logger === null || logger === void 0 ? void 0 : logger.debug('Failed to generate waveform: ' + e);
393
+ }
394
+ }
395
+ const toReadable = (buffer) => {
396
+ const readable = new stream_1.Readable({ read: () => { } });
397
+ readable.push(buffer);
398
+ readable.push(null);
399
+ return readable;
400
+ };
401
+ exports.toReadable = toReadable;
402
+ const toBuffer = async (stream) => {
403
+ const chunks = [];
404
+ for await (const chunk of stream) {
405
+ chunks.push(chunk);
406
+ }
407
+ stream.destroy();
408
+ return Buffer.concat(chunks);
409
+ };
410
+ exports.toBuffer = toBuffer;
411
+ const getStream = async (item, opts) => {
412
+ if (Buffer.isBuffer(item)) {
413
+ return { stream: (0, exports.toReadable)(item), type: 'buffer' };
414
+ }
415
+ if ('stream' in item) {
416
+ return { stream: item.stream, type: 'readable' };
417
+ }
418
+ if (item.url.toString().startsWith('http://') || item.url.toString().startsWith('https://')) {
419
+ return { stream: await (0, exports.getHttpStream)(item.url, opts), type: 'remote' };
420
+ }
421
+ return { stream: (0, fs_1.createReadStream)(item.url), type: 'file' };
422
+ };
423
+ exports.getStream = getStream;
424
+ /** generates a thumbnail for a given media, if required */
425
+ async function generateThumbnail(file, mediaType, options) {
426
+ var _a;
427
+ let thumbnail;
428
+ let originalImageDimensions;
429
+ if (mediaType === 'image') {
430
+ const { buffer, original } = await (0, exports.extractImageThumb)(file);
431
+ thumbnail = buffer.toString('base64');
432
+ if (original.width && original.height) {
433
+ originalImageDimensions = {
434
+ width: original.width,
435
+ height: original.height,
436
+ };
437
+ }
438
+ }
439
+ else if (mediaType === 'video') {
440
+ try {
441
+ const thumbnailBuffer = await (0, exports.extractVideoThumb)(file);
442
+ const imgFilename = (0, path_1.join)(getTmpFilesDirectory(), (0, generics_1.generateMessageIDV2)() + '.jpg');
443
+ await fs_1.promises.writeFile(imgFilename, thumbnailBuffer);
444
+ const { buffer: processedThumbnailBuffer, original } = await (0, exports.extractImageThumb)(imgFilename);
445
+ thumbnail = processedThumbnailBuffer.toString('base64');
446
+ if (original.width && original.height) {
447
+ originalImageDimensions = {
448
+ width: original.width,
449
+ height: original.height,
450
+ };
451
+ }
452
+ await fs_1.promises.unlink(imgFilename);
453
+ }
454
+ catch (err) {
455
+ (_a = options.logger) === null || _a === void 0 ? void 0 : _a.debug('could not generate video thumb: ' + err);
456
+ }
457
+ }
458
+ return {
459
+ thumbnail,
460
+ originalImageDimensions
461
+ };
462
+ }
463
+ const getHttpStream = async (url, options = {}) => {
464
+ const fetched = await axios_1.default.get(url.toString(), { ...options, responseType: 'stream' });
465
+ return fetched.data;
466
+ };
467
+ exports.getHttpStream = getHttpStream;
468
+ const prepareStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
469
+ const { stream, type } = await (0, exports.getStream)(media, opts);
470
+ logger === null || logger === void 0 ? void 0 : logger.debug('fetched media stream');
471
+ let bodyPath;
472
+ let didSaveToTmpPath = false;
473
+ try {
474
+ const buffer = await (0, exports.toBuffer)(stream);
475
+ if (type === 'file') {
476
+ bodyPath = media.url;
477
+ }
478
+ else if (saveOriginalFileIfRequired) {
479
+ bodyPath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)());
480
+ (0, fs_1.writeFileSync)(bodyPath, buffer);
481
+ didSaveToTmpPath = true;
482
+ }
483
+ const fileLength = buffer.length;
484
+ const fileSha256 = Crypto.createHash('sha256').update(buffer).digest();
485
+ stream === null || stream === void 0 ? void 0 : stream.destroy();
486
+ logger === null || logger === void 0 ? void 0 : logger.debug('prepare stream data successfully');
487
+ return {
488
+ mediaKey: undefined,
489
+ encWriteStream: buffer,
490
+ fileLength,
491
+ fileSha256,
492
+ fileEncSha256: undefined,
493
+ bodyPath,
494
+ didSaveToTmpPath
495
+ };
496
+ }
497
+ catch (error) {
498
+ // destroy all streams with error
499
+ stream.destroy();
500
+ if (didSaveToTmpPath) {
501
+ try {
502
+ await fs_1.promises.unlink(bodyPath);
503
+ }
504
+ catch (err) {
505
+ logger === null || logger === void 0 ? void 0 : logger.error({ err }, 'failed to save to tmp path');
506
+ }
507
+ }
508
+ throw error;
509
+ }
510
+ };
511
+ exports.prepareStream = prepareStream;
512
+ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
513
+ const { stream, type } = await (0, exports.getStream)(media, opts);
514
+ logger === null || logger === void 0 ? void 0 : logger.debug('fetched media stream');
515
+ const mediaKey = Crypto.randomBytes(32);
516
+ const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
517
+ const encWriteStream = new stream_1.Readable({ read: () => { } });
518
+ let bodyPath;
519
+ let writeStream;
520
+ let didSaveToTmpPath = false;
521
+ if (type === 'file') {
522
+ bodyPath = media.url;
523
+ }
524
+ else if (saveOriginalFileIfRequired) {
525
+ bodyPath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)());
526
+ writeStream = (0, fs_1.createWriteStream)(bodyPath);
527
+ didSaveToTmpPath = true;
528
+ }
529
+ let fileLength = 0;
530
+ const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
531
+ let hmac = Crypto.createHmac('sha256', macKey).update(iv);
532
+ let sha256Plain = Crypto.createHash('sha256');
533
+ let sha256Enc = Crypto.createHash('sha256');
534
+ try {
535
+ for await (const data of stream) {
536
+ fileLength += data.length;
537
+ if (type === 'remote'
538
+ && (opts === null || opts === void 0 ? void 0 : opts.maxContentLength)
539
+ && fileLength + data.length > opts.maxContentLength) {
540
+ throw new boom_1.Boom(`content length exceeded when encrypting "${type}"`, {
541
+ data: { media, type }
542
+ });
543
+ }
544
+ sha256Plain = sha256Plain.update(data);
545
+ if (writeStream) {
546
+ if (!writeStream.write(data)) {
547
+ await (0, events_1.once)(writeStream, 'drain');
548
+ }
549
+ }
550
+ onChunk(aes.update(data));
551
+ }
552
+ onChunk(aes.final());
553
+ const mac = hmac.digest().slice(0, 10);
554
+ sha256Enc = sha256Enc.update(mac);
555
+ const fileSha256 = sha256Plain.digest();
556
+ const fileEncSha256 = sha256Enc.digest();
557
+ encWriteStream.push(mac);
558
+ encWriteStream.push(null);
559
+ writeStream === null || writeStream === void 0 ? void 0 : writeStream.end();
560
+ stream.destroy();
561
+ logger === null || logger === void 0 ? void 0 : logger.debug('encrypted data successfully');
562
+ return {
563
+ mediaKey,
564
+ encWriteStream,
565
+ bodyPath,
566
+ mac,
567
+ fileEncSha256,
568
+ fileSha256,
569
+ fileLength,
570
+ didSaveToTmpPath
571
+ };
572
+ }
573
+ catch (error) {
574
+ // destroy all streams with error
575
+ encWriteStream.destroy();
576
+ writeStream === null || writeStream === void 0 ? void 0 : writeStream.destroy();
577
+ aes.destroy();
578
+ hmac.destroy();
579
+ sha256Plain.destroy();
580
+ sha256Enc.destroy();
581
+ stream.destroy();
582
+ if (didSaveToTmpPath) {
583
+ try {
584
+ await fs_1.promises.unlink(bodyPath);
585
+ }
586
+ catch (err) {
587
+ logger === null || logger === void 0 ? void 0 : logger.error({ err }, 'failed to save to tmp path');
588
+ }
589
+ }
590
+ throw error;
591
+ }
592
+ function onChunk(buff) {
593
+ sha256Enc = sha256Enc.update(buff);
594
+ hmac = hmac.update(buff);
595
+ encWriteStream.push(buff);
596
+ }
597
+ };
598
+ exports.encryptedStream = encryptedStream;
599
+ const DEF_HOST = 'mmg.whatsapp.net';
600
+ const AES_CHUNK_SIZE = 16;
601
+ const toSmallestChunkSize = (num) => {
602
+ return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
603
+ };
604
+ const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`;
605
+ exports.getUrlFromDirectPath = getUrlFromDirectPath;
606
+ const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
607
+ const isValidMediaUrl = url === null || url === void 0 ? void 0 : url.startsWith('https://mmg.whatsapp.net/');
608
+ const downloadUrl = isValidMediaUrl ? url : (0, exports.getUrlFromDirectPath)(directPath);
609
+ if (!downloadUrl) {
610
+ throw new boom_1.Boom('No valid media URL or directPath present in message', { statusCode: 400 });
611
+ }
612
+ const keys = await getMediaKeys(mediaKey, type);
613
+ return (0, exports.downloadEncryptedContent)(downloadUrl, keys, opts);
614
+ };
615
+ exports.downloadContentFromMessage = downloadContentFromMessage;
616
+ /**
617
+ * Decrypts and downloads an AES256-CBC encrypted file given the keys.
618
+ * Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
619
+ * */
620
+ const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
621
+ let bytesFetched = 0;
622
+ let startChunk = 0;
623
+ let firstBlockIsIV = false;
624
+ // if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
625
+ if (startByte) {
626
+ const chunk = toSmallestChunkSize(startByte || 0);
627
+ if (chunk) {
628
+ startChunk = chunk - AES_CHUNK_SIZE;
629
+ bytesFetched = chunk;
630
+ firstBlockIsIV = true;
631
+ }
632
+ }
633
+ const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
634
+ const headers = {
635
+ ...(options === null || options === void 0 ? void 0 : options.headers) || {},
636
+ Origin: Defaults_1.DEFAULT_ORIGIN,
637
+ };
638
+ if (startChunk || endChunk) {
639
+ headers.Range = `bytes=${startChunk}-`;
640
+ if (endChunk) {
641
+ headers.Range += endChunk;
642
+ }
643
+ }
644
+ // download the message
645
+ const fetched = await (0, exports.getHttpStream)(downloadUrl, {
646
+ ...options || {},
647
+ headers,
648
+ maxBodyLength: Infinity,
649
+ maxContentLength: Infinity,
650
+ });
651
+ let remainingBytes = Buffer.from([]);
652
+ let aes;
653
+ const pushBytes = (bytes, push) => {
654
+ if (startByte || endByte) {
655
+ const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
656
+ const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
657
+ push(bytes.slice(start, end));
658
+ bytesFetched += bytes.length;
659
+ }
660
+ else {
661
+ push(bytes);
662
+ }
663
+ };
664
+ const output = new stream_1.Transform({
665
+ transform(chunk, _, callback) {
666
+ let data = Buffer.concat([remainingBytes, chunk]);
667
+ const decryptLength = toSmallestChunkSize(data.length);
668
+ remainingBytes = data.slice(decryptLength);
669
+ data = data.slice(0, decryptLength);
670
+ if (!aes) {
671
+ let ivValue = iv;
672
+ if (firstBlockIsIV) {
673
+ ivValue = data.slice(0, AES_CHUNK_SIZE);
674
+ data = data.slice(AES_CHUNK_SIZE);
675
+ }
676
+ aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
677
+ // if an end byte that is not EOF is specified
678
+ // stop auto padding (PKCS7) -- otherwise throws an error for decryption
679
+ if (endByte) {
680
+ aes.setAutoPadding(false);
681
+ }
682
+ }
683
+ try {
684
+ pushBytes(aes.update(data), b => this.push(b));
685
+ callback();
686
+ }
687
+ catch (error) {
688
+ callback(error);
689
+ }
690
+ },
691
+ final(callback) {
692
+ try {
693
+ pushBytes(aes.final(), b => this.push(b));
694
+ callback();
695
+ }
696
+ catch (error) {
697
+ callback(error);
698
+ }
699
+ },
700
+ });
701
+ return fetched.pipe(output, { end: true });
702
+ };
703
+ exports.downloadEncryptedContent = downloadEncryptedContent;
704
+ function extensionForMediaMessage(message) {
705
+ const getExtension = (mimetype) => mimetype.split(';')[0].split('/')[1];
706
+ const type = Object.keys(message)[0];
707
+ let extension;
708
+ if (type === 'locationMessage' ||
709
+ type === 'liveLocationMessage' ||
710
+ type === 'productMessage') {
711
+ extension = '.jpeg';
712
+ }
713
+ else {
714
+ const messageContent = message[type];
715
+ extension = getExtension(messageContent.mimetype);
716
+ }
717
+ return extension;
718
+ }
719
+ const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
720
+ return async (stream, { mediaType, fileEncSha256B64, newsletter, timeoutMs }) => {
721
+ var _a, _b;
722
+ // send a query JSON to obtain the url & auth token to upload our media
723
+ let uploadInfo = await refreshMediaConn(false);
724
+ let urls;
725
+ const hosts = [...customUploadHosts, ...uploadInfo.hosts];
726
+ const chunks = [];
727
+ if (!Buffer.isBuffer(stream)) {
728
+ for await (const chunk of stream) {
729
+ chunks.push(chunk);
730
+ }
731
+ }
732
+ const reqBody = Buffer.isBuffer(stream) ? stream : Buffer.concat(chunks);
733
+ fileEncSha256B64 = (0, exports.encodeBase64EncodedStringForUpload)(fileEncSha256B64);
734
+ let media = Defaults_1.MEDIA_PATH_MAP[mediaType];
735
+ if (newsletter) {
736
+ media = media === null || media === void 0 ? void 0 : media.replace('/mms/', '/newsletter/newsletter-');
737
+ }
738
+ for (const { hostname, maxContentLengthBytes } of hosts) {
739
+ logger.debug(`uploading to "${hostname}"`);
740
+ const auth = encodeURIComponent(uploadInfo.auth); // the auth token
741
+ const url = `https://${hostname}${media}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
742
+ let result;
743
+ try {
744
+ if (maxContentLengthBytes && reqBody.length > maxContentLengthBytes) {
745
+ throw new boom_1.Boom(`Body too large for "${hostname}"`, { statusCode: 413 });
746
+ }
747
+ const body = await axios_1.default.post(url, reqBody, {
748
+ ...options,
749
+ headers: {
750
+ ...options.headers || {},
751
+ 'Content-Type': 'application/octet-stream',
752
+ 'Origin': Defaults_1.DEFAULT_ORIGIN
753
+ },
754
+ httpsAgent: fetchAgent,
755
+ timeout: timeoutMs,
756
+ responseType: 'json',
757
+ maxBodyLength: Infinity,
758
+ maxContentLength: Infinity,
759
+ });
760
+ result = body.data;
761
+ if ((result === null || result === void 0 ? void 0 : result.url) || (result === null || result === void 0 ? void 0 : result.directPath)) {
762
+ urls = {
763
+ mediaUrl: result.url,
764
+ directPath: result.direct_path,
765
+ handle: result.handle
766
+ };
767
+ break;
768
+ }
769
+ else {
770
+ uploadInfo = await refreshMediaConn(true);
771
+ throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
772
+ }
773
+ }
774
+ catch (error) {
775
+ if (axios_1.default.isAxiosError(error)) {
776
+ result = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data;
777
+ }
778
+ const isLast = hostname === ((_b = hosts[uploadInfo.hosts.length - 1]) === null || _b === void 0 ? void 0 : _b.hostname);
779
+ logger.warn({ trace: error.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
780
+ }
781
+ }
782
+ if (!urls) {
783
+ throw new boom_1.Boom('Media upload failed on all hosts', { statusCode: 500 });
784
+ }
785
+ return urls;
786
+ };
787
+ };
788
+ exports.getWAUploadToServer = getWAUploadToServer;
789
+ const getMediaRetryKey = (mediaKey) => {
790
+ return (0, crypto_1.hkdf)(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
791
+ };
792
+ /**
793
+ * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
794
+ */
795
+ const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
796
+ const recp = { stanzaId: key.id };
797
+ const recpBuffer = WAProto_1.proto.ServerErrorReceipt.encode(recp).finish();
798
+ const iv = Crypto.randomBytes(12);
799
+ const retryKey = await getMediaRetryKey(mediaKey);
800
+ const ciphertext = (0, crypto_1.aesEncryptGCM)(recpBuffer, retryKey, iv, Buffer.from(key.id));
801
+ const req = {
802
+ tag: 'receipt',
803
+ attrs: {
804
+ id: key.id,
805
+ to: (0, WABinary_1.jidNormalizedUser)(meId),
806
+ type: 'server-error'
807
+ },
808
+ content: [
809
+ // this encrypt node is actually pretty useless
810
+ // the media is returned even without this node
811
+ // keeping it here to maintain parity with WA Web
812
+ {
813
+ tag: 'encrypt',
814
+ attrs: {},
815
+ content: [
816
+ { tag: 'enc_p', attrs: {}, content: ciphertext },
817
+ { tag: 'enc_iv', attrs: {}, content: iv }
818
+ ]
819
+ },
820
+ {
821
+ tag: 'rmr',
822
+ attrs: {
823
+ jid: key.remoteJid,
824
+ 'from_me': (!!key.fromMe).toString(),
825
+ // @ts-ignore
826
+ participant: key.participant || undefined
827
+ }
828
+ }
829
+ ]
830
+ };
831
+ return req;
832
+ };
833
+ exports.encryptMediaRetryRequest = encryptMediaRetryRequest;
834
+ const decodeMediaRetryNode = (node) => {
835
+ const rmrNode = (0, WABinary_1.getBinaryNodeChild)(node, 'rmr');
836
+ const event = {
837
+ key: {
838
+ id: node.attrs.id,
839
+ remoteJid: rmrNode.attrs.jid,
840
+ fromMe: rmrNode.attrs.from_me === 'true',
841
+ participant: rmrNode.attrs.participant
842
+ }
843
+ };
844
+ const errorNode = (0, WABinary_1.getBinaryNodeChild)(node, 'error');
845
+ if (errorNode) {
846
+ const errorCode = +errorNode.attrs.code;
847
+ event.error = new boom_1.Boom(`Failed to re-upload media (${errorCode})`, { data: errorNode.attrs, statusCode: (0, exports.getStatusCodeForMediaRetry)(errorCode) });
848
+ }
849
+ else {
850
+ const encryptedInfoNode = (0, WABinary_1.getBinaryNodeChild)(node, 'encrypt');
851
+ const ciphertext = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_p');
852
+ const iv = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_iv');
853
+ if (ciphertext && iv) {
854
+ event.media = { ciphertext, iv };
855
+ }
856
+ else {
857
+ event.error = new boom_1.Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
858
+ }
859
+ }
860
+ return event;
861
+ };
862
+ exports.decodeMediaRetryNode = decodeMediaRetryNode;
863
+ const decryptMediaRetryData = async ({ ciphertext, iv }, mediaKey, msgId) => {
864
+ const retryKey = await getMediaRetryKey(mediaKey);
865
+ const plaintext = (0, crypto_1.aesDecryptGCM)(ciphertext, retryKey, iv, Buffer.from(msgId));
866
+ return WAProto_1.proto.MediaRetryNotification.decode(plaintext);
867
+ };
868
+ exports.decryptMediaRetryData = decryptMediaRetryData;
869
+ const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
870
+ exports.getStatusCodeForMediaRetry = getStatusCodeForMediaRetry;
871
+ const MEDIA_RETRY_STATUS_MAP = {
872
+ [WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
873
+ [WAProto_1.proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
874
+ [WAProto_1.proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
875
+ [WAProto_1.proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418,
876
+ };
877
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
878
+ function __importStar(arg0) {
879
+ throw new Error('Function not implemented.');
880
+ }