Skip to content

Commit

Permalink
fix: Fixed CPU and memory usage
Browse files Browse the repository at this point in the history
  • Loading branch information
edgardmessias committed Dec 1, 2020
1 parent fec67ca commit b439abf
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 65 deletions.
17 changes: 13 additions & 4 deletions src/api/layers/host.layer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ export class HostLayer {

while (true) {
const result = await this.getQrCode();
if (!result || !result.urlCode) {
if (!result?.urlCode) {
break;
}
if (urlCode !== result.urlCode) {
Expand All @@ -241,6 +241,16 @@ export class HostLayer {
}
}

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,
Expand All @@ -266,6 +276,7 @@ export class HostLayer {
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);
Expand All @@ -289,9 +300,7 @@ export class HostLayer {
// Wait for interface update
await sleep(200);
this.spin('Checking phone is connected...');
const inChat = await isInsideChat(this.page)
.toPromise()
.catch(() => false);
const inChat = await this.waitForInChat();

if (!inChat) {
this.spin('Phone not connected', 'fail');
Expand Down
120 changes: 65 additions & 55 deletions src/controllers/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,73 +63,83 @@ import { CreateConfig } from '../config/create-config';
import { ScrapQrcode } from '../api/model/qrcode';
import { tokenSession } from '../config/tokenSession.config';

export const getInterfaceStatus = async (
waPage: puppeteer.Page
): Promise<string | null> => {
return await waPage
.waitForFunction(
() => {
const elLoginWrapper = document.querySelector(
'body > div > div > .landing-wrapper'
);
const elQRCodeCanvas = document.querySelector('canvas');
if (elLoginWrapper && elQRCodeCanvas) {
return 'UNPAIRED';
}

const streamStatus =
window['Store'] &&
window['Store'].Stream &&
window['Store'].Stream.displayInfo;
if (['PAIRING', 'RESUMING'].includes(streamStatus)) {
return 'PAIRING';
}
const elChat = document.querySelector('.app,.two') as HTMLDivElement;
if (elChat && elChat.attributes && elChat.tabIndex) {
return 'CONNECTED';
}
return false;
},
{
timeout: 0,
polling: 100,
}
)
.then(async (element) => {
return await element.evaluate((a) => a);
})
.catch(() => null);
};

/**
* Validates if client is authenticated
* @returns true if is authenticated, false otherwise
* @param waPage
*/
export const isAuthenticated = async (waPage: puppeteer.Page) => {
try {
return merge(
needsToScan(waPage),
isInsideChat(waPage),
isConnectingToPhone(waPage)
)
.pipe(take(1))
.toPromise();
} catch (e) {}
const status = await getInterfaceStatus(waPage);
if (typeof status !== 'string') {
return null;
}

return ['CONNECTED', 'PAIRING'].includes(status);
};

export const needsToScan = (waPage: puppeteer.Page) => {
return from(
waPage
.waitForSelector('body > div > div > .landing-wrapper', {
timeout: 0,
})
.then(() => false)
.catch(() => null)
);
export const needsToScan = async (waPage: puppeteer.Page) => {
const status = await getInterfaceStatus(waPage);
if (typeof status !== 'string') {
return null;
}

return status === 'UNPAIRED';
};

export const isInsideChat = (waPage: puppeteer.Page) => {
return from(
waPage
.waitForFunction(
`
(document.getElementsByClassName('app')[0] &&
document.getElementsByClassName('app')[0].attributes &&
!!document.getElementsByClassName('app')[0].attributes.tabindex) ||
(document.getElementsByClassName('two')[0] &&
document.getElementsByClassName('two')[0].attributes &&
!!document.getElementsByClassName('two')[0].attributes.tabindex)
`,
{
timeout: 0,
}
)
.then(() => true)
.catch(() => null)
);
export const isInsideChat = async (waPage: puppeteer.Page) => {
const status = await getInterfaceStatus(waPage);
if (typeof status !== 'string') {
return null;
}

return status === 'CONNECTED';
};

export const isConnectingToPhone = (waPage: puppeteer.Page) => {
return from(
waPage
.waitForFunction(
`
window['Store'] &&
window['Store'].Stream &&
['PAIRING', 'NORMAL'].includes(
window['Store'].Stream.displayInfo
)
`,
{
timeout: 0,
}
)
.then(() => true)
.catch(() => null)
);
export const isConnectingToPhone = async (waPage: puppeteer.Page) => {
const status = await getInterfaceStatus(waPage);
if (typeof status !== 'string') {
return null;
}

return status === 'PAIRING';
};

export async function asciiQr(code: string): Promise<string> {
Expand Down
13 changes: 7 additions & 6 deletions src/controllers/initializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import { initWhatsapp, initBrowser } from './browser';
import { checkUpdates, welcomeScreen } from './welcome';
import { getSpinnies } from '../utils/spinnies';
import { SocketState } from '../api/model/enum';
import { deleteFiles } from '../api/helpers';

/**
* Start the bot
Expand Down Expand Up @@ -182,12 +183,16 @@ export async function create(
saveToken(waPage, session, mergedOptions).catch((e) => {
console.log(e);
});
}, 100);
}, 1000);
}
});
}

if (mergedOptions.waitForLogin) {
const isLogged = await client.waitForLogin(catchQR, statusFind);
if (!isLogged) {
throw 'Not Logged';
}
client.onStateChange((state) => {
if (
state === SocketState.UNPAIRED ||
Expand All @@ -196,14 +201,10 @@ export async function create(
if (statusFind) {
statusFind('desconnectedMobile', session);
}
deleteFiles(mergedOptions, session, spinnies);
client.waitForLogin(catchQR, statusFind).catch(() => {});
}
});

const isLogged = await client.waitForLogin(catchQR, statusFind);
if (!isLogged) {
throw 'Not Logged';
}
}

if (mergedOptions.debug) {
Expand Down

0 comments on commit b439abf

Please sign in to comment.