@wppconnect-team/wppconnect 1.41.3 → 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 (47) hide show
  1. package/CHANGELOG.md +12 -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/exposed.enum.d.ts +2 -1
  7. package/dist/api/helpers/exposed.enum.js +1 -0
  8. package/dist/api/helpers/file-to-base64.js +30 -81
  9. package/dist/api/helpers/filename-from-mimetype.js +4 -4
  10. package/dist/api/helpers/scrape-img-qr.js +37 -86
  11. package/dist/api/helpers/scrape-login.js +12 -57
  12. package/dist/api/helpers/select-sticker.js +35 -100
  13. package/dist/api/layers/business.layer.js +29 -134
  14. package/dist/api/layers/catalog.layer.js +59 -210
  15. package/dist/api/layers/community.layer.js +29 -120
  16. package/dist/api/layers/controls.layer.js +62 -262
  17. package/dist/api/layers/group.layer.js +126 -391
  18. package/dist/api/layers/host.layer.js +348 -702
  19. package/dist/api/layers/labels.layer.js +35 -131
  20. package/dist/api/layers/listener.layer.d.ts +9 -1
  21. package/dist/api/layers/listener.layer.js +392 -491
  22. package/dist/api/layers/newsletter.layer.js +20 -89
  23. package/dist/api/layers/profile.layer.js +73 -184
  24. package/dist/api/layers/retriever.layer.js +163 -468
  25. package/dist/api/layers/sender.layer.js +554 -1094
  26. package/dist/api/layers/status.layer.js +80 -179
  27. package/dist/api/layers/ui.layer.js +32 -129
  28. package/dist/api/model/enum/definitions.js +1 -1
  29. package/dist/api/whatsapp.js +200 -426
  30. package/dist/config/WAuserAgente.js +1 -1
  31. package/dist/config/create-config.js +1 -1
  32. package/dist/config/puppeteer.config.js +1 -1
  33. package/dist/controllers/auth.js +42 -110
  34. package/dist/controllers/browser.js +251 -411
  35. package/dist/controllers/initializer.js +171 -265
  36. package/dist/controllers/websocket.js +29 -28
  37. package/dist/controllers/welcome.js +38 -88
  38. package/dist/lib/wapi/wapi.js +1 -1
  39. package/dist/token-store/fileTokenStore.js +83 -173
  40. package/dist/token-store/isValidSessionToken.js +2 -2
  41. package/dist/token-store/isValidTokenStore.js +2 -2
  42. package/dist/token-store/memoryTokenStore.js +11 -14
  43. package/dist/utils/ffmpeg.js +75 -131
  44. package/dist/utils/logger.js +5 -5
  45. package/dist/utils/semver.js +6 -6
  46. package/dist/utils/sleep.js +1 -1
  47. package/package.json +8 -8
@@ -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,482 +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 WAuserAgente_1 = require("../config/WAuserAgente");
118
- var helpers_1 = require("./helpers");
119
- var decrypt_1 = require("./helpers/decrypt");
120
- var business_layer_1 = require("./layers/business.layer");
121
- var fs = __importStar(require("fs"));
122
- var sleep_1 = require("../utils/sleep");
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;
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
- console.error("Attempt ".concat(attempt, " failed: "), error_1.message);
162
- if (attempt === retries) {
163
- console.error("".concat(outputPath, " - All attempt failed to download the file: ").concat(url));
164
- throw error_1;
165
- }
166
- console.log("".concat(outputPath, " - Retrying to download the file: ").concat(url, " in 5 seconds..."));
167
- return [4 /*yield*/, (0, sleep_1.sleep)(5000)];
168
- case 4:
169
- _b.sent();
170
- return [3 /*break*/, 5];
171
- case 5: return [2 /*return*/];
172
- }
173
- });
174
- };
175
- attempt = 1;
176
- _a.label = 1;
177
- case 1:
178
- if (!(attempt <= retries)) return [3 /*break*/, 4];
179
- return [5 /*yield**/, _loop_1(attempt)];
180
- case 2:
181
- state_1 = _a.sent();
182
- if (typeof state_1 === "object")
183
- return [2 /*return*/, state_1.value];
184
- _a.label = 3;
185
- case 3:
186
- attempt++;
187
- return [3 /*break*/, 1];
188
- case 4: return [2 /*return*/];
189
- }
190
- });
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);
191
73
  });
192
- };
193
- var interval = null;
194
- if (_this.page) {
195
- _this.page.on('close', function () { return __awaiter(_this, void 0, void 0, function () {
196
- return __generator(this, function (_a) {
197
- clearInterval(interval);
198
- return [2 /*return*/];
199
- });
200
- }); });
201
74
  }
202
- interval = setInterval(function () { return __awaiter(_this, void 0, void 0, function () {
203
- var newConnected;
204
- var _this = this;
205
- return __generator(this, function (_a) {
206
- switch (_a.label) {
207
- case 0: return [4 /*yield*/, page
208
- .evaluate(function () { return WPP.conn.isRegistered(); })
209
- .catch(function () { return null; })];
210
- case 1:
211
- newConnected = _a.sent();
212
- if (newConnected === null || newConnected === this.connected) {
213
- return [2 /*return*/];
214
- }
215
- this.connected = newConnected;
216
- if (!newConnected) {
217
- this.log('info', 'Session Unpaired', { type: 'session' });
218
- setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
219
- return __generator(this, function (_a) {
220
- if (this.statusFind) {
221
- try {
222
- this.statusFind('disconnectedMobile', session);
223
- }
224
- catch (error) { }
225
- }
226
- return [2 /*return*/];
227
- });
228
- }); }, 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 || '');
229
89
  }
230
- return [2 /*return*/];
231
- }
232
- });
233
- }); }, 1000);
234
- 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);
235
104
  }
236
- Whatsapp.prototype.afterPageScriptInjected = function () {
237
- return __awaiter(this, void 0, void 0, function () {
238
- var _this = this;
239
- return __generator(this, function (_a) {
240
- switch (_a.label) {
241
- case 0: return [4 /*yield*/, _super.prototype.afterPageScriptInjected.call(this)];
242
- case 1:
243
- _a.sent();
244
- this.page
245
- .evaluate(function () { return WPP.conn.isRegistered(); })
246
- .then(function (isAuthenticated) {
247
- _this.connected = isAuthenticated;
248
- })
249
- .catch(function () { return null; });
250
- return [2 /*return*/];
251
- }
252
- });
253
- });
254
- };
255
105
  /**
256
106
  * Decrypts message file
257
107
  * @param data Message object
258
108
  * @returns Decrypted file buffer (null otherwise)
259
109
  */
260
- Whatsapp.prototype.downloadFile = function (data) {
261
- return __awaiter(this, void 0, void 0, function () {
262
- return __generator(this, function (_a) {
263
- switch (_a.label) {
264
- case 0: return [4 /*yield*/, (0, helpers_1.evaluateAndReturn)(this.page, function (data) { return WAPI.downloadFile(data); }, data)];
265
- case 1: return [2 /*return*/, _a.sent()];
266
- }
267
- });
268
- });
269
- };
110
+ async downloadFile(data) {
111
+ return await (0, helpers_1.evaluateAndReturn)(this.page, (data) => WAPI.downloadFile(data), data);
112
+ }
270
113
  /**
271
114
  * Download and returns the media content in base64 format
272
115
  * @param messageId Message or id
273
116
  * @returns Base64 of media
274
117
  */
275
- Whatsapp.prototype.downloadMedia = function (messageId) {
276
- return __awaiter(this, void 0, void 0, function () {
277
- var _this = this;
278
- return __generator(this, function (_a) {
279
- switch (_a.label) {
280
- case 0:
281
- if (typeof messageId !== 'string') {
282
- messageId = messageId.id;
283
- }
284
- return [4 /*yield*/, (0, helpers_1.evaluateAndReturn)(this.page, function (messageId) { return __awaiter(_this, void 0, void 0, function () { var _a, _b; return __generator(this, function (_c) {
285
- switch (_c.label) {
286
- case 0:
287
- _b = (_a = WPP.util).blobToBase64;
288
- return [4 /*yield*/, WPP.chat.downloadMedia(messageId)];
289
- case 1: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
290
- }
291
- }); }); }, messageId)];
292
- case 1: return [2 /*return*/, _a.sent()];
293
- }
294
- });
295
- });
296
- };
297
- Object.defineProperty(Whatsapp.prototype, "waPage", {
298
- /**
299
- * Get the puppeteer page instance
300
- * @returns The Whatsapp page
301
- */
302
- get: function () {
303
- return this.page;
304
- },
305
- enumerable: false,
306
- configurable: true
307
- });
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
+ }
308
141
  /**
309
142
  * Get the puppeteer page screenshot
310
143
  * @returns The Whatsapp page screenshot as a PNG encoded in base64 (not the full data URI, just the base64 section)
311
144
  */
312
- Whatsapp.prototype.takeScreenshot = function () {
313
- return __awaiter(this, void 0, void 0, function () {
314
- return __generator(this, function (_a) {
315
- switch (_a.label) {
316
- case 0:
317
- if (!this.page) return [3 /*break*/, 2];
318
- return [4 /*yield*/, this.page.screenshot({ encoding: 'base64' })];
319
- case 1: return [2 /*return*/, _a.sent()];
320
- case 2: return [2 /*return*/];
321
- }
322
- });
323
- });
324
- };
145
+ async takeScreenshot() {
146
+ if (this.page) {
147
+ return await this.page.screenshot({ encoding: 'base64' });
148
+ }
149
+ }
325
150
  /**
326
151
  * Clicks on 'use here' button (When it gets unlaunched)
327
152
  * This method tracks the class of the button
328
153
  * WhatsApp Web might change this class name over time
329
154
  * Don't rely on this method
330
155
  */
331
- Whatsapp.prototype.useHere = function () {
332
- return __awaiter(this, void 0, void 0, function () {
333
- return __generator(this, function (_a) {
334
- switch (_a.label) {
335
- case 0: return [4 /*yield*/, (0, helpers_1.evaluateAndReturn)(this.page, function () { return WAPI.takeOver(); })];
336
- case 1: return [2 /*return*/, _a.sent()];
337
- }
338
- });
339
- });
340
- };
156
+ async useHere() {
157
+ return await (0, helpers_1.evaluateAndReturn)(this.page, () => WAPI.takeOver());
158
+ }
341
159
  /**
342
160
  * Log out of WhatsApp
343
161
  * @returns boolean
344
162
  */
345
- Whatsapp.prototype.logout = function () {
346
- return __awaiter(this, void 0, void 0, function () {
347
- return __generator(this, function (_a) {
348
- switch (_a.label) {
349
- case 0: return [4 /*yield*/, (0, helpers_1.evaluateAndReturn)(this.page, function () { return WPP.conn.logout(); })];
350
- case 1: return [2 /*return*/, _a.sent()];
351
- }
352
- });
353
- });
354
- };
163
+ async logout() {
164
+ return await (0, helpers_1.evaluateAndReturn)(this.page, () => WPP.conn.logout());
165
+ }
355
166
  /**
356
167
  * Closes page and browser
357
168
  * @internal
358
169
  */
359
- Whatsapp.prototype.close = function () {
360
- return __awaiter(this, void 0, void 0, function () {
361
- var browser;
362
- return __generator(this, function (_a) {
363
- switch (_a.label) {
364
- case 0:
365
- browser = this.page.browser();
366
- if (!!this.page.isClosed()) return [3 /*break*/, 3];
367
- return [4 /*yield*/, this.page.close().catch(function () { return null; })];
368
- case 1:
369
- _a.sent();
370
- return [4 /*yield*/, browser.close().catch(function () { return null; })];
371
- case 2:
372
- _a.sent();
373
- _a.label = 3;
374
- case 3: return [2 /*return*/, true];
375
- }
376
- });
377
- });
378
- };
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
+ }
379
187
  /**
380
188
  * Return PID process
381
189
  * @internal
382
190
  */
383
- Whatsapp.prototype.getPID = function () {
384
- var browser = this.page.browser();
385
- var process = browser.process();
386
- return process.pid;
387
- };
191
+ getPID() {
192
+ const browser = this.page.browser();
193
+ const process = browser.process();
194
+ return process?.pid;
195
+ }
388
196
  /**
389
197
  * Get a message by its ID
390
198
  * @param messageId string
391
199
  * @returns Message object
392
200
  */
393
- Whatsapp.prototype.getMessageById = function (messageId) {
394
- return __awaiter(this, void 0, void 0, function () {
395
- return __generator(this, function (_a) {
396
- switch (_a.label) {
397
- case 0: return [4 /*yield*/, (0, helpers_1.evaluateAndReturn)(this.page, function (messageId) { return WAPI.getMessageById(messageId); }, messageId)];
398
- case 1: return [2 /*return*/, (_a.sent())];
399
- }
400
- });
401
- });
402
- };
201
+ async getMessageById(messageId) {
202
+ return (await (0, helpers_1.evaluateAndReturn)(this.page, (messageId) => WAPI.getMessageById(messageId), messageId));
203
+ }
403
204
  /**
404
205
  * Returns a list of messages from a chat
405
206
  * @param chatId string ID of the conversation or group
406
207
  * @param params GetMessagesParam Result filtering options (count, id, direction) see {@link GetMessagesParam}.
407
208
  * @returns Message object
408
209
  */
409
- Whatsapp.prototype.getMessages = function (chatId_1) {
410
- return __awaiter(this, arguments, void 0, function (chatId, params) {
411
- if (params === void 0) { params = {}; }
412
- return __generator(this, function (_a) {
413
- switch (_a.label) {
414
- case 0: return [4 /*yield*/, (0, helpers_1.evaluateAndReturn)(this.page, function (_a) {
415
- var chatId = _a.chatId, params = _a.params;
416
- return WAPI.getMessages(chatId, params);
417
- }, { chatId: chatId, params: params })];
418
- case 1: return [2 /*return*/, _a.sent()];
419
- }
420
- });
421
- });
422
- };
210
+ async getMessages(chatId, params = {}) {
211
+ return await (0, helpers_1.evaluateAndReturn)(this.page, ({ chatId, params }) => WAPI.getMessages(chatId, params), { chatId, params: params });
212
+ }
423
213
  /**
424
214
  * Decrypts message file
425
215
  * @param message Message object
426
216
  * @returns Decrypted file buffer (`null` otherwise)
427
217
  */
428
- Whatsapp.prototype.decryptFile = function (message) {
429
- return __awaiter(this, void 0, void 0, function () {
430
- var mediaUrl, options, haventGottenImageYet, res, error_2, buff;
431
- return __generator(this, function (_a) {
432
- switch (_a.label) {
433
- case 0:
434
- mediaUrl = message.clientUrl || message.deprecatedMms3Url;
435
- options = (0, decrypt_1.makeOptions)(WAuserAgente_1.useragentOverride);
436
- if (!mediaUrl)
437
- throw new Error('message is missing critical data (`mediaUrl`) needed to download the file.');
438
- haventGottenImageYet = true;
439
- _a.label = 1;
440
- case 1:
441
- _a.trys.push([1, 8, , 9]);
442
- _a.label = 2;
443
- case 2:
444
- if (!haventGottenImageYet) return [3 /*break*/, 7];
445
- return [4 /*yield*/, axios_1.default.get(mediaUrl.trim(), options)];
446
- case 3:
447
- res = _a.sent();
448
- if (!(res.status == 200)) return [3 /*break*/, 4];
449
- haventGottenImageYet = false;
450
- return [3 /*break*/, 6];
451
- case 4: return [4 /*yield*/, (0, decrypt_1.timeout)(2000)];
452
- case 5:
453
- _a.sent();
454
- _a.label = 6;
455
- case 6: return [3 /*break*/, 2];
456
- case 7: return [3 /*break*/, 9];
457
- case 8:
458
- error_2 = _a.sent();
459
- throw new Error('Error trying to download the file.');
460
- case 9:
461
- buff = Buffer.from(res.data, 'binary');
462
- 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;
463
230
  }
464
- });
465
- });
466
- };
467
- Whatsapp.prototype.decryptAndSaveFile = function (message, savePath) {
468
- return __awaiter(this, void 0, void 0, function () {
469
- var mediaUrl, tempSavePath_1, inputReadStream, outputWriteStream_1, decryptedStream_1, error_3;
470
- return __generator(this, function (_a) {
471
- switch (_a.label) {
472
- case 0:
473
- mediaUrl = message.clientUrl || message.deprecatedMms3Url;
474
- if (!mediaUrl) {
475
- throw new Error('Message is missing critical data needed to download the file.');
476
- }
477
- _a.label = 1;
478
- case 1:
479
- _a.trys.push([1, 4, , 5]);
480
- tempSavePath_1 = savePath + '.encrypted';
481
- return [4 /*yield*/, this.downloadEncryptedFile(mediaUrl.trim(), tempSavePath_1)];
482
- case 2:
483
- _a.sent();
484
- inputReadStream = fs.createReadStream(tempSavePath_1);
485
- outputWriteStream_1 = fs.createWriteStream(savePath);
486
- decryptedStream_1 = (0, decrypt_1.newMagix)(message.mediaKey, message.type, message.size);
487
- inputReadStream.pipe(decryptedStream_1).pipe(outputWriteStream_1);
488
- return [4 /*yield*/, new Promise(function (resolve, reject) {
489
- outputWriteStream_1.on('finish', function () {
490
- console.log("Deciphering complete. Deleting the encrypted file: ".concat(tempSavePath_1));
491
- fs.unlink(tempSavePath_1, function (error) {
492
- if (error) {
493
- console.error("Error deleting the input file: ".concat(tempSavePath_1), error);
494
- reject(error);
495
- }
496
- else {
497
- console.log('Encrypted file deleted successfully');
498
- resolve();
499
- }
500
- });
501
- });
502
- outputWriteStream_1.on('error', function (error) {
503
- console.error("Error during writing file: ".concat(savePath), error);
504
- reject(error);
505
- });
506
- decryptedStream_1.on('error', function (error) {
507
- console.error('An error occurred while decrypting the file', error);
508
- reject(error);
509
- });
510
- })];
511
- case 3:
512
- _a.sent();
513
- return [3 /*break*/, 5];
514
- case 4:
515
- error_3 = _a.sent();
516
- throw error_3;
517
- case 5: return [2 /*return*/];
231
+ else {
232
+ await (0, decrypt_1.timeout)(2000);
518
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
+ });
519
276
  });
520
- });
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
+ }
521
306
  };
522
307
  /**
523
308
  * Rejects a call received via WhatsApp
524
309
  * @param callId string Call ID, if not passed, all calls will be rejected
525
310
  * @returns Number of rejected calls
526
311
  */
527
- Whatsapp.prototype.rejectCall = function (callId) {
528
- return __awaiter(this, void 0, void 0, function () {
529
- return __generator(this, function (_a) {
530
- switch (_a.label) {
531
- case 0: return [4 /*yield*/, (0, helpers_1.evaluateAndReturn)(this.page, function (_a) {
532
- var callId = _a.callId;
533
- return WPP.call.rejectCall(callId);
534
- }, {
535
- callId: callId,
536
- })];
537
- case 1: return [2 /*return*/, _a.sent()];
538
- }
539
- });
312
+ async rejectCall(callId) {
313
+ return await (0, helpers_1.evaluateAndReturn)(this.page, ({ callId }) => WPP.call.rejectCall(callId), {
314
+ callId,
540
315
  });
541
- };
542
- return Whatsapp;
543
- }(business_layer_1.BusinessLayer));
316
+ }
317
+ }
544
318
  exports.Whatsapp = Whatsapp;