@wppconnect-team/wppconnect 1.22.0 → 1.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,9 @@
1
+ # 1.23.0 (2023-03-12)
2
+
3
+ ### Bug Fixes
4
+
5
+ - Reduced the number of log for events ([5b39646](https://github.com/wppconnect-team/wppconnect/commit/5b396467c594396741f61495da1c23bac19c8c94))
6
+
1
7
  # 1.22.0 (2023-02-19)
2
8
 
3
9
  ### Features
@@ -1,36 +1,46 @@
1
+ /// <reference types="node" />
1
2
  import { Page } from 'puppeteer';
3
+ import { Logger } from 'winston';
2
4
  import { CreateConfig } from '../../config/create-config';
3
- import { SocketState } from '../model/enum';
4
- import { ScrapQrcode } from '../model/qrcode';
5
5
  import { LogLevel } from '../../utils/logger';
6
- import { Logger } from 'winston';
7
6
  import { CatchQRCallback, HostDevice, LoadingScreenCallback, StatusFindCallback } from '../model';
8
- import { TokenStore } from '../../token-store';
7
+ import { SocketState } from '../model/enum';
8
+ import { ScrapQrcode } from '../model/qrcode';
9
9
  export declare class HostLayer {
10
10
  page: Page;
11
11
  readonly session: string;
12
12
  readonly options: CreateConfig;
13
13
  readonly logger: Logger;
14
- readonly tokenStore: TokenStore;
15
14
  protected autoCloseInterval: any;
16
15
  protected autoCloseCalled: boolean;
17
- protected statusFind?: StatusFindCallback;
18
16
  protected isInitialized: boolean;
19
17
  protected isInjected: boolean;
18
+ protected isStarted: boolean;
19
+ protected isLogged: boolean;
20
+ protected isInChat: boolean;
21
+ protected checkStartInterval?: NodeJS.Timer;
22
+ protected urlCode: string;
23
+ protected attempt: number;
24
+ catchQR?: CatchQRCallback;
25
+ statusFind?: StatusFindCallback;
20
26
  onLoadingScreen?: LoadingScreenCallback;
21
27
  constructor(page: Page, session?: string, options?: CreateConfig);
22
28
  protected log(level: LogLevel, message: string, meta?: object): void;
23
29
  protected initialize(): Promise<void>;
24
30
  protected afterPageLoad(): Promise<void>;
25
31
  protected afterPageScriptInjected(): Promise<void>;
32
+ start(): Promise<void>;
33
+ protected checkStart(): Promise<void>;
34
+ protected checkQrCode(): Promise<void>;
35
+ protected checkInChat(): Promise<void>;
26
36
  protected tryAutoClose(): void;
27
37
  protected startAutoClose(time?: number | null): void;
28
38
  protected cancelAutoClose(): void;
29
39
  getQrCode(): Promise<ScrapQrcode>;
30
- waitForQrCodeScan(catchQR?: CatchQRCallback): Promise<void>;
40
+ waitForQrCodeScan(): Promise<void>;
31
41
  waitForInChat(): Promise<boolean>;
32
42
  waitForPageLoad(): Promise<void>;
33
- waitForLogin(catchQR?: CatchQRCallback, statusFind?: StatusFindCallback): Promise<boolean>;
43
+ waitForLogin(): Promise<boolean>;
34
44
  /**
35
45
  * @category Host
36
46
  * @returns Current host device details
@@ -65,53 +65,30 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
65
65
  Object.defineProperty(exports, "__esModule", { value: true });
66
66
  exports.HostLayer = void 0;
67
67
  var create_config_1 = require("../../config/create-config");
68
- var browser_1 = require("../../controllers/browser");
69
- var helpers_1 = require("../helpers");
70
68
  var auth_1 = require("../../controllers/auth");
71
- var sleep_1 = require("../../utils/sleep");
69
+ var browser_1 = require("../../controllers/browser");
72
70
  var logger_1 = require("../../utils/logger");
73
- var token_store_1 = require("../../token-store");
71
+ var sleep_1 = require("../../utils/sleep");
72
+ var helpers_1 = require("../helpers");
74
73
  var HostLayer = /** @class */ (function () {
75
74
  function HostLayer(page, session, options) {
76
75
  this.page = page;
77
76
  this.autoCloseInterval = null;
78
77
  this.autoCloseCalled = false;
79
- this.statusFind = null;
80
78
  this.isInitialized = false;
81
79
  this.isInjected = false;
80
+ this.isStarted = false;
81
+ this.isLogged = false;
82
+ this.isInChat = false;
83
+ this.checkStartInterval = null;
84
+ this.urlCode = '';
85
+ this.attempt = 0;
86
+ this.catchQR = null;
87
+ this.statusFind = null;
82
88
  this.onLoadingScreen = null;
83
89
  this.session = session;
84
90
  this.options = __assign(__assign({}, create_config_1.defaultOptions), options);
85
91
  this.logger = this.options.logger || logger_1.defaultLogger;
86
- if (typeof this.options.tokenStore === 'string') {
87
- switch (this.options.tokenStore) {
88
- case 'memory':
89
- this.tokenStore = new token_store_1.MemoryTokenStore();
90
- break;
91
- case 'file':
92
- default:
93
- this.tokenStore = new token_store_1.FileTokenStore({
94
- path: this.options.folderNameToken,
95
- });
96
- break;
97
- }
98
- }
99
- else {
100
- this.tokenStore = this.options.tokenStore;
101
- }
102
- if (!(0, token_store_1.isValidTokenStore)(this.tokenStore)) {
103
- this.log('warn', 'Invalid tokenStore, using default tokenStore', {
104
- type: 'tokenStore',
105
- });
106
- if (this.options.folderNameToken) {
107
- this.tokenStore = new token_store_1.FileTokenStore({
108
- path: this.options.folderNameToken,
109
- });
110
- }
111
- else {
112
- this.tokenStore = new token_store_1.MemoryTokenStore();
113
- }
114
- }
115
92
  this.log('info', 'Initializing...');
116
93
  this.initialize();
117
94
  }
@@ -120,40 +97,19 @@ var HostLayer = /** @class */ (function () {
120
97
  this.logger.log(__assign({ level: level, message: message, session: this.session, type: 'client' }, meta));
121
98
  };
122
99
  HostLayer.prototype.initialize = function () {
123
- var _a, _b;
124
100
  return __awaiter(this, void 0, void 0, function () {
125
- var sessionToken, isValidToken, hasUserDataDir, clear;
126
101
  var _this = this;
127
- return __generator(this, function (_c) {
128
- switch (_c.label) {
129
- case 0:
130
- sessionToken = this.options.sessionToken;
131
- if (!!sessionToken) return [3 /*break*/, 2];
132
- return [4 /*yield*/, Promise.resolve(this.tokenStore.getToken(this.session))];
133
- case 1:
134
- sessionToken = _c.sent();
135
- _c.label = 2;
136
- case 2:
137
- isValidToken = (0, token_store_1.isValidSessionToken)(sessionToken);
138
- if (isValidToken) {
139
- this.log('verbose', 'Injecting session token', { type: 'token' });
140
- }
141
- hasUserDataDir = !!((_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.puppeteerOptions) === null || _b === void 0 ? void 0 : _b.userDataDir);
142
- clear = !hasUserDataDir || (hasUserDataDir && !isValidToken);
143
- this.page.on('close', function () {
144
- _this.cancelAutoClose();
145
- _this.log('verbose', 'Page Closed', { type: 'page' });
146
- });
147
- return [4 /*yield*/, (0, browser_1.initWhatsapp)(this.page, sessionToken, clear, this.options.whatsappVersion, this.log.bind(this))];
148
- case 3:
149
- _c.sent();
150
- this.page.on('load', function () {
151
- _this.log('verbose', 'Page loaded', { type: 'page' });
152
- _this.afterPageLoad();
153
- });
154
- this.isInitialized = true;
155
- return [2 /*return*/];
156
- }
102
+ return __generator(this, function (_a) {
103
+ this.page.on('close', function () {
104
+ _this.cancelAutoClose();
105
+ _this.log('verbose', 'Page Closed', { type: 'page' });
106
+ });
107
+ this.page.on('load', function () {
108
+ _this.log('verbose', 'Page loaded', { type: 'page' });
109
+ _this.afterPageLoad();
110
+ });
111
+ this.isInitialized = true;
112
+ return [2 /*return*/];
157
113
  });
158
114
  });
159
115
  };
@@ -209,6 +165,109 @@ var HostLayer = /** @class */ (function () {
209
165
  _this.log('info', "WA-JS version: ".concat(version));
210
166
  })
211
167
  .catch(function () { return null; });
168
+ (0, helpers_1.evaluateAndReturn)(this.page, function () {
169
+ WPP.on('conn.auth_code_change', window.checkQrCode);
170
+ }).catch(function () { return null; });
171
+ (0, helpers_1.evaluateAndReturn)(this.page, function () {
172
+ WPP.on('conn.main_ready', window.checkInChat);
173
+ }).catch(function () { return null; });
174
+ this.checkQrCode();
175
+ this.checkInChat();
176
+ return [2 /*return*/];
177
+ });
178
+ });
179
+ };
180
+ HostLayer.prototype.start = function () {
181
+ return __awaiter(this, void 0, void 0, function () {
182
+ var _this = this;
183
+ return __generator(this, function (_a) {
184
+ switch (_a.label) {
185
+ case 0:
186
+ if (this.isStarted) {
187
+ return [2 /*return*/];
188
+ }
189
+ this.isStarted = true;
190
+ return [4 /*yield*/, (0, browser_1.initWhatsapp)(this.page, null, false, this.options.whatsappVersion, this.log.bind(this))];
191
+ case 1:
192
+ _a.sent();
193
+ return [4 /*yield*/, this.page.exposeFunction('checkQrCode', function () { return _this.checkQrCode(); })];
194
+ case 2:
195
+ _a.sent();
196
+ return [4 /*yield*/, this.page.exposeFunction('checkInChat', function () { return _this.checkInChat(); })];
197
+ case 3:
198
+ _a.sent();
199
+ this.checkStartInterval = setInterval(function () { return _this.checkStart(); }, 5000);
200
+ this.page.on('close', function () {
201
+ clearInterval(_this.checkStartInterval);
202
+ });
203
+ return [2 /*return*/];
204
+ }
205
+ });
206
+ });
207
+ };
208
+ HostLayer.prototype.checkStart = function () {
209
+ return __awaiter(this, void 0, void 0, function () {
210
+ return __generator(this, function (_a) {
211
+ (0, auth_1.needsToScan)(this.page)
212
+ .then(function (need) { })
213
+ .catch(function () { return null; });
214
+ return [2 /*return*/];
215
+ });
216
+ });
217
+ };
218
+ HostLayer.prototype.checkQrCode = function () {
219
+ var _a;
220
+ return __awaiter(this, void 0, void 0, function () {
221
+ var needScan, result, qr;
222
+ return __generator(this, function (_b) {
223
+ switch (_b.label) {
224
+ case 0: return [4 /*yield*/, (0, auth_1.needsToScan)(this.page).catch(function () { return null; })];
225
+ case 1:
226
+ needScan = _b.sent();
227
+ this.isLogged = !needScan;
228
+ if (!needScan) {
229
+ this.attempt = 0;
230
+ return [2 /*return*/];
231
+ }
232
+ return [4 /*yield*/, this.getQrCode()];
233
+ case 2:
234
+ result = _b.sent();
235
+ if (!(result === null || result === void 0 ? void 0 : result.urlCode) || this.urlCode === result.urlCode) {
236
+ return [2 /*return*/];
237
+ }
238
+ this.urlCode = result.urlCode;
239
+ this.attempt++;
240
+ qr = '';
241
+ if (!(this.options.logQR || this.catchQR)) return [3 /*break*/, 4];
242
+ return [4 /*yield*/, (0, auth_1.asciiQr)(this.urlCode)];
243
+ case 3:
244
+ qr = _b.sent();
245
+ _b.label = 4;
246
+ case 4:
247
+ if (this.options.logQR) {
248
+ this.log('info', "Waiting for QRCode Scan (Attempt ".concat(this.attempt, ")...:\n").concat(qr), { code: this.urlCode });
249
+ }
250
+ else {
251
+ this.log('verbose', "Waiting for QRCode Scan: Attempt ".concat(this.attempt));
252
+ }
253
+ (_a = this.catchQR) === null || _a === void 0 ? void 0 : _a.call(this, result.base64Image, qr, this.attempt, result.urlCode);
254
+ return [2 /*return*/];
255
+ }
256
+ });
257
+ });
258
+ };
259
+ HostLayer.prototype.checkInChat = function () {
260
+ var _a;
261
+ return __awaiter(this, void 0, void 0, function () {
262
+ var inChat;
263
+ return __generator(this, function (_b) {
264
+ inChat = (0, auth_1.isInsideChat)(this.page).catch(function () { return null; });
265
+ this.isInChat = !!inChat;
266
+ if (!inChat) {
267
+ return [2 /*return*/];
268
+ }
269
+ this.log('http', 'Connected');
270
+ (_a = this.statusFind) === null || _a === void 0 ? void 0 : _a.call(this, 'inChat', this.session);
212
271
  return [2 /*return*/];
213
272
  });
214
273
  });
@@ -271,78 +330,58 @@ var HostLayer = /** @class */ (function () {
271
330
  });
272
331
  });
273
332
  };
274
- HostLayer.prototype.waitForQrCodeScan = function (catchQR) {
333
+ HostLayer.prototype.waitForQrCodeScan = function () {
275
334
  return __awaiter(this, void 0, void 0, function () {
276
- var urlCode, attempt, needsScan, result, qr;
335
+ var needScan;
277
336
  return __generator(this, function (_a) {
278
337
  switch (_a.label) {
279
338
  case 0:
280
- urlCode = null;
281
- attempt = 0;
339
+ if (!this.isStarted) {
340
+ throw new Error('waitForQrCodeScan error: Session not started');
341
+ }
282
342
  _a.label = 1;
283
343
  case 1:
284
- if (!true) return [3 /*break*/, 8];
285
- return [4 /*yield*/, (0, auth_1.needsToScan)(this.page).catch(function () { return null; })];
344
+ if (!(!this.page.isClosed() && !this.isLogged)) return [3 /*break*/, 4];
345
+ return [4 /*yield*/, (0, sleep_1.sleep)(200)];
286
346
  case 2:
287
- needsScan = _a.sent();
288
- if (!needsScan) {
289
- return [3 /*break*/, 8];
290
- }
291
- return [4 /*yield*/, this.getQrCode()];
292
- case 3:
293
- result = _a.sent();
294
- if (!((result === null || result === void 0 ? void 0 : result.urlCode) && urlCode !== result.urlCode)) return [3 /*break*/, 6];
295
- urlCode = result.urlCode;
296
- attempt++;
297
- qr = '';
298
- if (!(this.options.logQR || catchQR)) return [3 /*break*/, 5];
299
- return [4 /*yield*/, (0, auth_1.asciiQr)(urlCode)];
300
- case 4:
301
- qr = _a.sent();
302
- _a.label = 5;
303
- case 5:
304
- if (this.options.logQR) {
305
- this.log('info', "Waiting for QRCode Scan (Attempt ".concat(attempt, ")...:\n").concat(qr), { code: urlCode });
306
- }
307
- else {
308
- this.log('verbose', "Waiting for QRCode Scan: Attempt ".concat(attempt));
309
- }
310
- if (catchQR) {
311
- catchQR(result.base64Image, qr, attempt, result.urlCode);
312
- }
313
- _a.label = 6;
314
- case 6: return [4 /*yield*/, (0, sleep_1.sleep)(200)];
315
- case 7:
316
347
  _a.sent();
348
+ return [4 /*yield*/, (0, auth_1.needsToScan)(this.page).catch(function () { return null; })];
349
+ case 3:
350
+ needScan = _a.sent();
351
+ this.isLogged = !needScan;
317
352
  return [3 /*break*/, 1];
318
- case 8: return [2 /*return*/];
353
+ case 4: return [2 /*return*/];
319
354
  }
320
355
  });
321
356
  });
322
357
  };
323
358
  HostLayer.prototype.waitForInChat = function () {
324
359
  return __awaiter(this, void 0, void 0, function () {
325
- var inChat, start;
360
+ var start, inChat;
326
361
  return __generator(this, function (_a) {
327
362
  switch (_a.label) {
328
- case 0: return [4 /*yield*/, (0, auth_1.isInsideChat)(this.page)];
329
- case 1:
330
- inChat = _a.sent();
363
+ case 0:
364
+ if (!this.isStarted) {
365
+ throw new Error('waitForInChat error: Session not started');
366
+ }
367
+ if (!this.isLogged) {
368
+ return [2 /*return*/, false];
369
+ }
331
370
  start = Date.now();
332
- _a.label = 2;
333
- case 2:
334
- if (!(inChat === false)) return [3 /*break*/, 5];
335
- if (Date.now() - start >= 60000) {
371
+ _a.label = 1;
372
+ case 1:
373
+ if (!(!this.page.isClosed() && this.isLogged && !this.isInChat)) return [3 /*break*/, 3];
374
+ if (this.options.deviceSyncTimeout > 0 &&
375
+ Date.now() - start >= this.options.deviceSyncTimeout) {
336
376
  return [2 /*return*/, false];
337
377
  }
338
378
  return [4 /*yield*/, (0, sleep_1.sleep)(1000)];
339
- case 3:
379
+ case 2:
340
380
  _a.sent();
341
- return [4 /*yield*/, (0, auth_1.isInsideChat)(this.page)];
342
- case 4:
343
- inChat = _a.sent();
344
- return [3 /*break*/, 2];
345
- case 5: return [2 /*return*/, inChat];
381
+ inChat = (0, auth_1.isInsideChat)(this.page).catch(function () { return null; });
382
+ this.isInChat = !!inChat;
383
+ return [3 /*break*/, 1];
384
+ case 3: return [2 /*return*/, this.isInChat];
346
385
  }
347
386
  });
348
387
  });
@@ -365,48 +404,48 @@ var HostLayer = /** @class */ (function () {
365
404
  });
366
405
  });
367
406
  };
368
- HostLayer.prototype.waitForLogin = function (catchQR, statusFind) {
407
+ HostLayer.prototype.waitForLogin = function () {
408
+ var _a, _b, _c, _d, _e, _f;
369
409
  return __awaiter(this, void 0, void 0, function () {
370
410
  var authenticated, inChat;
371
- return __generator(this, function (_a) {
372
- switch (_a.label) {
411
+ return __generator(this, function (_g) {
412
+ switch (_g.label) {
373
413
  case 0:
374
- this.statusFind = statusFind;
375
414
  this.log('http', 'Waiting page load');
376
415
  return [4 /*yield*/, this.waitForPageLoad()];
377
416
  case 1:
378
- _a.sent();
417
+ _g.sent();
379
418
  this.log('http', 'Checking is logged...');
380
419
  return [4 /*yield*/, (0, auth_1.isAuthenticated)(this.page).catch(function () { return null; })];
381
420
  case 2:
382
- authenticated = _a.sent();
421
+ authenticated = _g.sent();
383
422
  this.startAutoClose();
384
423
  if (!(authenticated === false)) return [3 /*break*/, 6];
385
424
  this.log('http', 'Waiting for QRCode Scan...');
386
- statusFind && statusFind('notLogged', this.session);
387
- return [4 /*yield*/, this.waitForQrCodeScan(catchQR)];
425
+ (_a = this.statusFind) === null || _a === void 0 ? void 0 : _a.call(this, 'notLogged', this.session);
426
+ return [4 /*yield*/, this.waitForQrCodeScan()];
388
427
  case 3:
389
- _a.sent();
428
+ _g.sent();
390
429
  this.log('http', 'Checking QRCode status...');
391
430
  // Wait for interface update
392
431
  return [4 /*yield*/, (0, sleep_1.sleep)(200)];
393
432
  case 4:
394
433
  // Wait for interface update
395
- _a.sent();
434
+ _g.sent();
396
435
  return [4 /*yield*/, (0, auth_1.isAuthenticated)(this.page).catch(function () { return null; })];
397
436
  case 5:
398
- authenticated = _a.sent();
437
+ authenticated = _g.sent();
399
438
  if (authenticated === null) {
400
439
  this.log('warn', 'Failed to authenticate');
401
- statusFind && statusFind('qrReadError', this.session);
440
+ (_b = this.statusFind) === null || _b === void 0 ? void 0 : _b.call(this, 'qrReadError', this.session);
402
441
  }
403
442
  else if (authenticated) {
404
443
  this.log('http', 'QRCode Success');
405
- statusFind && statusFind('qrReadSuccess', this.session);
444
+ (_c = this.statusFind) === null || _c === void 0 ? void 0 : _c.call(this, 'qrReadSuccess', this.session);
406
445
  }
407
446
  else {
408
447
  this.log('warn', 'QRCode Fail');
409
- statusFind && statusFind('qrReadFail', this.session);
448
+ (_d = this.statusFind) === null || _d === void 0 ? void 0 : _d.call(this, 'qrReadFail', this.session);
410
449
  this.tryAutoClose();
411
450
  throw 'Failed to read the QRCode';
412
451
  }
@@ -414,9 +453,9 @@ var HostLayer = /** @class */ (function () {
414
453
  case 6:
415
454
  if (authenticated === true) {
416
455
  this.log('http', 'Authenticated');
417
- statusFind && statusFind('isLogged', this.session);
456
+ (_e = this.statusFind) === null || _e === void 0 ? void 0 : _e.call(this, 'isLogged', this.session);
418
457
  }
419
- _a.label = 7;
458
+ _g.label = 7;
420
459
  case 7:
421
460
  if (!(authenticated === true)) return [3 /*break*/, 10];
422
461
  // Reinicia o contador do autoclose
@@ -425,21 +464,19 @@ var HostLayer = /** @class */ (function () {
425
464
  return [4 /*yield*/, (0, sleep_1.sleep)(200)];
426
465
  case 8:
427
466
  // Wait for interface update
428
- _a.sent();
467
+ _g.sent();
429
468
  this.startAutoClose(this.options.deviceSyncTimeout);
430
469
  this.log('http', 'Checking phone is connected...');
431
470
  return [4 /*yield*/, this.waitForInChat()];
432
471
  case 9:
433
- inChat = _a.sent();
472
+ inChat = _g.sent();
434
473
  if (!inChat) {
435
474
  this.log('warn', 'Phone not connected');
436
- statusFind && statusFind('phoneNotConnected', this.session);
475
+ (_f = this.statusFind) === null || _f === void 0 ? void 0 : _f.call(this, 'phoneNotConnected', this.session);
437
476
  this.tryAutoClose();
438
477
  throw 'Phone not connected';
439
478
  }
440
479
  this.cancelAutoClose();
441
- this.log('http', 'Connected');
442
- statusFind && statusFind('inChat', this.session);
443
480
  return [2 /*return*/, true];
444
481
  case 10:
445
482
  if (authenticated === false) {
@@ -145,7 +145,10 @@ var ListenerLayer = /** @class */ (function (_super) {
145
145
  }
146
146
  Promise.resolve().then(function () {
147
147
  var _a;
148
- _this.log('debug', "Emitting ".concat(func, " event (").concat(_this.listenerEmitter.listenerCount(func), " registered)"));
148
+ var count = _this.listenerEmitter.listenerCount(func);
149
+ if (count > 0) {
150
+ _this.log('debug', "Emitting ".concat(func, " event (").concat(count, " registered)"));
151
+ }
149
152
  (_a = _this.listenerEmitter).emit.apply(_a, __spreadArray([func], args, false));
150
153
  });
151
154
  })
@@ -1,8 +1,8 @@
1
1
  /// <reference types="node" />
2
2
  import { Page } from 'puppeteer';
3
+ import { CreateConfig } from '../config/create-config';
3
4
  import { BusinessLayer } from './layers/business.layer';
4
5
  import { GetMessagesParam, Message } from './model';
5
- import { CreateConfig } from '../config/create-config';
6
6
  export declare class Whatsapp extends BusinessLayer {
7
7
  page: Page;
8
8
  private connected;
@@ -66,5 +66,5 @@ export declare class Whatsapp extends BusinessLayer {
66
66
  * @param callId string ID da ligação, caso não passado, todas ligações serão rejeitadas
67
67
  * @returns Número de ligações rejeitadas
68
68
  */
69
- rejectCall(callId?: string): Promise<number>;
69
+ rejectCall(callId?: string): Promise<boolean>;
70
70
  }