forked from orkestral/venom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
host.layer.ts
389 lines (344 loc) · 13.6 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
/*
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM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MMMMm::M- dMMNy/dMMN/ yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMN/ +NMMMN- /yyyyyys d. dMMMMNo` dNy-+ymmmho-+NN- dMMMMMMMMN/ yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMNyNMMMMN+::::::::::m+/mMMMMMMd: dMMNho///+ymMMN+/mMMMMMMMMNs/hMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMNsmMMMMMMMMMMMMMMNNNNMMNNNMMNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMMMMMMMMMMMMMNMMNMNMMMNMMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMNMNMMMNMMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNMMNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
*/
import { Page } from 'puppeteer';
import { CreateConfig, defaultOptions } from '../../config/create-config';
import { SocketState } from '../model/enum';
import { injectApi } from '../../controllers/browser';
import { ScrapQrcode } from '../model/qrcode';
import { scrapeImg } from '../helpers';
import {
asciiQr,
isAuthenticated,
isInsideChat,
retrieveQR,
} from '../../controllers/auth';
import { sleep } from '../../utils/sleep';
import { getSpinnies } from '../../utils/spinnies';
import * as Spinnies from 'spinnies';
export class HostLayer {
readonly session: string;
readonly options: CreateConfig;
protected spinnies: Spinnies = getSpinnies();
protected spinStatus = {
apiInject: '',
autoCloseRemain: 0,
previousText: '',
previousStatus: null,
state: '',
};
protected autoCloseInterval = null;
constructor(public page: Page, session?: string, options?: CreateConfig) {
this.session = session;
this.options = { ...defaultOptions, ...options };
this.page.on('load', () => {
this.initialize();
});
this.page.on('close', () => {
this.cancelAutoClose();
this.spin('Page Closed', 'fail');
});
this.spin('Initializing...', 'spinning');
this.initialize();
}
protected spin(text?: string, status?: Spinnies.SpinnerStatus) {
const name = `session-${this.session}`;
text = text || this.spinStatus.previousText;
this.spinStatus.previousText = text;
status =
status || (this.spinStatus.previousStatus as Spinnies.SpinnerStatus);
this.spinStatus.previousStatus = status;
let fullText = `{session: ${this.session}`;
if (this.spinStatus.apiInject) {
fullText += `, apiInject: ${this.spinStatus.apiInject}`;
}
if (this.spinStatus.state) {
fullText += `, state: ${this.spinStatus.state}`;
}
if (this.autoCloseInterval) {
if (!this.options.disableSpins && this.spinStatus.autoCloseRemain > 0) {
fullText += `, autoCloneRemain: ${this.spinStatus.autoCloseRemain}`;
} else if (this.options.autoClose > 0) {
fullText += `, autoClose: ${Math.round(this.options.autoClose / 1000)}`;
}
}
fullText += `}: ${text}`;
let prevText = '';
try {
prevText = this.spinnies.pick(name).text;
} catch (error) {
this.spinnies.add(name, { text: fullText, status });
prevText = fullText;
}
if (prevText !== fullText) {
this.spinnies.update(name, {
text: fullText,
status,
});
}
}
protected async initialize() {
this.spinStatus.apiInject = 'injecting';
this.spin();
await injectApi(this.page)
.then(() => {
this.spinStatus.apiInject = 'injected';
})
.catch(() => {
this.spinStatus.apiInject = 'failed';
});
this.spin();
}
protected tryAutoClose() {
if (
this.options.autoClose > 0 &&
!this.autoCloseInterval &&
!this.page.isClosed()
) {
try {
this.page.close();
} catch (error) {}
}
}
protected startAutoClose() {
if (this.options.autoClose > 0 && !this.autoCloseInterval) {
let remain = this.options.autoClose;
this.autoCloseInterval = setInterval(() => {
if (this.page.isClosed()) {
this.cancelAutoClose();
return;
}
remain -= 1000;
this.spinStatus.autoCloseRemain = Math.round(remain / 1000);
this.spin();
if (remain <= 0) {
this.cancelAutoClose();
this.tryAutoClose();
}
}, 1000);
}
}
protected cancelAutoClose() {
clearInterval(this.autoCloseInterval);
this.autoCloseInterval = null;
this.spin();
}
public async getQrCode() {
let qrResult: ScrapQrcode | undefined;
qrResult = await scrapeImg(this.page).catch(() => undefined);
if (!qrResult || !qrResult.urlCode) {
qrResult = await retrieveQR(this.page).catch(() => undefined);
}
return qrResult;
}
public async waitForQrCodeScan(
catchQR?: (
qrCode: string,
asciiQR: string,
attempt: number,
urlCode?: string
) => void
) {
let urlCode = null;
let attempt = 0;
while (true) {
const result = await this.getQrCode();
if (!result?.urlCode) {
break;
}
if (urlCode !== result.urlCode) {
urlCode = result.urlCode;
attempt++;
let qr = '';
if (this.options.logQR || catchQR) {
qr = await asciiQr(urlCode);
}
if (this.options.logQR) {
this.spin(`Waiting for QRCode Scan (Attempt ${attempt})...:\n${qr}`);
} else {
this.spin(`Waiting for QRCode Scan: Attempt ${attempt}`);
}
if (catchQR) {
catchQR(result.base64Image, qr, attempt, result.urlCode);
}
}
await sleep(500);
}
}
public async waitForInChat() {
let inChat = await isInsideChat(this.page);
while (inChat === false) {
await sleep(200);
inChat = await isInsideChat(this.page);
}
return inChat;
}
public async waitForLogin(
catchQR?: (
qrCode: string,
asciiQR: string,
attempt: number,
urlCode?: string
) => void,
statusFind?: (statusGet: string, session: string) => void
) {
this.spin('Waiting page load', 'spinning');
await this.page
.waitForFunction(`document.readyState === 'complete'`)
.catch(() => {});
this.startAutoClose();
this.spin('Checking is logged...');
let authenticated = await isAuthenticated(this.page).catch(() => null);
if (authenticated === false) {
this.spin('Waiting for QRCode Scan...');
statusFind && statusFind('notLogged', this.session);
await this.waitForQrCodeScan(catchQR);
this.spin('Checking QRCode status...');
// Wait for interface update
await sleep(200);
authenticated = await isAuthenticated(this.page).catch(() => null);
if (authenticated) {
this.spin('QRCode Success');
statusFind && statusFind('qrReadSuccess', this.session);
} else {
this.spin('QRCode Fail', 'fail');
statusFind && statusFind('qrReadFail', this.session);
this.cancelAutoClose();
this.tryAutoClose();
throw 'Failed to read the QRCode';
}
} else if (authenticated === true) {
this.spin('Authenticated');
statusFind && statusFind('isLogged', this.session);
}
if (authenticated === true) {
// Wait for interface update
await sleep(200);
this.spin('Checking phone is connected...');
const inChat = await this.waitForInChat();
if (!inChat) {
this.spin('Phone not connected', 'fail');
statusFind && statusFind('phoneNotConnected', this.session);
this.cancelAutoClose();
this.tryAutoClose();
throw 'Phone not connected';
}
this.cancelAutoClose();
this.spin('Connected', 'succeed');
statusFind && statusFind('inChat', this.session);
return true;
}
if (authenticated === false) {
this.cancelAutoClose();
this.tryAutoClose();
this.spin('Not logged', 'fail');
throw 'Not logged';
}
this.cancelAutoClose();
this.tryAutoClose();
this.spin('Unknow error', 'fail');
throw 'Unknow error';
}
/**
* Delete the Service Workers
*/
public async killServiceWorker() {
return await this.page.evaluate(() => WAPI.killServiceWorker());
}
/**
* Load the service again
*/
public async restartService() {
return await this.page.evaluate(() => WAPI.restartService());
}
/**
* @returns Current host device details
*/
public async getHostDevice() {
return await this.page.evaluate(() => WAPI.getHost());
}
/**
* Retrieves WA version
*/
public async getWAVersion() {
return await this.page.evaluate(() => WAPI.getWAVersion());
}
/**
* Retrieves the connecction state
*/
public async getConnectionState(): Promise<SocketState> {
return await this.page.evaluate(() => {
//@ts-ignore
return Store.State.default.state;
});
}
/**
* Retrieves if the phone is online. Please note that this may not be real time.
*/
public async isConnected() {
return await this.page.evaluate(() => WAPI.isConnected());
}
/**
* Retrieves if the phone is online. Please note that this may not be real time.
*/
public async isLoggedIn() {
return await this.page.evaluate(() => WAPI.isLoggedIn());
}
/**
* Retrieves Battery Level
*/
public async getBatteryLevel() {
return await this.page.evaluate(() => WAPI.getBatteryLevel());
}
}