File size: 8,405 Bytes
4c34106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/*
 * This file is part of WPPConnect.
 *
 * WPPConnect is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * WPPConnect is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with WPPConnect.  If not, see <https://www.gnu.org/licenses/>.
 */

import * as fs from 'fs';
import * as path from 'path';
import { Browser } from 'puppeteer';
import sanitize from 'sanitize-filename';
import {
  CatchQRCallback,
  CreateOptions,
  LinkByCodeCallback,
  LoadingScreenCallback,
  StatusFindCallback,
} from '../api/model/initializer';
import { Whatsapp } from '../api/whatsapp';
import { CreateConfig, defaultOptions } from '../config/create-config';
import { SessionToken } from '../token-store';
import { defaultLogger } from '../utils/logger';
import { sleep } from '../utils/sleep';
import { getOrCreatePage, initBrowser } from './browser';
import { checkUpdates, welcomeScreen } from './welcome';

process.on(
  'unhandledRejection',
  (reason: Error | any, promise: Promise<any>) => {
    let message = 'Unhandled Rejection: ';
    if (reason instanceof Error) {
      if (reason.stack) {
        message += reason.stack;
      } else {
        message += reason.toString();
      }
    } else {
      message += JSON.stringify(reason);
    }

    defaultLogger.error(message);
  }
);

/**
 * Start the bot
 * @returns Whatsapp page, with this parameter you will be able to access the bot functions
 */
export async function create(createOption: CreateOptions): Promise<Whatsapp>;
/**
 * Start the bot
 * 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".
 * @returns Whatsapp page, with this parameter you will be able to access the bot functions
 * @deprecated Deprecated in favor of create with {@link CreateOptions} (e.g., wppconnect.create({session: 'test'})).
 */
export async function create(
  sessionName: string,
  catchQR?: CatchQRCallback,
  statusFind?: StatusFindCallback,
  onLoadingScreen?: LoadingScreenCallback,
  catchLinkCode?: LinkByCodeCallback,
  options?: CreateConfig,
  browserSessionToken?: SessionToken
): Promise<Whatsapp>;

export async function create(
  sessionOrOption: string | CreateOptions,
  catchQR?: CatchQRCallback,
  statusFind?: StatusFindCallback,
  onLoadingScreen?: LoadingScreenCallback,
  catchLinkCode?: LinkByCodeCallback,
  options?: CreateConfig,
  browserSessionToken?: SessionToken
): Promise<Whatsapp> {
  let session = 'session';
  let usingDeprecatedCreate = false;

  if (
    typeof sessionOrOption === 'string' &&
    sessionOrOption.replace(/\s/g, '').length
  ) {
    session = sessionOrOption.replace(/\s/g, '');

    usingDeprecatedCreate =
      typeof sessionOrOption === 'string' ||
      typeof catchQR !== 'undefined' ||
      typeof statusFind !== 'undefined' ||
      typeof options !== 'undefined' ||
      typeof browserSessionToken !== 'undefined';
  } else if (typeof sessionOrOption === 'object') {
    options = sessionOrOption;
    if (sessionOrOption.session) session = sessionOrOption.session;
    catchQR = sessionOrOption.catchQR || catchQR;
    statusFind = sessionOrOption.statusFind || statusFind;
    onLoadingScreen = sessionOrOption.onLoadingScreen || onLoadingScreen;
    catchLinkCode = sessionOrOption.catchLinkCode || catchLinkCode;

    if (!options.sessionToken) {
      options.sessionToken =
        sessionOrOption.browserSessionToken || browserSessionToken;
    }
  }

  const { onStreamModeChanged, onStreamInfoChanged } =
    sessionOrOption as CreateOptions; // Only available in new create method

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

  const logger = mergedOptions.logger;

  if (usingDeprecatedCreate) {
    logger.warn(
      'You are using deprecated create method, please use create({options}) See: https://wppconnect.io/wppconnect/pages/Getting%20Started/creating-client.html#passing-options-on-create'
    );
  }

  if (!mergedOptions.disableWelcome) {
    welcomeScreen();
  }

  if (mergedOptions.updatesLog) {
    await checkUpdates();
  }

  let browser = mergedOptions.browser;
  let page = mergedOptions.page;

  if (!browser && page) {
    // Get browser from page
    browser = page.browser();
  } else if (!browser && !page) {
    if (
      !mergedOptions.browserWS &&
      !mergedOptions.puppeteerOptions?.userDataDir
    ) {
      mergedOptions.puppeteerOptions.userDataDir = path.resolve(
        process.cwd(),
        path.join(mergedOptions.folderNameToken, sanitize(session))
      );

      if (!fs.existsSync(mergedOptions.puppeteerOptions.userDataDir)) {
        fs.mkdirSync(mergedOptions.puppeteerOptions.userDataDir, {
          recursive: true,
        });
      }
    }

    if (!mergedOptions.browserWS) {
      logger.info(
        `Using browser folder '${mergedOptions.puppeteerOptions.userDataDir}'`,
        {
          session,
          type: 'browser',
        }
      );
    }

    // Initialize new browser
    logger.info('Initializing browser...', { session, type: 'browser' });
    browser = await initBrowser(session, mergedOptions, logger).catch((e) => {
      if (mergedOptions.browserWS && mergedOptions.browserWS != '') {
        logger.error(`Error when try to connect ${mergedOptions.browserWS}`, {
          session,
          type: 'browser',
        });
      } else {
        logger.error(`Error no open browser`, {
          session,
          type: 'browser',
        });
      }
      logger.error(e.message, {
        session,
        type: 'browser',
      });
      throw e;
    });

    logger.http('checking headless...', {
      session,
      type: 'browser',
    });

    if (mergedOptions.headless) {
      logger.http('headless option is active, browser hidden', {
        session,
        type: 'browser',
      });
    } else {
      logger.http('headless option is disabled, browser visible', {
        session,
        type: 'browser',
      });
    }
  }

  if (!mergedOptions.browserWS && browser['_process']) {
    browser['_process'].once('close', () => {
      browser['isClose'] = true;
    });
  }

  (browser as Browser).on('targetdestroyed', async (target: any) => {
    if (
      typeof (browser as Browser).isConnected === 'function' &&
      !(browser as Browser).isConnected()
    ) {
      return;
    }
    const pages = await browser.pages();
    if (!pages.length) {
      browser.close().catch(() => null);
    }
  });

  (browser as Browser).on('disconnected', () => {
    if (mergedOptions.browserWS) {
      statusFind && statusFind('serverClose', session);
    } else {
      statusFind && statusFind('browserClose', session);
    }
  });

  if (!page) {
    // Initialize a page
    page = await getOrCreatePage(browser);
  }

  if (page) {
    await page.setBypassCSP(true);

    const client = new Whatsapp(page, session, mergedOptions);
    client.catchQR = catchQR;
    client.statusFind = statusFind;
    client.onLoadingScreen = onLoadingScreen;
    client.catchLinkCode = catchLinkCode;

    if (onStreamModeChanged) {
      client.onStreamModeChanged(onStreamModeChanged);
    }
    if (onStreamInfoChanged) {
      client.onStreamInfoChanged(onStreamInfoChanged);
    }

    await client.start();

    if (mergedOptions.waitForLogin) {
      const isLogged = await client.waitForLogin();
      if (!isLogged) {
        throw new Error('Not Logged');
      }

      let waitLoginPromise = null;
      client.onStateChange(async (state) => {
        const connected = await page.evaluate(() => WPP.conn.isRegistered());
        if (!connected) {
          await sleep(2000);

          if (!waitLoginPromise) {
            waitLoginPromise = client
              .waitForLogin()
              .catch(() => {})
              .finally(() => {
                waitLoginPromise = null;
              });
          }
          await waitLoginPromise;
        }
      });
    }

    return client;
  }
}