@wppconnect-team/wppconnect 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/api/helpers/base64-mimetype.js +2 -2
  3. package/dist/api/helpers/decrypt.js +65 -72
  4. package/dist/api/helpers/download-file.js +31 -81
  5. package/dist/api/helpers/evaluate-and-return.js +98 -93
  6. package/dist/api/helpers/file-to-base64.js +30 -81
  7. package/dist/api/helpers/filename-from-mimetype.js +4 -4
  8. package/dist/api/helpers/scrape-img-qr.js +37 -86
  9. package/dist/api/helpers/scrape-login.js +12 -57
  10. package/dist/api/helpers/select-sticker.js +35 -100
  11. package/dist/api/layers/business.layer.js +29 -134
  12. package/dist/api/layers/catalog.layer.js +59 -210
  13. package/dist/api/layers/community.layer.js +29 -120
  14. package/dist/api/layers/controls.layer.js +62 -262
  15. package/dist/api/layers/group.layer.js +126 -391
  16. package/dist/api/layers/host.layer.js +348 -702
  17. package/dist/api/layers/labels.layer.js +35 -131
  18. package/dist/api/layers/listener.layer.js +386 -504
  19. package/dist/api/layers/newsletter.layer.js +20 -89
  20. package/dist/api/layers/profile.layer.js +73 -184
  21. package/dist/api/layers/retriever.layer.js +161 -468
  22. package/dist/api/layers/sender.layer.js +554 -1094
  23. package/dist/api/layers/status.layer.js +80 -179
  24. package/dist/api/layers/ui.layer.js +32 -129
  25. package/dist/api/model/enum/definitions.js +1 -1
  26. package/dist/api/whatsapp.js +200 -437
  27. package/dist/config/WAuserAgente.js +1 -1
  28. package/dist/config/create-config.js +1 -1
  29. package/dist/config/puppeteer.config.js +1 -1
  30. package/dist/controllers/auth.js +42 -110
  31. package/dist/controllers/browser.js +251 -411
  32. package/dist/controllers/initializer.js +171 -265
  33. package/dist/controllers/websocket.js +29 -28
  34. package/dist/controllers/welcome.js +38 -88
  35. package/dist/token-store/fileTokenStore.js +83 -173
  36. package/dist/token-store/isValidSessionToken.js +2 -2
  37. package/dist/token-store/isValidTokenStore.js +2 -2
  38. package/dist/token-store/memoryTokenStore.js +11 -14
  39. package/dist/utils/ffmpeg.js +75 -131
  40. package/dist/utils/logger.js +5 -5
  41. package/dist/utils/semver.js +6 -6
  42. package/dist/utils/sleep.js +1 -1
  43. package/package.json +6 -6
@@ -15,21 +15,6 @@
15
15
  * You should have received a copy of the GNU Lesser General Public License
16
16
  * along with WPPConnect. If not, see <https://www.gnu.org/licenses/>.
17
17
  */
18
- var __extends = (this && this.__extends) || (function () {
19
- var extendStatics = function (d, b) {
20
- extendStatics = Object.setPrototypeOf ||
21
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
23
- return extendStatics(d, b);
24
- };
25
- return function (d, b) {
26
- if (typeof b !== "function" && b !== null)
27
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
28
- extendStatics(d, b);
29
- function __() { this.constructor = d; }
30
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31
- };
32
- })();
33
18
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
34
19
  if (k2 === undefined) k2 = k;
35
20
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -63,493 +48,271 @@ var __importStar = (this && this.__importStar) || (function () {
63
48
  return result;
64
49
  };
65
50
  })();
66
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
67
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
68
- return new (P || (P = Promise))(function (resolve, reject) {
69
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
70
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
71
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
72
- step((generator = generator.apply(thisArg, _arguments || [])).next());
73
- });
74
- };
75
- var __generator = (this && this.__generator) || function (thisArg, body) {
76
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
77
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
78
- function verb(n) { return function (v) { return step([n, v]); }; }
79
- function step(op) {
80
- if (f) throw new TypeError("Generator is already executing.");
81
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
82
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
83
- if (y = 0, t) op = [op[0] & 2, t.value];
84
- switch (op[0]) {
85
- case 0: case 1: t = op; break;
86
- case 4: _.label++; return { value: op[1], done: false };
87
- case 5: _.label++; y = op[1]; op = [0]; continue;
88
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
89
- default:
90
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
91
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
92
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
93
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
94
- if (t[2]) _.ops.pop();
95
- _.trys.pop(); continue;
96
- }
97
- op = body.call(thisArg, _);
98
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
99
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
100
- }
101
- };
102
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
103
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
104
- if (ar || !(i in from)) {
105
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
106
- ar[i] = from[i];
107
- }
108
- }
109
- return to.concat(ar || Array.prototype.slice.call(from));
110
- };
111
51
  var __importDefault = (this && this.__importDefault) || function (mod) {
112
52
  return (mod && mod.__esModule) ? mod : { "default": mod };
113
53
  };
114
54
  Object.defineProperty(exports, "__esModule", { value: true });
115
55
  exports.Whatsapp = void 0;
116
- var axios_1 = __importDefault(require("axios"));
117
- var fs = __importStar(require("fs"));
118
- var WAuserAgente_1 = require("../config/WAuserAgente");
119
- var sleep_1 = require("../utils/sleep");
120
- var helpers_1 = require("./helpers");
121
- var decrypt_1 = require("./helpers/decrypt");
122
- var business_layer_1 = require("./layers/business.layer");
123
- var Whatsapp = /** @class */ (function (_super) {
124
- __extends(Whatsapp, _super);
125
- function Whatsapp(page, session, options) {
126
- var _this = _super.call(this, page, session, options) || this;
127
- _this.page = page;
128
- _this.connected = null;
129
- _this.downloadEncryptedFile = function (url_1, outputPath_1) {
130
- var args_1 = [];
131
- for (var _i = 2; _i < arguments.length; _i++) {
132
- args_1[_i - 2] = arguments[_i];
133
- }
134
- return __awaiter(_this, __spreadArray([url_1, outputPath_1], args_1, true), void 0, function (url, outputPath, retries) {
135
- var _loop_1, attempt, state_1;
136
- if (retries === void 0) { retries = 3; }
137
- return __generator(this, function (_a) {
138
- switch (_a.label) {
139
- case 0:
140
- _loop_1 = function (attempt) {
141
- var response_1, error_1, errorMessage;
142
- return __generator(this, function (_b) {
143
- switch (_b.label) {
144
- case 0:
145
- _b.trys.push([0, 3, , 5]);
146
- return [4 /*yield*/, axios_1.default.get(url, (0, decrypt_1.makeOptions)(WAuserAgente_1.useragentOverride, 'stream'))];
147
- case 1:
148
- response_1 = _b.sent();
149
- return [4 /*yield*/, new Promise(function (resolve, reject) {
150
- var writer = fs.createWriteStream(outputPath);
151
- response_1.data.pipe(writer);
152
- writer.on('finish', resolve);
153
- writer.on('error', reject);
154
- })];
155
- case 2:
156
- _b.sent();
157
- console.log("Encrypted file downloaded at ".concat(outputPath));
158
- return [2 /*return*/, { value: void 0 }];
159
- case 3:
160
- error_1 = _b.sent();
161
- errorMessage = error_1 instanceof Error ? error_1.message : String(error_1);
162
- console.error("Attempt ".concat(attempt, " failed: "), errorMessage);
163
- if (attempt === retries) {
164
- console.error("".concat(outputPath, " - All attempt failed to download the file: ").concat(url));
165
- throw error_1;
166
- }
167
- console.log("".concat(outputPath, " - Retrying to download the file: ").concat(url, " in 5 seconds..."));
168
- return [4 /*yield*/, (0, sleep_1.sleep)(5000)];
169
- case 4:
170
- _b.sent();
171
- return [3 /*break*/, 5];
172
- case 5: return [2 /*return*/];
173
- }
174
- });
175
- };
176
- attempt = 1;
177
- _a.label = 1;
178
- case 1:
179
- if (!(attempt <= retries)) return [3 /*break*/, 4];
180
- return [5 /*yield**/, _loop_1(attempt)];
181
- case 2:
182
- state_1 = _a.sent();
183
- if (typeof state_1 === "object")
184
- return [2 /*return*/, state_1.value];
185
- _a.label = 3;
186
- case 3:
187
- attempt++;
188
- return [3 /*break*/, 1];
189
- case 4: return [2 /*return*/];
190
- }
191
- });
56
+ const axios_1 = __importDefault(require("axios"));
57
+ const fs = __importStar(require("fs"));
58
+ const WAuserAgente_1 = require("../config/WAuserAgente");
59
+ const sleep_1 = require("../utils/sleep");
60
+ const helpers_1 = require("./helpers");
61
+ const decrypt_1 = require("./helpers/decrypt");
62
+ const business_layer_1 = require("./layers/business.layer");
63
+ class Whatsapp extends business_layer_1.BusinessLayer {
64
+ page;
65
+ connected = null;
66
+ constructor(page, session, options) {
67
+ super(page, session, options);
68
+ this.page = page;
69
+ let interval = null;
70
+ if (this.page) {
71
+ this.page.on('close', async () => {
72
+ clearInterval(interval);
192
73
  });
193
- };
194
- var interval = null;
195
- if (_this.page) {
196
- _this.page.on('close', function () { return __awaiter(_this, void 0, void 0, function () {
197
- return __generator(this, function (_a) {
198
- clearInterval(interval);
199
- return [2 /*return*/];
200
- });
201
- }); });
202
74
  }
203
- interval = setInterval(function () { return __awaiter(_this, void 0, void 0, function () {
204
- var newConnected;
205
- var _this = this;
206
- return __generator(this, function (_a) {
207
- switch (_a.label) {
208
- case 0: return [4 /*yield*/, page
209
- .evaluate(function () { return WPP.conn.isRegistered(); })
210
- .catch(function () { return null; })];
211
- case 1:
212
- newConnected = _a.sent();
213
- if (newConnected === null || newConnected === this.connected) {
214
- return [2 /*return*/];
215
- }
216
- this.connected = newConnected;
217
- if (!newConnected) {
218
- this.log('info', 'Session Unpaired', { type: 'session' });
219
- setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
220
- return __generator(this, function (_a) {
221
- if (this.statusFind) {
222
- try {
223
- this.statusFind('disconnectedMobile', session || '');
224
- }
225
- catch (error) { }
226
- }
227
- return [2 /*return*/];
228
- });
229
- }); }, 1000);
75
+ interval = setInterval(async () => {
76
+ const newConnected = await page
77
+ .evaluate(() => WPP.conn.isRegistered())
78
+ .catch(() => null);
79
+ if (newConnected === null || newConnected === this.connected) {
80
+ return;
81
+ }
82
+ this.connected = newConnected;
83
+ if (!newConnected) {
84
+ this.log('info', 'Session Unpaired', { type: 'session' });
85
+ setTimeout(async () => {
86
+ if (this.statusFind) {
87
+ try {
88
+ this.statusFind('disconnectedMobile', session || '');
230
89
  }
231
- return [2 /*return*/];
232
- }
233
- });
234
- }); }, 1000);
235
- return _this;
90
+ catch (error) { }
91
+ }
92
+ }, 1000);
93
+ }
94
+ }, 1000);
95
+ }
96
+ async afterPageScriptInjected() {
97
+ await super.afterPageScriptInjected();
98
+ this.page
99
+ .evaluate(() => WPP.conn.isRegistered())
100
+ .then((isAuthenticated) => {
101
+ this.connected = isAuthenticated;
102
+ })
103
+ .catch(() => null);
236
104
  }
237
- Whatsapp.prototype.afterPageScriptInjected = function () {
238
- return __awaiter(this, void 0, void 0, function () {
239
- var _this = this;
240
- return __generator(this, function (_a) {
241
- switch (_a.label) {
242
- case 0: return [4 /*yield*/, _super.prototype.afterPageScriptInjected.call(this)];
243
- case 1:
244
- _a.sent();
245
- this.page
246
- .evaluate(function () { return WPP.conn.isRegistered(); })
247
- .then(function (isAuthenticated) {
248
- _this.connected = isAuthenticated;
249
- })
250
- .catch(function () { return null; });
251
- return [2 /*return*/];
252
- }
253
- });
254
- });
255
- };
256
105
  /**
257
106
  * Decrypts message file
258
107
  * @param data Message object
259
108
  * @returns Decrypted file buffer (null otherwise)
260
109
  */
261
- Whatsapp.prototype.downloadFile = function (data) {
262
- return __awaiter(this, void 0, void 0, function () {
263
- return __generator(this, function (_a) {
264
- switch (_a.label) {
265
- case 0: return [4 /*yield*/, (0, helpers_1.evaluateAndReturn)(this.page, function (data) { return WAPI.downloadFile(data); }, data)];
266
- case 1: return [2 /*return*/, _a.sent()];
267
- }
268
- });
269
- });
270
- };
110
+ async downloadFile(data) {
111
+ return await (0, helpers_1.evaluateAndReturn)(this.page, (data) => WAPI.downloadFile(data), data);
112
+ }
271
113
  /**
272
114
  * Download and returns the media content in base64 format
273
115
  * @param messageId Message or id
274
116
  * @returns Base64 of media
275
117
  */
276
- Whatsapp.prototype.downloadMedia = function (messageId) {
277
- return __awaiter(this, void 0, void 0, function () {
278
- var _this = this;
279
- return __generator(this, function (_a) {
280
- switch (_a.label) {
281
- case 0:
282
- if (typeof messageId !== 'string') {
283
- messageId = messageId.id;
284
- }
285
- if (!messageId) {
286
- throw new Error('downloadMedia: messageId is undefined or null. ' +
287
- 'Make sure the message object (e.g. quotedMsgObj) exists before calling downloadMedia.');
288
- }
289
- return [4 /*yield*/, (0, helpers_1.evaluateAndReturn)(this.page, function (messageId) { return __awaiter(_this, void 0, void 0, function () {
290
- var media;
291
- return __generator(this, function (_a) {
292
- switch (_a.label) {
293
- case 0: return [4 /*yield*/, WPP.chat.downloadMedia(messageId)];
294
- case 1:
295
- media = _a.sent();
296
- if (!media) {
297
- throw new Error("downloadMedia: no media found for message id \"".concat(messageId, "\". The message may not contain downloadable media."));
298
- }
299
- return [2 /*return*/, WPP.util.blobToBase64(media)];
300
- }
301
- });
302
- }); }, messageId)];
303
- case 1: return [2 /*return*/, _a.sent()];
304
- }
305
- });
306
- });
307
- };
308
- Object.defineProperty(Whatsapp.prototype, "waPage", {
309
- /**
310
- * Get the puppeteer page instance
311
- * @returns The Whatsapp page
312
- */
313
- get: function () {
314
- return this.page;
315
- },
316
- enumerable: false,
317
- configurable: true
318
- });
118
+ async downloadMedia(messageId) {
119
+ if (typeof messageId !== 'string') {
120
+ messageId = messageId.id;
121
+ }
122
+ if (!messageId) {
123
+ throw new Error('downloadMedia: messageId is undefined or null. ' +
124
+ 'Make sure the message object (e.g. quotedMsgObj) exists before calling downloadMedia.');
125
+ }
126
+ return await (0, helpers_1.evaluateAndReturn)(this.page, async (messageId) => {
127
+ const media = await WPP.chat.downloadMedia(messageId);
128
+ if (!media) {
129
+ throw new Error(`downloadMedia: no media found for message id "${messageId}". The message may not contain downloadable media.`);
130
+ }
131
+ return WPP.util.blobToBase64(media);
132
+ }, messageId);
133
+ }
134
+ /**
135
+ * Get the puppeteer page instance
136
+ * @returns The Whatsapp page
137
+ */
138
+ get waPage() {
139
+ return this.page;
140
+ }
319
141
  /**
320
142
  * Get the puppeteer page screenshot
321
143
  * @returns The Whatsapp page screenshot as a PNG encoded in base64 (not the full data URI, just the base64 section)
322
144
  */
323
- Whatsapp.prototype.takeScreenshot = function () {
324
- return __awaiter(this, void 0, void 0, function () {
325
- return __generator(this, function (_a) {
326
- switch (_a.label) {
327
- case 0:
328
- if (!this.page) return [3 /*break*/, 2];
329
- return [4 /*yield*/, this.page.screenshot({ encoding: 'base64' })];
330
- case 1: return [2 /*return*/, _a.sent()];
331
- case 2: return [2 /*return*/];
332
- }
333
- });
334
- });
335
- };
145
+ async takeScreenshot() {
146
+ if (this.page) {
147
+ return await this.page.screenshot({ encoding: 'base64' });
148
+ }
149
+ }
336
150
  /**
337
151
  * Clicks on 'use here' button (When it gets unlaunched)
338
152
  * This method tracks the class of the button
339
153
  * WhatsApp Web might change this class name over time
340
154
  * Don't rely on this method
341
155
  */
342
- Whatsapp.prototype.useHere = function () {
343
- return __awaiter(this, void 0, void 0, function () {
344
- return __generator(this, function (_a) {
345
- switch (_a.label) {
346
- case 0: return [4 /*yield*/, (0, helpers_1.evaluateAndReturn)(this.page, function () { return WAPI.takeOver(); })];
347
- case 1: return [2 /*return*/, _a.sent()];
348
- }
349
- });
350
- });
351
- };
156
+ async useHere() {
157
+ return await (0, helpers_1.evaluateAndReturn)(this.page, () => WAPI.takeOver());
158
+ }
352
159
  /**
353
160
  * Log out of WhatsApp
354
161
  * @returns boolean
355
162
  */
356
- Whatsapp.prototype.logout = function () {
357
- return __awaiter(this, void 0, void 0, function () {
358
- return __generator(this, function (_a) {
359
- switch (_a.label) {
360
- case 0: return [4 /*yield*/, (0, helpers_1.evaluateAndReturn)(this.page, function () { return WPP.conn.logout(); })];
361
- case 1: return [2 /*return*/, _a.sent()];
362
- }
363
- });
364
- });
365
- };
163
+ async logout() {
164
+ return await (0, helpers_1.evaluateAndReturn)(this.page, () => WPP.conn.logout());
165
+ }
366
166
  /**
367
167
  * Closes page and browser
368
168
  * @internal
369
169
  */
370
- Whatsapp.prototype.close = function () {
371
- return __awaiter(this, void 0, void 0, function () {
372
- var browser;
373
- return __generator(this, function (_a) {
374
- switch (_a.label) {
375
- case 0:
376
- browser = this.page.browser();
377
- if (!!this.page.isClosed()) return [3 /*break*/, 3];
378
- return [4 /*yield*/, this.page.close().catch(function () { return null; })];
379
- case 1:
380
- _a.sent();
381
- return [4 /*yield*/, browser.close().catch(function () { return null; })];
382
- case 2:
383
- _a.sent();
384
- _a.label = 3;
385
- case 3: return [2 /*return*/, true];
386
- }
387
- });
388
- });
389
- };
170
+ async close() {
171
+ const browser = this.page.browser();
172
+ if (!this.page.isClosed()) {
173
+ await this.page.close().catch(() => null);
174
+ await browser.close().catch(() => null);
175
+ /*
176
+ Code was removed as it is not necessary.
177
+ try {
178
+ const process = browser.process();
179
+ if (process) {
180
+ treekill(process.pid, 'SIGKILL');
181
+ }
182
+ } catch (error) {}
183
+ */
184
+ }
185
+ return true;
186
+ }
390
187
  /**
391
188
  * Return PID process
392
189
  * @internal
393
190
  */
394
- Whatsapp.prototype.getPID = function () {
395
- var browser = this.page.browser();
396
- var process = browser.process();
397
- return process === null || process === void 0 ? void 0 : process.pid;
398
- };
191
+ getPID() {
192
+ const browser = this.page.browser();
193
+ const process = browser.process();
194
+ return process?.pid;
195
+ }
399
196
  /**
400
197
  * Get a message by its ID
401
198
  * @param messageId string
402
199
  * @returns Message object
403
200
  */
404
- Whatsapp.prototype.getMessageById = function (messageId) {
405
- return __awaiter(this, void 0, void 0, function () {
406
- return __generator(this, function (_a) {
407
- switch (_a.label) {
408
- case 0: return [4 /*yield*/, (0, helpers_1.evaluateAndReturn)(this.page, function (messageId) { return WAPI.getMessageById(messageId); }, messageId)];
409
- case 1: return [2 /*return*/, (_a.sent())];
410
- }
411
- });
412
- });
413
- };
201
+ async getMessageById(messageId) {
202
+ return (await (0, helpers_1.evaluateAndReturn)(this.page, (messageId) => WAPI.getMessageById(messageId), messageId));
203
+ }
414
204
  /**
415
205
  * Returns a list of messages from a chat
416
206
  * @param chatId string ID of the conversation or group
417
207
  * @param params GetMessagesParam Result filtering options (count, id, direction) see {@link GetMessagesParam}.
418
208
  * @returns Message object
419
209
  */
420
- Whatsapp.prototype.getMessages = function (chatId_1) {
421
- return __awaiter(this, arguments, void 0, function (chatId, params) {
422
- if (params === void 0) { params = {}; }
423
- return __generator(this, function (_a) {
424
- switch (_a.label) {
425
- case 0: return [4 /*yield*/, (0, helpers_1.evaluateAndReturn)(this.page, function (_a) {
426
- var chatId = _a.chatId, params = _a.params;
427
- return WAPI.getMessages(chatId, params);
428
- }, { chatId: chatId, params: params })];
429
- case 1: return [2 /*return*/, _a.sent()];
430
- }
431
- });
432
- });
433
- };
210
+ async getMessages(chatId, params = {}) {
211
+ return await (0, helpers_1.evaluateAndReturn)(this.page, ({ chatId, params }) => WAPI.getMessages(chatId, params), { chatId, params: params });
212
+ }
434
213
  /**
435
214
  * Decrypts message file
436
215
  * @param message Message object
437
216
  * @returns Decrypted file buffer (`null` otherwise)
438
217
  */
439
- Whatsapp.prototype.decryptFile = function (message) {
440
- return __awaiter(this, void 0, void 0, function () {
441
- var mediaUrl, options, haventGottenImageYet, res, error_2, buff;
442
- return __generator(this, function (_a) {
443
- switch (_a.label) {
444
- case 0:
445
- mediaUrl = message.clientUrl || message.deprecatedMms3Url;
446
- options = (0, decrypt_1.makeOptions)(WAuserAgente_1.useragentOverride);
447
- if (!mediaUrl)
448
- throw new Error('message is missing critical data (`mediaUrl`) needed to download the file.');
449
- haventGottenImageYet = true;
450
- _a.label = 1;
451
- case 1:
452
- _a.trys.push([1, 8, , 9]);
453
- _a.label = 2;
454
- case 2:
455
- if (!haventGottenImageYet) return [3 /*break*/, 7];
456
- return [4 /*yield*/, axios_1.default.get(mediaUrl.trim(), options)];
457
- case 3:
458
- res = _a.sent();
459
- if (!(res.status == 200)) return [3 /*break*/, 4];
460
- haventGottenImageYet = false;
461
- return [3 /*break*/, 6];
462
- case 4: return [4 /*yield*/, (0, decrypt_1.timeout)(2000)];
463
- case 5:
464
- _a.sent();
465
- _a.label = 6;
466
- case 6: return [3 /*break*/, 2];
467
- case 7: return [3 /*break*/, 9];
468
- case 8:
469
- error_2 = _a.sent();
470
- throw new Error('Error trying to download the file.');
471
- case 9:
472
- buff = Buffer.from(res.data, 'binary');
473
- return [2 /*return*/, (0, decrypt_1.magix)(buff, message.mediaKey, message.type, message.size)];
218
+ async decryptFile(message) {
219
+ const mediaUrl = message.clientUrl || message.deprecatedMms3Url;
220
+ const options = (0, decrypt_1.makeOptions)(WAuserAgente_1.useragentOverride);
221
+ if (!mediaUrl)
222
+ throw new Error('message is missing critical data (`mediaUrl`) needed to download the file.');
223
+ let haventGottenImageYet = true;
224
+ let res;
225
+ try {
226
+ while (haventGottenImageYet) {
227
+ res = await axios_1.default.get(mediaUrl.trim(), options);
228
+ if (res.status == 200) {
229
+ haventGottenImageYet = false;
474
230
  }
475
- });
476
- });
477
- };
478
- Whatsapp.prototype.decryptAndSaveFile = function (message, savePath) {
479
- return __awaiter(this, void 0, void 0, function () {
480
- var mediaUrl, tempSavePath_1, inputReadStream, outputWriteStream_1, decryptedStream_1, error_3;
481
- return __generator(this, function (_a) {
482
- switch (_a.label) {
483
- case 0:
484
- mediaUrl = message.clientUrl || message.deprecatedMms3Url;
485
- if (!mediaUrl) {
486
- throw new Error('Message is missing critical data needed to download the file.');
487
- }
488
- _a.label = 1;
489
- case 1:
490
- _a.trys.push([1, 4, , 5]);
491
- tempSavePath_1 = savePath + '.encrypted';
492
- return [4 /*yield*/, this.downloadEncryptedFile(mediaUrl.trim(), tempSavePath_1)];
493
- case 2:
494
- _a.sent();
495
- inputReadStream = fs.createReadStream(tempSavePath_1);
496
- outputWriteStream_1 = fs.createWriteStream(savePath);
497
- decryptedStream_1 = (0, decrypt_1.newMagix)(message.mediaKey, message.type, message.size);
498
- inputReadStream.pipe(decryptedStream_1).pipe(outputWriteStream_1);
499
- return [4 /*yield*/, new Promise(function (resolve, reject) {
500
- outputWriteStream_1.on('finish', function () {
501
- console.log("Deciphering complete. Deleting the encrypted file: ".concat(tempSavePath_1));
502
- fs.unlink(tempSavePath_1, function (error) {
503
- if (error) {
504
- console.error("Error deleting the input file: ".concat(tempSavePath_1), error);
505
- reject(error);
506
- }
507
- else {
508
- console.log('Encrypted file deleted successfully');
509
- resolve();
510
- }
511
- });
512
- });
513
- outputWriteStream_1.on('error', function (error) {
514
- console.error("Error during writing file: ".concat(savePath), error);
515
- reject(error);
516
- });
517
- decryptedStream_1.on('error', function (error) {
518
- console.error('An error occurred while decrypting the file', error);
519
- reject(error);
520
- });
521
- })];
522
- case 3:
523
- _a.sent();
524
- return [3 /*break*/, 5];
525
- case 4:
526
- error_3 = _a.sent();
527
- throw error_3;
528
- case 5: return [2 /*return*/];
231
+ else {
232
+ await (0, decrypt_1.timeout)(2000);
529
233
  }
234
+ }
235
+ }
236
+ catch (error) {
237
+ throw new Error('Error trying to download the file.');
238
+ }
239
+ const buff = Buffer.from(res.data, 'binary');
240
+ return (0, decrypt_1.magix)(buff, message.mediaKey, message.type, message.size);
241
+ }
242
+ async decryptAndSaveFile(message, savePath) {
243
+ const mediaUrl = message.clientUrl || message.deprecatedMms3Url;
244
+ if (!mediaUrl) {
245
+ throw new Error('Message is missing critical data needed to download the file.');
246
+ }
247
+ try {
248
+ const tempSavePath = savePath + '.encrypted';
249
+ await this.downloadEncryptedFile(mediaUrl.trim(), tempSavePath);
250
+ const inputReadStream = fs.createReadStream(tempSavePath);
251
+ const outputWriteStream = fs.createWriteStream(savePath);
252
+ const decryptedStream = (0, decrypt_1.newMagix)(message.mediaKey, message.type, message.size);
253
+ inputReadStream.pipe(decryptedStream).pipe(outputWriteStream);
254
+ await new Promise((resolve, reject) => {
255
+ outputWriteStream.on('finish', () => {
256
+ console.log(`Deciphering complete. Deleting the encrypted file: ${tempSavePath}`);
257
+ fs.unlink(tempSavePath, (error) => {
258
+ if (error) {
259
+ console.error(`Error deleting the input file: ${tempSavePath}`, error);
260
+ reject(error);
261
+ }
262
+ else {
263
+ console.log('Encrypted file deleted successfully');
264
+ resolve();
265
+ }
266
+ });
267
+ });
268
+ outputWriteStream.on('error', (error) => {
269
+ console.error(`Error during writing file: ${savePath}`, error);
270
+ reject(error);
271
+ });
272
+ decryptedStream.on('error', (error) => {
273
+ console.error('An error occurred while decrypting the file', error);
274
+ reject(error);
275
+ });
530
276
  });
531
- });
277
+ }
278
+ catch (error) {
279
+ throw error;
280
+ }
281
+ }
282
+ downloadEncryptedFile = async (url, outputPath, retries = 3) => {
283
+ for (let attempt = 1; attempt <= retries; attempt++) {
284
+ try {
285
+ const response = await axios_1.default.get(url, (0, decrypt_1.makeOptions)(WAuserAgente_1.useragentOverride, 'stream'));
286
+ await new Promise((resolve, reject) => {
287
+ const writer = fs.createWriteStream(outputPath);
288
+ response.data.pipe(writer);
289
+ writer.on('finish', resolve);
290
+ writer.on('error', reject);
291
+ });
292
+ console.log(`Encrypted file downloaded at ${outputPath}`);
293
+ return;
294
+ }
295
+ catch (error) {
296
+ const errorMessage = error instanceof Error ? error.message : String(error);
297
+ console.error(`Attempt ${attempt} failed: `, errorMessage);
298
+ if (attempt === retries) {
299
+ console.error(`${outputPath} - All attempt failed to download the file: ${url}`);
300
+ throw error;
301
+ }
302
+ console.log(`${outputPath} - Retrying to download the file: ${url} in 5 seconds...`);
303
+ await (0, sleep_1.sleep)(5000);
304
+ }
305
+ }
532
306
  };
533
307
  /**
534
308
  * Rejects a call received via WhatsApp
535
309
  * @param callId string Call ID, if not passed, all calls will be rejected
536
310
  * @returns Number of rejected calls
537
311
  */
538
- Whatsapp.prototype.rejectCall = function (callId) {
539
- return __awaiter(this, void 0, void 0, function () {
540
- return __generator(this, function (_a) {
541
- switch (_a.label) {
542
- case 0: return [4 /*yield*/, (0, helpers_1.evaluateAndReturn)(this.page, function (_a) {
543
- var callId = _a.callId;
544
- return WPP.call.rejectCall(callId);
545
- }, {
546
- callId: callId,
547
- })];
548
- case 1: return [2 /*return*/, _a.sent()];
549
- }
550
- });
312
+ async rejectCall(callId) {
313
+ return await (0, helpers_1.evaluateAndReturn)(this.page, ({ callId }) => WPP.call.rejectCall(callId), {
314
+ callId,
551
315
  });
552
- };
553
- return Whatsapp;
554
- }(business_layer_1.BusinessLayer));
316
+ }
317
+ }
555
318
  exports.Whatsapp = Whatsapp;