-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
host.layer.ts
471 lines (404 loc) · 12.5 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
/*
* 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 { CreateConfig, defaultOptions } from '../../config/create-config';
import { SocketState } from '../model/enum';
import { initWhatsapp, injectApi } from '../../controllers/browser';
import { ScrapQrcode } from '../model/qrcode';
import { evaluateAndReturn, scrapeImg } from '../helpers';
import {
asciiQr,
getInterfaceStatus,
isAuthenticated,
isInsideChat,
needsToScan,
} from '../../controllers/auth';
import { sleep } from '../../utils/sleep';
import { defaultLogger, LogLevel } from '../../utils/logger';
import { Logger } from 'winston';
import { CatchQRCallback, HostDevice, StatusFindCallback } from '../model';
import {
FileTokenStore,
isValidSessionToken,
isValidTokenStore,
MemoryTokenStore,
TokenStore,
} from '../../token-store';
export class HostLayer {
readonly session: string;
readonly options: CreateConfig;
readonly logger: Logger;
readonly tokenStore: TokenStore;
protected autoCloseInterval = null;
protected autoCloseCalled = false;
protected statusFind?: StatusFindCallback = null;
constructor(public page: Page, session?: string, options?: CreateConfig) {
this.session = session;
this.options = { ...defaultOptions, ...options };
this.logger = this.options.logger || defaultLogger;
if (typeof this.options.tokenStore === 'string') {
switch (this.options.tokenStore) {
case 'memory':
this.tokenStore = new MemoryTokenStore();
break;
case 'file':
default:
this.tokenStore = new FileTokenStore({
path: this.options.folderNameToken,
});
break;
}
} else {
this.tokenStore = this.options.tokenStore;
}
if (!isValidTokenStore(this.tokenStore)) {
this.log('warn', 'Invalid tokenStore, using default tokenStore', {
type: 'tokenStore',
});
if (this.options.folderNameToken) {
this.tokenStore = new FileTokenStore({
path: this.options.folderNameToken,
});
} else {
this.tokenStore = new MemoryTokenStore();
}
}
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() {
let sessionToken = this.options.sessionToken;
if (!sessionToken) {
sessionToken = await Promise.resolve(
this.tokenStore.getToken(this.session)
);
}
const isValidToken = isValidSessionToken(sessionToken);
if (isValidToken) {
this.log('verbose', 'Injecting session token', { type: 'token' });
}
const hasUserDataDir = !!this.options?.puppeteerOptions?.userDataDir;
let clear = !hasUserDataDir || (hasUserDataDir && !isValidToken);
await initWhatsapp(
this.page,
sessionToken,
clear,
this.options.whatsappVersion
);
this.page.on('load', () => {
this.log('verbose', 'Page loaded', { type: 'page' });
this.afterPageLoad();
});
this.page.on('close', () => {
this.cancelAutoClose();
this.log('verbose', 'Page Closed', { type: 'page' });
});
}
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,
};
await evaluateAndReturn(
this.page,
(options) => {
(window as any).WPPConfig = options;
},
options
);
await injectApi(this.page)
.then(() => {
this.log('verbose', 'wapi.js injected');
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);
})
.catch((e) => {
this.log('verbose', 'wapi.js failed');
});
}
protected tryAutoClose() {
if (this.autoCloseInterval) {
this.cancelAutoClose();
}
if (
this.options.autoClose > 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() {
if (this.options.autoClose > 0 && !this.autoCloseInterval) {
const seconds = Math.round(this.options.autoClose / 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(catchQR?: CatchQRCallback) {
let urlCode = null;
let attempt = 0;
while (true) {
let needsScan = await needsToScan(this.page).catch(() => null);
if (!needsScan) {
break;
}
const result = await this.getQrCode();
if (result?.urlCode && urlCode !== result.urlCode) {
urlCode = result.urlCode;
attempt++;
let qr = '';
if (this.options.logQR || catchQR) {
qr = await asciiQr(urlCode);
}
if (this.options.logQR) {
this.log(
'info',
`Waiting for QRCode Scan (Attempt ${attempt})...:\n${qr}`,
{ code: urlCode }
);
} else {
this.log('verbose', `Waiting for QRCode Scan: Attempt ${attempt}`);
}
if (catchQR) {
catchQR(result.base64Image, qr, attempt, result.urlCode);
}
}
await sleep(200);
}
}
public async waitForInChat() {
let inChat = await isInsideChat(this.page);
while (inChat === false) {
await sleep(200);
inChat = await isInsideChat(this.page);
}
return inChat;
}
public async waitForPageLoad() {
await this.page
.waitForFunction(`!document.querySelector('#initial_startup')`)
.catch(() => {});
await getInterfaceStatus(this.page).catch(() => null);
}
public async waitForLogin(
catchQR?: CatchQRCallback,
statusFind?: StatusFindCallback
) {
this.statusFind = statusFind;
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...');
statusFind && statusFind('notLogged', this.session);
await this.waitForQrCodeScan(catchQR);
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');
statusFind && statusFind('qrReadError', this.session);
} else if (authenticated) {
this.log('http', 'QRCode Success');
statusFind && statusFind('qrReadSuccess', this.session);
} else {
this.log('warn', 'QRCode Fail');
statusFind && statusFind('qrReadFail', this.session);
this.tryAutoClose();
throw 'Failed to read the QRCode';
}
} else if (authenticated === true) {
this.log('http', 'Authenticated');
statusFind && statusFind('isLogged', this.session);
}
if (authenticated === true) {
// Reinicia o contador do autoclose
this.cancelAutoClose();
this.startAutoClose();
// Wait for interface update
await sleep(200);
this.log('http', 'Checking phone is connected...');
const inChat = await this.waitForInChat();
if (!inChat) {
this.log('warn', 'Phone not connected');
statusFind && statusFind('phoneNotConnected', this.session);
this.tryAutoClose();
throw 'Phone not connected';
}
this.cancelAutoClose();
this.log('http', 'Connected');
statusFind && statusFind('inChat', this.session);
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());
}
}