-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
browser.ts
812 lines (728 loc) · 23.7 KB
/
browser.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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
import * as ChromeLauncher from 'chrome-launcher';
import chromeVersion from 'chrome-version';
import * as fs from 'fs';
import * as path from 'path';
import {
Browser,
BrowserContext,
Page,
LaunchOptions,
PuppeteerLaunchOptions
} from 'puppeteer';
import puppeteer from 'puppeteer-extra';
import { options } from '../config';
import { CreateConfig } from '../config/create-config';
import { puppeteerConfig } from '../config/puppeteer.config';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
import { useragentOverride } from '../config/WAuserAgente';
import { sleep } from '../utils/sleep';
import * as Spinnies from 'spinnies';
import * as os from 'os';
import axios from 'axios';
import { defaultOptions } from '../config/create-config';
import * as unzipper from 'unzipper';
import { exec } from 'child_process';
import isRoot from 'is-root';
import 'node-fetch';
type CustomLaunchOptions = LaunchOptions & {
headless?: boolean | 'new' | 'old';
mkdirFolderToken?: options['mkdirFolderToken'];
folderNameToken?: options['folderNameToken'];
session?: options['session'];
puppeteerOptions?: options['puppeteerOptions'];
addBrowserArgs?: options['addBrowserArgs'];
browserPathExecutable?: options['browserPathExecutable'];
devtools?: options['devtools'];
browserArgs?: options['browserArgs'];
addProxy?: options['addProxy'];
browserWS?: options['browserWS'];
};
const cach_url =
'https://raw.githubusercontent.com/wppconnect-team/wa-version/main/html/';
export async function initWhatsapp(
options: options | CreateConfig,
browser: Browser
): Promise<Page | false> {
const waPage = await getWhatsappPage(browser);
if (!waPage) {
return false;
}
try {
await waPage.setUserAgent(useragentOverride);
waPage.setDefaultTimeout(60000);
const { userPass, userProxy, addProxy } = options;
if (typeof options.webVersion === 'string' && options.webVersion.length) {
await waPage.setRequestInterception(true);
waPage.on('request', async (req) => {
if (req.url() === 'https://web.whatsapp.com/') {
let url = cach_url + options.webVersion + '.html';
await req.respond({
status: 200,
contentType: 'text/html',
body: await (await fetch(url)).text()
});
} else {
if (options.forceWebpack === true) {
const headers = req.headers();
if (headers.cookie) {
// Filter out the 'wa_build' cookies and reconstruct the cookie header
headers.cookie = headers.cookie
.split(';')
.filter((cookie) => !cookie.trim().startsWith('wa_build'))
.join(';');
}
// Continue the request with potentially modified headers
await req.continue({ headers });
} else {
await req.continue();
}
}
});
}
if (
typeof userPass === 'string' &&
userPass.length &&
typeof userProxy === 'string' &&
userProxy.length &&
Array.isArray(addProxy) &&
addProxy.length
) {
await waPage.authenticate({
username: userProxy,
password: userPass
});
}
await waPage.goto(puppeteerConfig.whatsappUrl, {
waitUntil: 'domcontentloaded'
});
waPage.on('pageerror', ({ message }) => {
const erroLogType1 = message.includes('RegisterEffect is not a function');
const erroLogType2 = message.includes('[Report Only]');
if (erroLogType1 || erroLogType2) {
waPage.evaluate(() => {
localStorage.clear();
window.location.reload();
});
}
});
await browser.userAgent();
return waPage;
} catch (error) {
console.error(error);
await waPage.close();
return false;
}
}
export async function getWhatsappPage(
browser: Browser | BrowserContext
): Promise<Page | false> {
try {
const pages: Page[] = await browser.pages();
return pages.length !== 0 ? pages[0] : await browser.newPage();
} catch {
return false;
}
}
export function folderSession(
options: options | CreateConfig | CustomLaunchOptions
) {
try {
if (!options) {
throw new Error(`Missing required options`);
}
if (!options.folderNameToken) {
options.folderNameToken = defaultOptions.folderNameToken;
}
if (!options.session) {
options.session = defaultOptions.session;
}
const folderSession = options.mkdirFolderToken
? path.join(
path.resolve(
process.cwd(),
options.mkdirFolderToken,
options.folderNameToken,
options.session
)
)
: path.join(
path.resolve(process.cwd(), options.folderNameToken, options.session)
);
if (!fs.existsSync(folderSession)) {
fs.mkdirSync(folderSession, { recursive: true });
}
const folderMulidevice = options.mkdirFolderToken
? path.join(
path.resolve(
process.cwd(),
options.mkdirFolderToken,
options.folderNameToken
)
)
: path.join(path.resolve(process.cwd(), options.folderNameToken));
if (!fs.existsSync(folderMulidevice)) {
fs.mkdirSync(folderMulidevice, { recursive: true });
}
fs.chmodSync(folderMulidevice, '777');
fs.chmodSync(folderSession, '777');
options.puppeteerOptions = {
userDataDir: folderSession,
ignoreHTTPSErrors: true
} as LaunchOptions;
puppeteerConfig.chromiumArgs.push(`--user-data-dir=${folderSession}`);
return true;
} catch (error) {
console.error(error);
return false;
}
}
async function getGlobalChromeVersion(): Promise<string | null> {
try {
const chromePath = ChromeLauncher.Launcher.getInstallations().pop();
if (chromePath) {
const version = await chromeVersion(chromePath);
return version;
}
} catch (e) {
console.error('Error retrieving Chrome version:', e);
}
return null;
}
async function checkPathDowload(extractPath: string) {
try {
const pathChrome = path.join(extractPath, 'chrome-win', 'chrome.exe');
if (!fs.existsSync(pathChrome)) {
return false;
}
return pathChrome;
} catch {
return false;
}
}
async function getChromeVersionBash(executablePath: string): Promise<string> {
const notCheckText = 'Not check version';
try {
const platform = os.platform();
let command = '';
if (platform === 'linux') {
if (executablePath.includes('chromium')) {
command = 'chromium-browser --version';
} else if (executablePath.includes('chrome')) {
command = 'google-chrome --version';
}
} else if (platform === 'darwin' && executablePath.includes('Chrome')) {
command =
'/Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome --version';
}
if (!command) {
return notCheckText;
}
const { stdout, stderr } = await execAsync(command);
if (stderr) {
return notCheckText;
}
const version = stdout.trim().split(' ')[2];
return version;
} catch (error) {
return notCheckText;
}
}
function execAsync(
command: string
): Promise<{ stdout: string; stderr: string }> {
return new Promise((resolve) => {
exec(command, (error, stdout, stderr) => {
resolve({ stdout, stderr });
});
});
}
function downloadBash(): Promise<string | false> {
return new Promise((resolve, reject) => {
try {
const platform = os.platform();
if (platform === 'linux') {
exec(
'curl -O https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb',
(error, stdout, stderr) => {
if (error) {
throw new Error(
`Error downloading Google Chrome: ${error.message}`
);
}
exec(
'sudo dpkg -i google-chrome-stable_current_amd64.deb',
(error, stdout, stderr) => {
if (error) {
throw new Error(
`Error installing Google Chrome: ${error.message}`
);
}
exec('sudo apt-get update', (error, stdout, stderr) => {
if (error) {
throw new Error(
`Error update dependencies: ${error.message}`
);
}
exec('sudo apt-get install -f', (error, stdout, stderr) => {
if (error) {
throw new Error(
`Error fixing dependencies: ${error.message}`
);
}
exec('which google-chrome', (error, stdout, stderr) => {
if (error) {
throw new Error(
`Error getting Google Chrome path: ${error.message}`
);
}
const path = stdout.trim();
console.log(
`Google Chrome installed successfully at: ${path}`
);
return resolve(path);
});
});
});
}
);
}
);
} else if (platform === 'darwin') {
exec(
'curl -O https://dl.google.com/chrome/mac/stable/GGRO/googlechrome.dmg',
(error, stdout, stderr) => {
if (error) {
throw new Error(
`Error downloading Google Chrome: ${error.message}`
);
}
exec('hdiutil attach googlechrome.dmg', (error, stdout, stderr) => {
if (error) {
throw new Error(`Error mounting DMG file: ${error.message}`);
}
exec(
'rsync -a "/Volumes/Google Chrome/Google Chrome.app" "/Applications/"',
(error, stdout, stderr) => {
if (error) {
throw new Error(
`Error installing Google Chrome: ${error.message}`
);
}
exec(
'hdiutil detach "/Volumes/Google Chrome"',
(error, stdout, stderr) => {
if (error) {
throw new Error(
`Error unmounting DMG file: ${error.message}`
);
}
exec(
'ls -d "/Applications/Google Chrome.app"',
(error, stdout, stderr) => {
if (error) {
console.error(
`Error getting Google Chrome path: ${error.message}`
);
return;
}
const path = stdout.trim();
console.log(
`Google Chrome installed successfully at: ${path}`
);
return resolve(path);
}
);
}
);
}
);
});
}
);
}
resolve(false);
} catch (error) {
console.error(error);
return reject(false);
}
});
}
export async function initBrowser(
options: CustomLaunchOptions,
spinnies: any
): Promise<Browser | false> {
try {
// Use stealth plugin to avoid being detected as a bot
puppeteer.use(StealthPlugin());
const checkFolder = folderSession(options);
if (!checkFolder) {
throw new Error(`Error executing client session info`);
}
// Check for deprecated headless option
if (options.headless === true) {
console.warn(
'Warning: The usage of "headless: true" is deprecated. Please use "headless: \'new\'" or "headless: false" instead. https://developer.chrome.com/articles/new-headless/'
);
}
if (
options.headless !== 'new' &&
options.headless !== 'old' &&
options.headless !== false &&
options.headless !== true
) {
throw new Error('Now use only headless: "new", "true" or false');
}
const chromePath = getChromeExecutablePath();
// Set the executable path to the path of the Chrome binary or the executable path provided
let executablePath =
options.browserPathExecutable ??
getChrome() ??
puppeteer.executablePath() ??
chromePath;
spinnies.add(`executable-path-${options.session}`, {
text: `...`
});
spinnies.succeed(`executable-path-${options.session}`, {
text: `Executable path browser: ${executablePath}`
});
const extractPath = path.join(process.cwd(), 'chrome');
const checkPath = await checkPathDowload(extractPath);
const platform = os.platform();
if (!executablePath || !isChromeInstalled(executablePath)) {
spinnies.add(`browser-info-${options.session}`, {
text: `...`
});
spinnies.fail(`browser-info-${options.session}`, {
text: `Could not find the google-chrome browser on the machine!`
});
const resultBash = await downloadBash();
if (resultBash) {
executablePath = resultBash;
} else if (!checkPath) {
spinnies.add(`browser-status-${options.session}`, {
text: `Downloading browser...`
});
// Download the latest version of Chrome
const downloadUrl = `https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Win_x64%2F1000027%2Fchrome-win.zip?generation=1651780728332948&alt=media`;
const zipFilePath = path.join(
process.cwd(),
'chrome',
'chrome-win.zip'
);
if (!fs.existsSync(extractPath)) {
fs.mkdirSync(extractPath, { recursive: true });
}
fs.chmodSync(extractPath, '777');
spinnies.add(`browser-path-${options.session}`, {
text: `...`
});
spinnies.succeed(`browser-path-${options.session}`, {
text: `Path download Chrome: ${zipFilePath}`
});
const response = await axios.get(downloadUrl, {
responseType: 'arraybuffer'
});
// Verifica se o status da resposta é 200 (OK)
if (response.status === 200) {
await fs.promises.writeFile(zipFilePath, response.data);
spinnies.succeed(`browser-status-${options.session}`, {
text: `Download completed.`
});
spinnies.add(`browser-status-${options.session}`, {
text: `Extracting Chrome: ${extractPath}`
});
const zip = await unzipper.Open.file(zipFilePath);
await zip.extract({ path: extractPath });
spinnies.succeed(`browser-status-${options.session}`, {
text: `Chrome extracted successfully.`
});
const pathChrome = path.join(extractPath, 'chrome-win', 'chrome.exe');
if (!fs.existsSync(pathChrome)) {
throw new Error(`Error no Path download Chrome`);
}
const checkDowl = await checkPathDowload(extractPath);
if (!checkDowl) {
throw new Error(`Error no Path download Chrome`);
}
const folderChrom = path.join(extractPath, 'chrome-win');
fs.chmodSync(folderChrom, '777');
executablePath = pathChrome;
spinnies.add(`browser-path-${options.session}`, {
text: `...`
});
spinnies.succeed(`browser-path-${options.session}`, {
text: `Execute Path Chrome: ${executablePath}`
});
} else {
throw new Error('Error download file Chrome.');
}
} else {
executablePath = checkPath;
}
}
let chromeVersion = '';
let versionTimeout: string | number | NodeJS.Timeout;
spinnies.add(`browser-Platform-${options.session}`, {
text: `...`
});
spinnies.succeed(`browser-Platform-${options.session}`, {
text: `Platform: ${platform}`
});
if (platform === 'darwin' || platform === 'linux') {
chromeVersion = await getChromeVersionBash(executablePath);
} else {
if (executablePath.includes('google-chrome')) {
chromeVersion = await getGlobalChromeVersion();
} else {
const browser = await puppeteer.launch({
executablePath,
headless:
options.headless === true || options.headless === false
? options.headless
: 'new',
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
versionTimeout = setTimeout(() => {
browser.close();
throw new Error('This browser version has problems');
}, 10000);
chromeVersion = await browser.version();
clearTimeout(versionTimeout);
await browser.close();
}
}
if (chromeVersion) {
spinnies.add(`browser-Version-${options.session}`, {
text: `...`
});
spinnies.succeed(`browser-Version-${options.session}`, {
text: `Browser Version: ${chromeVersion}`
});
}
const extras = { executablePath };
if (Array.isArray(options.addProxy) && options.addProxy.length) {
const proxy =
options.addProxy[Math.floor(Math.random() * options.addProxy.length)];
const args = options.browserArgs ?? puppeteerConfig.chromiumArgs;
args.push(`--proxy-server=${proxy}`);
}
if (
Array.isArray(options.addBrowserArgs) &&
options.addBrowserArgs.length
) {
options.addBrowserArgs.forEach((arg) => {
if (!puppeteerConfig.chromiumArgs.includes(arg)) {
puppeteerConfig.chromiumArgs.push(arg);
}
});
}
if (options.headless === 'old') {
puppeteerConfig.chromiumArgs.push(`--headless=old`);
}
const launchOptions = {
headless: options.headless as 'new' | boolean,
devtools: options.devtools,
args: options.browserArgs ?? puppeteerConfig.chromiumArgs,
...options.puppeteerOptions,
...extras
};
const isRunningAsRoot = isRoot();
if (isRunningAsRoot && options.browserArgs && options.browserArgs.length) {
addArgsRoot(options.browserArgs);
}
if (options.browserWS && options.browserWS !== '') {
return await puppeteer.connect({ browserWSEndpoint: options.browserWS });
} else {
await removeStoredSingletonLock(
options.puppeteerOptions,
spinnies,
options
);
return await puppeteer.launch(launchOptions);
}
} catch (e) {
console.error(e);
return false;
}
}
function addArgsRoot(args: string[]) {
if (Array.isArray(args)) {
args.forEach((option) => {
if (!puppeteerConfig.argsRoot.includes(option)) {
puppeteerConfig.argsRoot.push(option);
}
});
}
}
function getChromeExecutablePath() {
const platform = os.platform();
switch (platform) {
case 'win32':
return getWindowsChromeExecutablePath();
case 'darwin':
return '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
case 'linux':
return '/usr/bin/google-chrome';
default:
console.error('Could not find browser.');
return null;
}
}
function getWindowsChromeExecutablePath() {
const programFilesPath = process.env.ProgramFiles || '';
const programFilesx86Path = process.env['ProgramFiles(x86)'] || '';
if (programFilesx86Path) {
return path.join(
programFilesx86Path,
'Google',
'Chrome',
'Application',
'chrome.exe'
);
} else if (programFilesPath) {
return path.join(
programFilesPath,
'Google',
'Chrome',
'Application',
'chrome.exe'
);
} else {
return null;
}
}
export async function statusLog(
page: Page,
spinnies: Spinnies,
session: string,
callback: (infoLog: string) => void
) {
while (true) {
if (page.isClosed()) {
try {
spinnies.fail(`whatzapp-intro-${session}`, {
text: 'Erro intro'
});
} catch {}
break;
}
const infoLog: string = await page
.evaluate(() => {
const target = document.getElementsByClassName('_2dfCc');
if (target && target.length) {
if (
target[0]['innerText'] !== 'WhatsApp' &&
target[0]['innerText'] !== window['statusInicial']
) {
window['statusInicial'] = target[0]['innerText'];
return window['statusInicial'];
}
}
})
.catch(() => {});
if (infoLog) {
callback(infoLog);
}
await sleep(200);
}
}
/**
* Retrieves chrome instance path
*/
function getChrome() {
try {
const chromeInstalations = ChromeLauncher.Launcher.getInstallations();
return chromeInstalations[0];
} catch (error) {
return undefined;
}
}
function isChromeInstalled(executablePath: string): boolean {
try {
fs.accessSync(executablePath);
return true;
} catch {
return false;
}
}
function removeStoredSingletonLock(
puppeteerOptions: PuppeteerLaunchOptions,
spinnies: any,
options: options | CreateConfig
): Promise<boolean> {
return new Promise((resolve, reject) => {
try {
const platform = os.platform();
const { userDataDir } = puppeteerOptions;
const singletonLockPath = path.join(
path.resolve(process.cwd(), userDataDir, 'SingletonLock')
);
if (platform === 'win32') {
// No need to remove the lock on Windows, so resolve with true directly.
resolve(true);
} else {
spinnies.add(`stored-singleton-lock-${options.session}`, {
text: `...`
});
spinnies.succeed(`stored-singleton-lock-${options.session}`, {
text: `Path Stored "SingletonLock": ${singletonLockPath}`
});
spinnies.add(`path-stored-singleton-lock-${options.session}`, {
text: `checking SingletonLock file`
});
if (fs.existsSync(singletonLockPath)) {
spinnies.add(`path-stored-singleton-lock-${options.session}`, {
text: `The file was found "SingletonLock"`
});
fs.unlink(singletonLockPath, (error) => {
if (error && error.code !== 'ENOENT') {
spinnies.fail(`path-stored-singleton-lock-${options.session}`, {
text: `Error removing "SingletonLock": ${error}`
});
reject(false);
} else {
spinnies.succeed(
`path-stored-singleton-lock-${options.session}`,
{
text: `Removing SingletonLock path: ${singletonLockPath}`
}
);
spinnies.add(
`path-stored-singleton-lock-write-file-${options.session}`,
{
text: `re-adding the file "SingletonLock": ${singletonLockPath}`
}
);
fs.writeFile(singletonLockPath, '', (error) => {
if (error && error.code !== 'ENOENT') {
spinnies.fail(
`path-stored-singleton-lock-write-file-${options.session}`,
{
text: `could not add the file "SingletonLock": ${singletonLockPath}`
}
);
reject(false);
} else {
spinnies.succeed(
`path-stored-singleton-lock-write-file-${options.session}`,
{
text: `file created successfully "SingletonLock": ${singletonLockPath}`
}
);
resolve(true);
}
});
}
});
} else {
spinnies.succeed(`path-stored-singleton-lock-${options.session}`, {
text: `The file "SingletonLock" was not found`
});
resolve(true);
}
}
} catch {
resolve(true);
}
});
}