Skip to content

Commit

Permalink
feat: multidevice and chromiumVersion
Browse files Browse the repository at this point in the history
  • Loading branch information
jonalan7 committed Dec 12, 2021
1 parent 8f08abb commit 4f8fe94
Show file tree
Hide file tree
Showing 5 changed files with 136 additions and 45 deletions.
1 change: 0 additions & 1 deletion src/api/helpers/closes-browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMNMNMMMNMMNNMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNMMNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
*/
import { type } from 'os';
import { Browser } from 'puppeteer';
import { CreateConfig } from '../../config/create-config';

Expand Down
12 changes: 12 additions & 0 deletions src/config/create-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,16 @@ export interface CreateConfig {
* @default false
*/
waitForLogin?: boolean;
/**
* automatically download Chromium browser
* @default true
*/
BrowserFetcher?: boolean;
/**
* Version of the browser that will be used
* @default '818858'
*/
chromiumVersion?: string;
/**
* Wait for in chat to return a instance of {@link Whatsapp}
* @default false
Expand All @@ -173,5 +183,7 @@ export const defaultOptions: CreateConfig = {
autoClose: 120000,
createPathFileToken: true,
waitForLogin: true,
BrowserFetcher: true,
chromiumVersion: '818858',
logger: defaultLogger
};
10 changes: 3 additions & 7 deletions src/config/puppeteer.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,8 @@ MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
const puppeteerConfig = {
whatsappUrl: 'https://web.whatsapp.com',
chromiumArgs: [
// `--app=${WAUrl}`,
'--log-level=3', // fatal only
//'--start-maximized',
'--no-default-browser-check',
'--no-zygote',
'--log-level=3',
'--disable-site-isolation-trials',
'--no-experiments',
'--ignore-gpu-blacklist',
Expand All @@ -70,7 +68,6 @@ const puppeteerConfig = {
'--enable-features=NetworkService',
'--disable-setuid-sandbox',
'--no-sandbox',
// Extras
'--disable-webgl',
'--disable-infobars',
'--window-position=0,0',
Expand All @@ -91,8 +88,7 @@ const puppeteerConfig = {
'--disable-accelerated-video-decode',
'--disable-dev-shm-usage',
'--disable-gl-drawing-for-tests',
'--incognito',
'--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'
'--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'
]
};

Expand Down
113 changes: 104 additions & 9 deletions src/controllers/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNMMNNNMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
*/
import * as ChromeLauncher from 'chrome-launcher';
import * as fs from 'fs';
import * as path from 'path';
import { Browser, BrowserContext, Page } from 'puppeteer';
import puppeteer from 'puppeteer-extra';
Expand All @@ -62,6 +63,8 @@ import StealthPlugin = require('puppeteer-extra-plugin-stealth');
import { auth_InjectToken } from './auth';
import { useragentOverride } from '../config/WAuserAgente';
import { tokenSession } from '../config/tokenSession.config';
import * as chalk from 'chalk';
import { Logger } from 'winston';

export async function initWhatsapp(
session: string,
Expand All @@ -73,9 +76,11 @@ export async function initWhatsapp(
if (waPage != null) {
try {
await waPage.setUserAgent(useragentOverride);
await waPage.setBypassCSP(true);
await waPage.goto(puppeteerConfig.whatsappUrl, {
waitUntil: 'domcontentloaded'
});
await browser.userAgent();
// Auth with token
await auth_InjectToken(waPage, session, options, token);
await waPage.evaluate(() => {
Expand All @@ -84,6 +89,7 @@ export async function initWhatsapp(
return waPage;
} catch {
waPage.close().catch(() => {});
browser.close().catch(() => {});
return false;
}
}
Expand Down Expand Up @@ -132,18 +138,101 @@ export async function injectApi(page: Page) {
export async function initBrowser(
session: string,
options: CreateConfig,
logger: Logger,
extras = {}
): Promise<Browser | string> {
if (options.useChrome) {
const chromePath = getChrome();
if (chromePath) {
extras = { ...extras, executablePath: chromePath };
const chromePath = getChrome();
if (options.useChrome && options.useChrome) {
extras = { ...extras, executablePath: chromePath };
} else {
if (options.BrowserFetcher) {
const browserFetcher = puppeteer.createBrowserFetcher();
logger.info(`${chalk.green('Check chromium....')}`, {
session,
type: 'browser'
});
logger.info(`${chalk.green('Checking the total bytes to download!')}`, {
session,
type: 'browser-total'
});

await browserFetcher
.download(options.chromiumVersion, (downloadedByte, totalBytes) => {
if (downloadedByte) {
logger.info(`${chalk.green(`wait... ${downloadedByte}`)}`, {
session,
type: 'browser'
});
}
if (totalBytes) {
logger.info(`${chalk.green(`Total Bytes ${totalBytes}`)}`, {
session,
type: 'browser-total'
});
}
})
.then((revisionInfo) => {
logger.info(`${chalk.green(`Chromium Finished result`)}`, {
session,
type: 'browser'
});
logger.info(`${chalk.green(`Chromium completed result`)}`, {
session,
type: 'browser-total'
});
extras = {
...extras,
executablePath: revisionInfo.executablePath
};
puppeteerConfig.chromiumArgs.push(`--single-process`);
})
.catch((e) => {
logger.info(`${chalk.red(`Error chromium: ${e}`)}`, {
session
});
extras = {};
});
} else {
console.log('Chrome not found, using chromium');
logger.info(`${chalk.red('Chrome not found, using chromium')}`, {
session
});
extras = {};
}
}

if (options.multidevice) {
const folderSession = path.join(
path.resolve(
process.cwd(),
options.mkdirFolderToken,
options.folderNameToken,
session
)
);

const folderMulidevice = path.join(
path.resolve(
process.cwd(),
options.mkdirFolderToken,
options.folderNameToken
)
);

if (!fs.existsSync(folderMulidevice)) {
fs.mkdirSync(folderMulidevice, {
recursive: true
});
}

fs.chmodSync(folderMulidevice, '777');

options.puppeteerOptions = {
userDataDir: folderSession
};

puppeteerConfig.chromiumArgs.push(`--user-data-dir=${folderSession}`);
}

// Use stealth plugin to avoid being detected as a bot
puppeteer.use(StealthPlugin());

Expand All @@ -156,7 +245,10 @@ export async function initBrowser(
.then((e) => {
browser = e;
})
.catch(() => {
.catch((e) => {
logger.info(`${chalk.red(`Error connect: ${e}`)}`, {
session
});
browser = 'connect';
});
} else {
Expand All @@ -173,7 +265,10 @@ export async function initBrowser(
.then((e) => {
browser = e;
})
.catch(() => {
.catch((e) => {
logger.info(`${chalk.red(`Error launch: ${e}`)}`, {
session
});
browser = 'launch';
});
}
Expand All @@ -183,13 +278,13 @@ export async function initBrowser(
export async function getWhatsappPage(
browser: Browser | BrowserContext
): Promise<Page> {
const pages = await browser.pages();
const pages = await browser.pages().catch();

if (pages.length) {
return pages[0];
}

return await browser.newPage();
return await browser.newPage().catch();
}

/**
Expand Down
45 changes: 17 additions & 28 deletions src/controllers/initializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,19 +162,6 @@ export async function create(
options = sessionOrOption;
}
let browserToken: any;
if (options?.multidevice != false) {
const dirPath = `./${defaultOptions.folderNameToken}/${session}`;

let existFile = fs.existsSync(dirPath + '.data.json');

if (existFile) {
fs.unlinkSync(dirPath + '.data.json');
}

defaultOptions.puppeteerOptions = {
userDataDir: dirPath
};
}

const mergedOptions = { ...defaultOptions, ...options };

Expand All @@ -190,7 +177,7 @@ export async function create(
logger.info('Initializing browser wss...', { session });
}

const browser = await initBrowser(session, mergedOptions);
const browser = await initBrowser(session, mergedOptions, logger);
// Erro of connect wss
if (typeof browser === 'string' && browser === 'connect') {
logger.info('Error when try to connect ' + mergedOptions.browserWS, {
Expand Down Expand Up @@ -370,21 +357,23 @@ export async function create(
console.log(`\nDebug: \x1b[34m${debugURL}\x1b[0m`);
}
await page.waitForSelector('#app .two', { visible: true }).catch(() => {});
await page.waitForFunction(
() => {
if (
window.Store &&
window.Store.WidFactory &&
window.Store.WidFactory.createWid
) {
return true;
await page
.waitForFunction(
() => {
if (
window.Store &&
window.Store.WidFactory &&
window.Store.WidFactory.createWid
) {
return true;
}
},
{
timeout: 0,
polling: 100
}
},
{
timeout: 0,
polling: 100
}
);
)
.catch(() => {});

return client;
}
Expand Down

0 comments on commit 4f8fe94

Please sign in to comment.