-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
host.layer.ts
541 lines (458 loc) · 14 KB
/
host.layer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
/*
* This file is part of WPPConnect.
*
* WPPConnect is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WPPConnect is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with WPPConnect. If not, see <https://www.gnu.org/licenses/>.
*/
import { Page } from 'puppeteer';
import { Logger } from 'winston';
import { CreateConfig, defaultOptions } from '../../config/create-config';
import {
asciiQr,
isAuthenticated,
isInsideChat,
needsToScan,
} from '../../controllers/auth';
import { initWhatsapp, injectApi } from '../../controllers/browser';
import { defaultLogger, LogLevel } from '../../utils/logger';
import { sleep } from '../../utils/sleep';
import { evaluateAndReturn, scrapeImg } from '../helpers';
import {
CatchQRCallback,
HostDevice,
LoadingScreenCallback,
StatusFindCallback,
} from '../model';
import { SocketState } from '../model/enum';
import { ScrapQrcode } from '../model/qrcode';
export class HostLayer {
readonly session: string;
readonly options: CreateConfig;
readonly logger: Logger;
protected autoCloseInterval = null;
protected autoCloseCalled = false;
protected isInitialized = false;
protected isInjected = false;
protected isStarted = false;
protected isLogged = false;
protected isInChat = false;
protected checkStartInterval?: NodeJS.Timer = null;
protected urlCode = '';
protected attempt = 0;
public catchQR?: CatchQRCallback = null;
public statusFind?: StatusFindCallback = null;
public onLoadingScreen?: LoadingScreenCallback = null;
constructor(public page: Page, session?: string, options?: CreateConfig) {
this.session = session;
this.options = { ...defaultOptions, ...options };
this.logger = this.options.logger || defaultLogger;
this.log('info', 'Initializing...');
this.initialize();
}
protected log(level: LogLevel, message: string, meta: object = {}) {
this.logger.log({
level,
message,
session: this.session,
type: 'client',
...meta,
});
}
protected async initialize() {
this.page.on('close', () => {
this.cancelAutoClose();
this.log('verbose', 'Page Closed', { type: 'page' });
});
this.page.on('load', () => {
this.log('verbose', 'Page loaded', { type: 'page' });
this.afterPageLoad();
});
this.isInitialized = true;
}
protected async afterPageLoad() {
this.log('verbose', 'Injecting wapi.js');
const options = {
deviceName: this.options.deviceName,
disableGoogleAnalytics: this.options.disableGoogleAnalytics,
googleAnalyticsId: this.options.googleAnalyticsId,
linkPreviewApiServers: this.options.linkPreviewApiServers,
poweredBy: this.options.poweredBy,
};
await evaluateAndReturn(
this.page,
(options) => {
(window as any).WPPConfig = options;
},
options
);
this.isInjected = false;
await injectApi(this.page, this.onLoadingScreen)
.then(() => {
this.isInjected = true;
this.log('verbose', 'wapi.js injected');
this.afterPageScriptInjected();
})
.catch((e) => {
console.log(e);
this.log('verbose', 'wapi.js failed');
});
}
protected async afterPageScriptInjected() {
this.getWAVersion()
.then((version) => {
this.log('info', `WhatsApp WEB version: ${version}`);
})
.catch(() => null);
this.getWAJSVersion()
.then((version) => {
this.log('info', `WA-JS version: ${version}`);
})
.catch(() => null);
evaluateAndReturn(this.page, () => {
WPP.on('conn.auth_code_change', (window as any).checkQrCode);
}).catch(() => null);
evaluateAndReturn(this.page, () => {
WPP.on('conn.main_ready', (window as any).checkInChat);
}).catch(() => null);
this.checkQrCode();
this.checkInChat();
}
public async start() {
if (this.isStarted) {
return;
}
this.isStarted = true;
await initWhatsapp(
this.page,
null,
false,
this.options.whatsappVersion,
this.log.bind(this)
);
await this.page.exposeFunction('checkQrCode', () => this.checkQrCode());
await this.page.exposeFunction('checkInChat', () => this.checkInChat());
this.checkStartInterval = setInterval(() => this.checkStart(), 5000);
this.page.on('close', () => {
clearInterval(this.checkStartInterval);
});
}
protected async checkStart() {
needsToScan(this.page)
.then((need) => {})
.catch(() => null);
}
protected async checkQrCode() {
const needScan = await needsToScan(this.page).catch(() => null);
this.isLogged = !needScan;
if (!needScan) {
this.attempt = 0;
return;
}
const result = await this.getQrCode();
if (!result?.urlCode || this.urlCode === result.urlCode) {
return;
}
this.urlCode = result.urlCode;
this.attempt++;
let qr = '';
if (this.options.logQR || this.catchQR) {
qr = await asciiQr(this.urlCode);
}
if (this.options.logQR) {
this.log(
'info',
`Waiting for QRCode Scan (Attempt ${this.attempt})...:\n${qr}`,
{ code: this.urlCode }
);
} else {
this.log('verbose', `Waiting for QRCode Scan: Attempt ${this.attempt}`);
}
this.catchQR?.(result.base64Image, qr, this.attempt, result.urlCode);
}
protected async checkInChat() {
const inChat = await isInsideChat(this.page).catch(() => null);
this.isInChat = !!inChat;
if (!inChat) {
return;
}
this.log('http', 'Connected');
this.statusFind?.('inChat', this.session);
}
protected tryAutoClose() {
if (this.autoCloseInterval) {
this.cancelAutoClose();
}
if (
(this.options.autoClose > 0 || this.options.deviceSyncTimeout > 0) &&
!this.autoCloseInterval &&
!this.page.isClosed()
) {
this.log('info', 'Closing the page');
this.autoCloseCalled = true;
this.statusFind && this.statusFind('autocloseCalled', this.session);
try {
this.page.close();
} catch (error) {}
}
}
protected startAutoClose(time: number | null = null) {
if (time === null || time === undefined) {
time = this.options.autoClose;
}
if (time > 0 && !this.autoCloseInterval) {
const seconds = Math.round(time / 1000);
this.log('info', `Auto close configured to ${seconds}s`);
let remain = seconds;
this.autoCloseInterval = setInterval(() => {
if (this.page.isClosed()) {
this.cancelAutoClose();
return;
}
remain -= 1;
if (remain % 10 === 0 || remain <= 5) {
this.log('http', `Auto close remain: ${remain}s`);
}
if (remain <= 0) {
this.tryAutoClose();
}
}, 1000);
}
}
protected cancelAutoClose() {
clearInterval(this.autoCloseInterval);
this.autoCloseInterval = null;
}
public async getQrCode() {
let qrResult: ScrapQrcode | undefined;
qrResult = await scrapeImg(this.page).catch(() => undefined);
return qrResult;
}
public async waitForQrCodeScan() {
if (!this.isStarted) {
throw new Error('waitForQrCodeScan error: Session not started');
}
while (!this.page.isClosed() && !this.isLogged) {
await sleep(200);
const needScan = await needsToScan(this.page).catch(() => null);
this.isLogged = !needScan;
}
}
public async waitForInChat() {
if (!this.isStarted) {
throw new Error('waitForInChat error: Session not started');
}
if (!this.isLogged) {
return false;
}
const start = Date.now();
while (!this.page.isClosed() && this.isLogged && !this.isInChat) {
if (
this.options.deviceSyncTimeout > 0 &&
Date.now() - start >= this.options.deviceSyncTimeout
) {
return false;
}
await sleep(1000);
const inChat = isInsideChat(this.page).catch(() => null);
this.isInChat = !!inChat;
}
return this.isInChat;
}
public async waitForPageLoad() {
while (!this.isInjected) {
await sleep(200);
}
await this.page.waitForFunction(() => WPP.isReady).catch(() => {});
}
public async waitForLogin() {
this.log('http', 'Waiting page load');
await this.waitForPageLoad();
this.log('http', 'Checking is logged...');
let authenticated = await isAuthenticated(this.page).catch(() => null);
this.startAutoClose();
if (authenticated === false) {
this.log('http', 'Waiting for QRCode Scan...');
this.statusFind?.('notLogged', this.session);
await this.waitForQrCodeScan();
this.log('http', 'Checking QRCode status...');
// Wait for interface update
await sleep(200);
authenticated = await isAuthenticated(this.page).catch(() => null);
if (authenticated === null) {
this.log('warn', 'Failed to authenticate');
this.statusFind?.('qrReadError', this.session);
} else if (authenticated) {
this.log('http', 'QRCode Success');
this.statusFind?.('qrReadSuccess', this.session);
} else {
this.log('warn', 'QRCode Fail');
this.statusFind?.('qrReadFail', this.session);
this.tryAutoClose();
throw 'Failed to read the QRCode';
}
} else if (authenticated === true) {
this.log('http', 'Authenticated');
this.statusFind?.('isLogged', this.session);
}
if (authenticated === true) {
// Reinicia o contador do autoclose
this.cancelAutoClose();
// Wait for interface update
await sleep(200);
this.startAutoClose(this.options.deviceSyncTimeout);
this.log('http', 'Checking phone is connected...');
const inChat = await this.waitForInChat();
if (!inChat) {
this.log('warn', 'Phone not connected');
this.statusFind?.('phoneNotConnected', this.session);
this.tryAutoClose();
throw 'Phone not connected';
}
this.cancelAutoClose();
return true;
}
if (authenticated === false) {
this.tryAutoClose();
this.log('warn', 'Not logged');
throw 'Not logged';
}
this.tryAutoClose();
if (this.autoCloseCalled) {
this.log('error', 'Auto Close Called');
throw 'Auto Close Called';
}
if (this.page.isClosed()) {
this.log('error', 'Page Closed');
throw 'Page Closed';
}
this.log('error', 'Unknow error');
throw 'Unknow error';
}
/**
* @category Host
* @returns Current host device details
*/
public async getHostDevice(): Promise<HostDevice> {
return await evaluateAndReturn(this.page, () => WAPI.getHost());
}
/**
* @category Host
* @returns Current wid connected
*/
public async getWid(): Promise<string> {
return await evaluateAndReturn(this.page, () => WAPI.getWid());
}
/**
* Retrieves WA version
* @category Host
*/
public async getWAVersion() {
await this.page
.waitForFunction(() => WAPI.getWAVersion())
.catch(() => null);
return await evaluateAndReturn(this.page, () => WAPI.getWAVersion());
}
/**
* Retrieves WA-JS version
* @category Host
*/
public async getWAJSVersion() {
await this.page.waitForFunction(() => WPP.version).catch(() => null);
return await evaluateAndReturn(this.page, () => WPP.version);
}
/**
* Retrieves the connecction state
* @category Host
*/
public async getConnectionState(): Promise<SocketState> {
return await evaluateAndReturn(this.page, () => {
return WPP.whatsapp.Socket.state as SocketState;
});
}
/**
* Retrieves if the phone is online. Please note that this may not be real time.
* @category Host
*/
public async isConnected() {
return await evaluateAndReturn(this.page, () => WAPI.isConnected());
}
/**
* Retrieves if the phone is online. Please note that this may not be real time.
* @category Host
*/
public async isLoggedIn() {
return await evaluateAndReturn(this.page, () => WAPI.isLoggedIn());
}
/**
* Retrieves Battery Level
* @category Host
*/
public async getBatteryLevel() {
return await evaluateAndReturn(this.page, () => WAPI.getBatteryLevel());
}
/**
* Start phone Watchdog, forcing the phone connection verification.
*
* @category Host
* @param interval interval number in miliseconds
*/
public async startPhoneWatchdog(interval: number = 15000) {
return await evaluateAndReturn(
this.page,
(interval) => WAPI.startPhoneWatchdog(interval),
interval
);
}
/**
* Stop phone Watchdog, more details in {@link startPhoneWatchdog}
* @category Host
*/
public async stopPhoneWatchdog(interval: number) {
return await evaluateAndReturn(this.page, () => WAPI.stopPhoneWatchdog());
}
/**
* Check the current session is an MultiDevice session
* @category Host
*/
public async isMultiDevice() {
return await evaluateAndReturn(this.page, () => WPP.conn.isMultiDevice());
}
/**
* Retrieve main interface is authenticated, loaded and synced
* @category Host
*/
public async isMainReady() {
return await evaluateAndReturn(this.page, () => WPP.conn.isMainReady());
}
/**
* Retrieve if is authenticated
* @category Host
*/
public async isAuthenticated() {
return await evaluateAndReturn(this.page, () => WPP.conn.isAuthenticated());
}
/**
* Retrieve if main interface is authenticated and loaded, bot not synced
* @category Host
*/
public async isMainLoaded() {
return await evaluateAndReturn(this.page, () => WPP.conn.isMainLoaded());
}
/**
* Retrieve if main interface is initializing
* @category Host
*/
public async isMainInit() {
return await evaluateAndReturn(this.page, () => WPP.conn.isMainInit());
}
}