Skip to content

Commit

Permalink
feat: Loading Screen callback function with percent and message (#1218)
Browse files Browse the repository at this point in the history
* loading screen

* browser.ts lint fix
  • Loading branch information
tonbotfy committed Jul 28, 2022
1 parent 408e71e commit 1a11117
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 4 deletions.
3 changes: 3 additions & 0 deletions docs/getting-started/creating-client.md
Expand Up @@ -46,6 +46,9 @@ wppconnect.create({
//Create session wss return "serverClose" case server for close
console.log('Session name: ', session);
},
onLoadingScreen: (percent, message) => {
console.log('LOADING_SCREEN', percent, message);
},
headless: true, // Headless chrome
devtools: false, // Open devtools by default
useChrome: true, // If false will use Chromium instance
Expand Down
7 changes: 6 additions & 1 deletion examples/bot-functions/index.js
Expand Up @@ -17,7 +17,12 @@
const wppconnect = require('../../dist');

wppconnect
.create()
.create({
session: 'teste',
onLoadingScreen: (percent, message) => {
console.log('LOADING_SCREEN', percent, message);
},
})
.then((client) => start(client))
.catch((erro) => {
console.log(erro);
Expand Down
12 changes: 10 additions & 2 deletions src/api/layers/host.layer.ts
Expand Up @@ -31,7 +31,12 @@ import {
import { sleep } from '../../utils/sleep';
import { defaultLogger, LogLevel } from '../../utils/logger';
import { Logger } from 'winston';
import { CatchQRCallback, HostDevice, StatusFindCallback } from '../model';
import {
CatchQRCallback,
HostDevice,
LoadingScreenCallback,
StatusFindCallback,
} from '../model';
import {
FileTokenStore,
isValidSessionToken,
Expand All @@ -50,6 +55,8 @@ export class HostLayer {
protected autoCloseCalled = false;
protected statusFind?: StatusFindCallback = null;

public onLoadingScreen?: LoadingScreenCallback = null;

constructor(public page: Page, session?: string, options?: CreateConfig) {
this.session = session;
this.options = { ...defaultOptions, ...options };
Expand Down Expand Up @@ -122,7 +129,8 @@ export class HostLayer {
this.page,
sessionToken,
clear,
this.options.whatsappVersion
this.options.whatsappVersion,
this.onLoadingScreen
);

this.page.on('load', () => {
Expand Down
10 changes: 10 additions & 0 deletions src/api/model/initializer.ts
Expand Up @@ -36,6 +36,11 @@ export type StatusFindCallback = (
session: string
) => void;

/**
* A callback will be received, informing data as percentage and loading screen message
*/
export type LoadingScreenCallback = (percent: number, message: string) => void;

export interface CreateOptions extends CreateConfig {
/**
* You must pass a string type parameter, this parameter will be the name of the client's session. If the parameter is not passed, the section name will be "session".
Expand All @@ -49,6 +54,11 @@ export interface CreateOptions extends CreateConfig {
* A callback will be received, informing the customer's status
*/
statusFind?: StatusFindCallback;

/**
* A callback will be received, informing data as percentage and loading screen message
*/
onLoadingScreen?: LoadingScreenCallback;
/**
* Pass the session token information you can receive this token with the await client.getSessionTokenBrowser () function
* @deprecated in favor of `sessionToken`
Expand Down
63 changes: 62 additions & 1 deletion src/controllers/browser.ts
Expand Up @@ -31,6 +31,7 @@ import { useragentOverride } from '../config/WAuserAgente';
import { WebSocketTransport } from './websocket';
import { Logger } from 'winston';
import { SessionToken } from '../token-store';
import { LoadingScreenCallback } from '../api/model';

export async function unregisterServiceWorker(page: Page) {
await page.evaluateOnNewDocument(() => {
Expand Down Expand Up @@ -84,7 +85,8 @@ export async function initWhatsapp(
page: Page,
token?: SessionToken,
clear = true,
version?: string
version?: string,
onLoadingScreenCallBack?: LoadingScreenCallback
) {
await page.setUserAgent(useragentOverride);

Expand All @@ -103,9 +105,68 @@ export async function initWhatsapp(
})
.catch(() => {});

await onLoadingScreen(page, onLoadingScreenCallBack);

return page;
}

let lastPercent = null;
let lastPercentMessage = null;
export async function onLoadingScreen(
page: Page,
onLoadingScreenCallBack?: LoadingScreenCallback
) {
await page.evaluate(`function getElementByXpath(path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}`);

await page.exposeFunction(
'loadingScreen',
async (percent: number, message: string) => {
if (lastPercent !== percent || lastPercentMessage !== message) {
onLoadingScreenCallBack && onLoadingScreenCallBack(percent, message);
lastPercent = percent;
lastPercentMessage = message;
}
}
);

await page.evaluate(
function (selectors) {
let observer = new MutationObserver(function () {
let window2: any = window;

let progressBar = window2.getElementByXpath(selectors.PROGRESS);
let progressMessage = window2.getElementByXpath(
selectors.PROGRESS_MESSAGE
);

if (progressBar) {
if (
this.lastPercent !== progressBar.value ||
this.lastPercentMessage !== progressMessage.innerText
) {
window2.loadingScreen(progressBar.value, progressMessage.innerText);
this.lastPercent = progressBar.value;
this.lastPercentMessage = progressMessage.innerText;
}
}
});

observer.observe(document, {
attributes: true,
childList: true,
characterData: true,
subtree: true,
});
},
{
PROGRESS: "//*[@id='app']/div/div/div[2]/progress",
PROGRESS_MESSAGE: "//*[@id='app']/div/div/div[3]",
}
);
}

export async function injectApi(page: Page) {
const injected = await page
.evaluate(() => {
Expand Down
5 changes: 5 additions & 0 deletions src/controllers/initializer.ts
Expand Up @@ -24,6 +24,7 @@ import { Browser } from 'puppeteer';
import {
CatchQRCallback,
CreateOptions,
LoadingScreenCallback,
StatusFindCallback,
} from '../api/model/initializer';
import { SessionToken } from '../token-store';
Expand Down Expand Up @@ -65,6 +66,7 @@ export async function create(
sessionName: string,
catchQR?: CatchQRCallback,
statusFind?: StatusFindCallback,
onLoadingScreen?: LoadingScreenCallback,
options?: CreateConfig,
browserSessionToken?: SessionToken
): Promise<Whatsapp>;
Expand All @@ -73,6 +75,7 @@ export async function create(
sessionOrOption: string | CreateOptions,
catchQR?: CatchQRCallback,
statusFind?: StatusFindCallback,
onLoadingScreen?: LoadingScreenCallback,
options?: CreateConfig,
browserSessionToken?: SessionToken
): Promise<Whatsapp> {
Expand All @@ -96,6 +99,7 @@ export async function create(
session = sessionOrOption.session;
catchQR = sessionOrOption.catchQR || catchQR;
statusFind = sessionOrOption.statusFind || statusFind;
onLoadingScreen = sessionOrOption.onLoadingScreen || onLoadingScreen;

if (!options.sessionToken) {
options.sessionToken =
Expand Down Expand Up @@ -227,6 +231,7 @@ export async function create(

if (page) {
const client = new Whatsapp(page, session, mergedOptions);
client.onLoadingScreen = onLoadingScreen;

if (mergedOptions.waitForLogin) {
const isLogged = await client.waitForLogin(catchQR, statusFind);
Expand Down

0 comments on commit 1a11117

Please sign in to comment.