@open-wa/wa-automate 4.24.2 → 4.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,6 @@
1
1
  import { Client } from '../api/Client';
2
2
  import { ConfigObject } from '../api/model/index';
3
- import { Spin } from './events';
4
- import { SessionInfo } from '../api/model/sessionInfo';
5
- import { Page } from 'puppeteer';
3
+ export declare const pkg: any, configWithCases: any, timeout: (ms: number) => Promise<unknown>;
6
4
  export declare let screenshot: any;
7
5
  /**
8
6
  * Used to initialize the client session.
@@ -22,36 +20,3 @@ export declare let screenshot: any;
22
20
  * @param config ConfigObject] The extended custom configuration
23
21
  */
24
22
  export declare function create(config?: ConfigObject): Promise<Client>;
25
- /**
26
- * @private
27
- */
28
- export declare function getPatch(config: ConfigObject, spinner?: Spin, sessionInfo?: SessionInfo): Promise<{
29
- data: any;
30
- tag: string;
31
- }>;
32
- /**
33
- * @private
34
- * @param page
35
- * @param spinner
36
- */
37
- export declare function injectLivePatch(page: Page, patch: {
38
- data: any;
39
- tag: string;
40
- }, spinner?: Spin): Promise<void>;
41
- /**
42
- * @private
43
- */
44
- export declare function getAndInjectLivePatch(page: Page, spinner?: Spin, preloadedPatch?: {
45
- data: any;
46
- tag: string;
47
- }, config?: ConfigObject, sessionInfo?: SessionInfo): Promise<void>;
48
- /**
49
- * @private
50
- */
51
- export declare function getLicense(config: ConfigObject, me: {
52
- _serialized: string;
53
- }, debugInfo: SessionInfo, spinner?: Spin): Promise<string | false>;
54
- export declare function earlyInjectionCheck(page: Page): Promise<(page: Page) => boolean>;
55
- export declare function getAndInjectLicense(page: Page, config: ConfigObject, me: {
56
- _serialized: string;
57
- }, debugInfo: SessionInfo, spinner?: Spin, preloadedLicense?: string | false): Promise<boolean>;
@@ -42,12 +42,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
42
42
  return (mod && mod.__esModule) ? mod : { "default": mod };
43
43
  };
44
44
  Object.defineProperty(exports, "__esModule", { value: true });
45
- exports.getAndInjectLicense = exports.earlyInjectionCheck = exports.getLicense = exports.getAndInjectLivePatch = exports.injectLivePatch = exports.getPatch = exports.create = exports.screenshot = void 0;
45
+ exports.create = exports.screenshot = exports.timeout = exports.configWithCases = exports.pkg = void 0;
46
46
  const fs = __importStar(require("fs"));
47
47
  const boxen_1 = __importDefault(require("boxen"));
48
48
  const os_name_1 = __importDefault(require("os-name"));
49
49
  const update_notifier_1 = __importDefault(require("update-notifier"));
50
- const crypto = __importStar(require("crypto"));
51
50
  const Client_1 = require("../api/Client");
52
51
  const index_1 = require("../api/model/index");
53
52
  const path = __importStar(require("path"));
@@ -59,13 +58,14 @@ const tree_kill_1 = __importDefault(require("tree-kill"));
59
58
  const cfonts_1 = __importDefault(require("cfonts"));
60
59
  const tools_1 = require("../utils/tools");
61
60
  const crypto_1 = require("crypto");
62
- const init_patch_1 = require("./init_patch");
63
61
  const fs_extra_1 = require("fs-extra");
64
62
  const pico_s3_1 = require("pico-s3");
65
- const pkg = fs_extra_1.readJsonSync(path.join(__dirname, '../../package.json')), configWithCases = fs_extra_1.readJsonSync(path.join(__dirname, '../../bin/config-schema.json')), timeout = (ms) => {
63
+ const init_patch_1 = require("./init_patch");
64
+ const patch_manager_1 = require("./patch_manager");
65
+ const timeout = (ms) => {
66
66
  return new Promise(resolve => setTimeout(resolve, ms, 'timeout'));
67
67
  };
68
- let axios;
68
+ exports.pkg = fs_extra_1.readJsonSync(path.join(__dirname, '../../package.json')), exports.configWithCases = fs_extra_1.readJsonSync(path.join(__dirname, '../../bin/config-schema.json')), exports.timeout = timeout;
69
69
  /**
70
70
  * Used to initialize the client session.
71
71
  *
@@ -97,11 +97,11 @@ function create(config = {}) {
97
97
  }
98
98
  if (!(config === null || config === void 0 ? void 0 : config.skipUpdateCheck) || (config === null || config === void 0 ? void 0 : config.keepUpdated)) {
99
99
  notifier = yield update_notifier_1.default({
100
- pkg,
100
+ pkg: exports.pkg,
101
101
  updateCheckInterval: 0
102
102
  });
103
103
  notifier.notify();
104
- if ((notifier === null || notifier === void 0 ? void 0 : notifier.update) && (config === null || config === void 0 ? void 0 : config.keepUpdated) && (notifier === null || notifier === void 0 ? void 0 : notifier.update.latest) !== pkg.version) {
104
+ if ((notifier === null || notifier === void 0 ? void 0 : notifier.update) && (config === null || config === void 0 ? void 0 : config.keepUpdated) && (notifier === null || notifier === void 0 ? void 0 : notifier.update.latest) !== exports.pkg.version) {
105
105
  console.log('UPDATING @OPEN-WA');
106
106
  const crossSpawn = yield Promise.resolve().then(() => __importStar(require('cross-spawn')));
107
107
  const result = crossSpawn.sync('npm', ['i', '@open-wa/wa-automate'], { stdio: 'inherit' });
@@ -121,7 +121,7 @@ function create(config = {}) {
121
121
  }
122
122
  if (config === null || config === void 0 ? void 0 : config.inDocker) {
123
123
  //try to infer config variables from process.env
124
- config = Object.assign(Object.assign({}, config), tools_1.getConfigFromProcessEnv(configWithCases));
124
+ config = Object.assign(Object.assign({}, config), tools_1.getConfigFromProcessEnv(exports.configWithCases));
125
125
  config.chromiumArgs = (config === null || config === void 0 ? void 0 : config.chromiumArgs) || [];
126
126
  customUserAgent = config.customUserAgent;
127
127
  }
@@ -136,8 +136,8 @@ function create(config = {}) {
136
136
  });
137
137
  console.log((config === null || config === void 0 ? void 0 : config.disableSpins) ? boxen_1.default([
138
138
  `@open-wa/wa-automate `,
139
- `${pkg.description}`,
140
- `Version: ${pkg.version} `,
139
+ `${exports.pkg.description}`,
140
+ `Version: ${exports.pkg.version} `,
141
141
  `Check out the latest changes: https://github.com/open-wa/wa-automate-nodejs#latest-changes `,
142
142
  ].join('\n'), { padding: 1, borderColor: 'yellow', borderStyle: 'bold' }) : prettyFont.string);
143
143
  if (config === null || config === void 0 ? void 0 : config.popup) {
@@ -152,7 +152,7 @@ function create(config = {}) {
152
152
  if (typeof config === 'string')
153
153
  console.error("AS OF VERSION 3+ YOU CAN NO LONGER SET THE SESSION ID AS THE FIRST PARAMETER OF CREATE. CREATE CAN ONLY TAKE A CONFIG OBJECT. IF YOU STILL HAVE CONFIGS AS A SECOND PARAMETER, THEY WILL HAVE NO EFFECT! PLEASE SEE DOCS.");
154
154
  spinner.start('Starting');
155
- spinner.succeed(`Version: ${pkg.version}`);
155
+ spinner.succeed(`Version: ${exports.pkg.version}`);
156
156
  spinner.info(`Initializing WA`);
157
157
  /**
158
158
  * Check if the IGNORE folder exists, therefore, assume that the session is MD.
@@ -190,11 +190,11 @@ function create(config = {}) {
190
190
  if (msg.type() === 'error' && !msg.text().includes('apify') && !msg.text().includes('crashlogs'))
191
191
  yield exports.screenshot(waPage);
192
192
  }));
193
- const WA_AUTOMATE_VERSION = `${pkg.version}${(notifier === null || notifier === void 0 ? void 0 : notifier.update) && ((notifier === null || notifier === void 0 ? void 0 : notifier.update.latest) !== pkg.version) ? ` UPDATE AVAILABLE: ${notifier === null || notifier === void 0 ? void 0 : notifier.update.latest}` : ''}`;
193
+ const WA_AUTOMATE_VERSION = `${exports.pkg.version}${(notifier === null || notifier === void 0 ? void 0 : notifier.update) && ((notifier === null || notifier === void 0 ? void 0 : notifier.update.latest) !== exports.pkg.version) ? ` UPDATE AVAILABLE: ${notifier === null || notifier === void 0 ? void 0 : notifier.update.latest}` : ''}`;
194
194
  yield waPage.waitForFunction('window.Debug!=undefined && window.Debug.VERSION!=undefined');
195
195
  //@ts-ignore
196
196
  const WA_VERSION = yield waPage.evaluate(() => window.Debug ? window.Debug.VERSION : 'I think you have been TOS_BLOCKed');
197
- const canInjectEarly = yield earlyInjectionCheck(waPage);
197
+ const canInjectEarly = yield patch_manager_1.earlyInjectionCheck(waPage);
198
198
  const attemptingReauth = yield waPage.evaluate(`!!(localStorage['WAToken2'] || localStorage['last-wid-md'])`);
199
199
  let debugInfo = {
200
200
  WA_VERSION,
@@ -229,7 +229,7 @@ function create(config = {}) {
229
229
  const authRace = [];
230
230
  authRace.push(auth_1.isAuthenticated(waPage).catch(() => { }));
231
231
  if ((config === null || config === void 0 ? void 0 : config.authTimeout) !== 0) {
232
- authRace.push(timeout((config.authTimeout || config.multiDevice ? 120 : 60) * 1000));
232
+ authRace.push(exports.timeout((config.authTimeout || config.multiDevice ? 120 : 60) * 1000));
233
233
  }
234
234
  const authenticated = yield Promise.race(authRace);
235
235
  if (authenticated === 'NUKE' && !(config === null || config === void 0 ? void 0 : config.ignoreNuke)) {
@@ -249,11 +249,11 @@ function create(config = {}) {
249
249
  * Attempt to preload the license
250
250
  */
251
251
  const earlyWid = yield waPage.evaluate(`(localStorage["last-wid"] || '').replace(/"/g,"")`);
252
- const licensePromise = getLicense(config, {
252
+ const licensePromise = patch_manager_1.getLicense(config, {
253
253
  _serialized: earlyWid
254
254
  }, debugInfo, spinner);
255
255
  if (authenticated == 'timeout') {
256
- const outOfReach = yield Promise.race([auth_1.phoneIsOutOfReach(waPage), timeout(20 * 1000)]);
256
+ const outOfReach = yield Promise.race([auth_1.phoneIsOutOfReach(waPage), exports.timeout(20 * 1000)]);
257
257
  spinner.emit(outOfReach && outOfReach !== 'timeout' ? 'appOffline' : 'authTimeout');
258
258
  spinner.fail(outOfReach && outOfReach !== 'timeout' ? 'Authentication timed out. Please open the app on the phone. Shutting down' : 'Authentication timed out. Shutting down. Consider increasing authTimeout config variable: https://open-wa.github.io/wa-automate-nodejs/interfaces/configobject.html#authtimeout');
259
259
  yield kill(waPage);
@@ -272,7 +272,7 @@ function create(config = {}) {
272
272
  let to = ((config === null || config === void 0 ? void 0 : config.qrTimeout) || 60) * 1000;
273
273
  if (config === null || config === void 0 ? void 0 : config.multiDevice)
274
274
  to = to * 2;
275
- race.push(timeout(to));
275
+ race.push(exports.timeout(to));
276
276
  }
277
277
  const result = yield Promise.race(race);
278
278
  if (result === "MULTI_DEVICE_DETECTED" && !(config === null || config === void 0 ? void 0 : config.multiDevice)) {
@@ -308,7 +308,7 @@ function create(config = {}) {
308
308
  //check if page is valid after 5 seconds
309
309
  spinner.start('Checking if session is valid');
310
310
  if (config === null || config === void 0 ? void 0 : config.safeMode)
311
- yield timeout(5000);
311
+ yield exports.timeout(5000);
312
312
  }
313
313
  //@ts-ignore
314
314
  const VALID_SESSION = yield waPage.evaluate(() => window.Store && window.Store.Msg ? true : false);
@@ -316,7 +316,7 @@ function create(config = {}) {
316
316
  /**
317
317
  * Session is valid, attempt to preload patches
318
318
  */
319
- const patchPromise = getPatch(config, spinner, debugInfo);
319
+ const patchPromise = patch_manager_1.getPatch(config, spinner, debugInfo);
320
320
  spinner.succeed('Client is ready');
321
321
  const localStorage = JSON.parse(yield waPage.evaluate(() => {
322
322
  return JSON.stringify(window.localStorage);
@@ -373,7 +373,7 @@ function create(config = {}) {
373
373
  }
374
374
  //patch issues with wapi.js
375
375
  if (!(config === null || config === void 0 ? void 0 : config.skipPatches)) {
376
- yield getAndInjectLivePatch(waPage, spinner, yield patchPromise, config, debugInfo);
376
+ yield patch_manager_1.getAndInjectLivePatch(waPage, spinner, yield patchPromise, config, debugInfo);
377
377
  debugInfo.OW_KEY = yield waPage.evaluate(`window.o()`);
378
378
  }
379
379
  if ((config === null || config === void 0 ? void 0 : config.skipBrokenMethodsCheck) !== true)
@@ -392,7 +392,7 @@ function create(config = {}) {
392
392
  const client = new Client_1.Client(waPage, config, debugInfo);
393
393
  const { me } = yield client.getMe();
394
394
  if ((config === null || config === void 0 ? void 0 : config.licenseKey) || me._serialized !== earlyWid) {
395
- yield getAndInjectLicense(waPage, config, me, debugInfo, spinner, me._serialized !== earlyWid ? false : yield licensePromise);
395
+ yield patch_manager_1.getAndInjectLicense(waPage, config, me, debugInfo, spinner, me._serialized !== earlyWid ? false : yield licensePromise);
396
396
  }
397
397
  spinner.info("Finalizing web session...");
398
398
  yield init_patch_1.injectInitPatch(waPage);
@@ -454,147 +454,3 @@ const kill = (p) => __awaiter(void 0, void 0, void 0, function* () {
454
454
  tree_kill_1.default(pid, 'SIGKILL');
455
455
  }
456
456
  });
457
- /**
458
- * @private
459
- */
460
- function getPatch(config, spinner, sessionInfo) {
461
- return __awaiter(this, void 0, void 0, function* () {
462
- const ghUrl = `https://raw.githubusercontent.com/open-wa/wa-automate-nodejs/master/patches.json`;
463
- const hasSpin = !!spinner;
464
- /**
465
- * Undo below comment when a githack alternative is found.
466
- */
467
- const patchesBaseUrl = (config === null || config === void 0 ? void 0 : config.cachedPatch) ? ghUrl : pkg.patches;
468
- const patchesUrl = patchesBaseUrl + `?wv=${sessionInfo.WA_VERSION}&wav=${sessionInfo.WA_AUTOMATE_VERSION}`;
469
- if (!spinner)
470
- spinner = new events_1.Spin(config.sessionId, "FETCH_PATCH", config.disableSpins, true);
471
- spinner === null || spinner === void 0 ? void 0 : spinner.start(`Downloading ${(config === null || config === void 0 ? void 0 : config.cachedPatch) ? 'cached ' : ''}patches from ${patchesBaseUrl}`, hasSpin ? undefined : 2);
472
- if (!axios)
473
- axios = yield Promise.resolve().then(() => __importStar(require('axios')));
474
- const START = Date.now();
475
- const { data, headers } = yield axios.get(patchesUrl).catch(() => {
476
- spinner === null || spinner === void 0 ? void 0 : spinner.info('Downloading patches. Retrying.');
477
- return axios.get(`${ghUrl}?v=${Date.now()}`);
478
- });
479
- const END = Date.now();
480
- if (!headers['etag']) {
481
- spinner === null || spinner === void 0 ? void 0 : spinner.info('Generating patch hash');
482
- headers['etag'] = crypto.createHash('md5').update(typeof data === 'string' ? data : JSON.stringify(data)).digest("hex").slice(-5);
483
- }
484
- spinner === null || spinner === void 0 ? void 0 : spinner.succeed(`Downloaded patches in ${(END - START) / 1000}s`);
485
- return {
486
- data,
487
- tag: `${(headers.etag || '').replace(/"/g, '').slice(-5)}`
488
- };
489
- });
490
- }
491
- exports.getPatch = getPatch;
492
- /**
493
- * @private
494
- * @param page
495
- * @param spinner
496
- */
497
- function injectLivePatch(page, patch, spinner) {
498
- return __awaiter(this, void 0, void 0, function* () {
499
- const { data, tag } = patch;
500
- spinner === null || spinner === void 0 ? void 0 : spinner.info('Installing patches');
501
- yield Promise.all(data.map(patch => page.evaluate(`${patch}`)));
502
- spinner === null || spinner === void 0 ? void 0 : spinner.succeed(`Patches Installed: ${tag}`);
503
- });
504
- }
505
- exports.injectLivePatch = injectLivePatch;
506
- /**
507
- * @private
508
- */
509
- function getAndInjectLivePatch(page, spinner, preloadedPatch, config, sessionInfo) {
510
- return __awaiter(this, void 0, void 0, function* () {
511
- let patch = preloadedPatch;
512
- if (!patch)
513
- patch = yield getPatch(config, spinner, sessionInfo);
514
- yield injectLivePatch(page, patch, spinner);
515
- });
516
- }
517
- exports.getAndInjectLivePatch = getAndInjectLivePatch;
518
- /**
519
- * @private
520
- */
521
- function getLicense(config, me, debugInfo, spinner) {
522
- return __awaiter(this, void 0, void 0, function* () {
523
- if (!(config === null || config === void 0 ? void 0 : config.licenseKey) || !(me === null || me === void 0 ? void 0 : me._serialized))
524
- return false;
525
- if (!axios)
526
- axios = yield Promise.resolve().then(() => __importStar(require('axios')));
527
- const hasSpin = !!spinner;
528
- if (!spinner)
529
- spinner = new events_1.Spin(config.sessionId || "session", "FETCH_LICENSE", config.disableSpins, true);
530
- spinner === null || spinner === void 0 ? void 0 : spinner.start(`Fetching License: ${Array.isArray(config.licenseKey) ? config.licenseKey : config.licenseKey.indexOf("-") == -1 ? config.licenseKey.slice(-4) : config.licenseKey.split("-").slice(-1)[0]}`, hasSpin ? undefined : 2);
531
- try {
532
- const START = Date.now();
533
- const { data } = yield axios.post(pkg.licenseCheckUrl, Object.assign({ key: config.licenseKey, number: me._serialized }, debugInfo));
534
- const END = Date.now();
535
- spinner === null || spinner === void 0 ? void 0 : spinner.succeed(`Downloaded License in ${(END - START) / 1000}s`);
536
- return data;
537
- }
538
- catch (error) {
539
- spinner === null || spinner === void 0 ? void 0 : spinner.fail(`License request failed: ${error.statusCode || error.status || error.code} ${error.message}`);
540
- return false;
541
- }
542
- });
543
- }
544
- exports.getLicense = getLicense;
545
- function earlyInjectionCheck(page) {
546
- return __awaiter(this, void 0, void 0, function* () {
547
- //@ts-ignore
548
- return yield page.evaluate(() => { if (window.webpackChunkwhatsapp_web_client) {
549
- window.webpackChunkbuild = window.webpackChunkwhatsapp_web_client;
550
- }
551
- else {
552
- (function () { const f = Object.entries(window).filter(([, o]) => o && o.push && (o.push != [].push)); if (f[0]) {
553
- window.webpackChunkbuild = window[f[0][0]];
554
- } })();
555
- } return (typeof webpackChunkbuild !== "undefined"); });
556
- });
557
- }
558
- exports.earlyInjectionCheck = earlyInjectionCheck;
559
- function getAndInjectLicense(page, config, me, debugInfo, spinner, preloadedLicense) {
560
- return __awaiter(this, void 0, void 0, function* () {
561
- if (!(config === null || config === void 0 ? void 0 : config.licenseKey) || !(me === null || me === void 0 ? void 0 : me._serialized))
562
- return false;
563
- if (!axios)
564
- axios = yield Promise.resolve().then(() => __importStar(require('axios')));
565
- let l_err;
566
- let data = preloadedLicense;
567
- spinner === null || spinner === void 0 ? void 0 : spinner.info('Checking License');
568
- try {
569
- if (!data) {
570
- spinner === null || spinner === void 0 ? void 0 : spinner.info('Fethcing License...');
571
- data = yield getLicense(config, me, debugInfo, spinner);
572
- }
573
- if (data) {
574
- spinner === null || spinner === void 0 ? void 0 : spinner.info('Injecting License...');
575
- const l_success = yield page.evaluate(data => eval(data), data);
576
- if (!l_success) {
577
- spinner === null || spinner === void 0 ? void 0 : spinner.info('License injection failed. Getting error..');
578
- l_err = yield page.evaluate('window.launchError');
579
- }
580
- else {
581
- spinner === null || spinner === void 0 ? void 0 : spinner.info('License injected successfully..');
582
- const keyType = yield page.evaluate('window.KEYTYPE || false');
583
- spinner === null || spinner === void 0 ? void 0 : spinner.succeed(`License Valid${keyType ? `: ${keyType}` : ''}`);
584
- return true;
585
- }
586
- }
587
- else
588
- l_err = "The key is invalid";
589
- if (l_err) {
590
- spinner === null || spinner === void 0 ? void 0 : spinner.fail(`License issue${l_err ? `: ${l_err}` : ""}`);
591
- }
592
- return false;
593
- }
594
- catch (error) {
595
- spinner === null || spinner === void 0 ? void 0 : spinner.fail(`License request failed: ${error.statusCode || error.status || error.code} ${error.message}`);
596
- return false;
597
- }
598
- });
599
- }
600
- exports.getAndInjectLicense = getAndInjectLicense;
@@ -0,0 +1,37 @@
1
+ import { ConfigObject } from '../api/model/index';
2
+ import { Spin } from './events';
3
+ import { SessionInfo } from '../api/model/sessionInfo';
4
+ import { Page } from 'puppeteer';
5
+ /**
6
+ * @private
7
+ */
8
+ export declare function getPatch(config: ConfigObject, spinner?: Spin, sessionInfo?: SessionInfo): Promise<{
9
+ data: any;
10
+ tag: string;
11
+ }>;
12
+ /**
13
+ * @private
14
+ * @param page
15
+ * @param spinner
16
+ */
17
+ export declare function injectLivePatch(page: Page, patch: {
18
+ data: any;
19
+ tag: string;
20
+ }, spinner?: Spin): Promise<void>;
21
+ /**
22
+ * @private
23
+ */
24
+ export declare function getAndInjectLivePatch(page: Page, spinner?: Spin, preloadedPatch?: {
25
+ data: any;
26
+ tag: string;
27
+ }, config?: ConfigObject, sessionInfo?: SessionInfo): Promise<void>;
28
+ /**
29
+ * @private
30
+ */
31
+ export declare function getLicense(config: ConfigObject, me: {
32
+ _serialized: string;
33
+ }, debugInfo: SessionInfo, spinner?: Spin): Promise<string | false>;
34
+ export declare function earlyInjectionCheck(page: Page): Promise<(page: Page) => boolean>;
35
+ export declare function getAndInjectLicense(page: Page, config: ConfigObject, me: {
36
+ _serialized: string;
37
+ }, debugInfo: SessionInfo, spinner?: Spin, preloadedLicense?: string | false): Promise<boolean>;
@@ -0,0 +1,219 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
22
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
23
+ return new (P || (P = Promise))(function (resolve, reject) {
24
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
25
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
26
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
27
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
28
+ });
29
+ };
30
+ var __importDefault = (this && this.__importDefault) || function (mod) {
31
+ return (mod && mod.__esModule) ? mod : { "default": mod };
32
+ };
33
+ Object.defineProperty(exports, "__esModule", { value: true });
34
+ exports.getAndInjectLicense = exports.earlyInjectionCheck = exports.getLicense = exports.getAndInjectLivePatch = exports.injectLivePatch = exports.getPatch = void 0;
35
+ const crypto = __importStar(require("crypto"));
36
+ const events_1 = require("./events");
37
+ const initializer_1 = require("./initializer");
38
+ const axios_1 = __importDefault(require("axios"));
39
+ const fs_1 = require("fs");
40
+ const { default: PQueue } = require("p-queue");
41
+ const queue = new PQueue();
42
+ /**
43
+ * @private
44
+ */
45
+ function getPatch(config, spinner, sessionInfo) {
46
+ return __awaiter(this, void 0, void 0, function* () {
47
+ var data = null;
48
+ var headers = {};
49
+ const ghUrl = `https://raw.githubusercontent.com/open-wa/wa-automate-nodejs/master/patches.json`;
50
+ const hasSpin = !!spinner;
51
+ const patchFilePath = `${process.cwd()}/patches.ignore.data.json`;
52
+ /**
53
+ * If cachedPatch is true then search for patch in current working directory.
54
+ */
55
+ if (config === null || config === void 0 ? void 0 : config.cachedPatch) {
56
+ spinner.info('Searching for cached patch');
57
+ // open file called patches.json and read as string
58
+ if (fs_1.existsSync(patchFilePath)) {
59
+ spinner.info('Found cached patch');
60
+ const lastModifiedDate = fs_1.statSync(patchFilePath).mtimeMs;
61
+ /**
62
+ * Check if patchFilePath file is more than 1 day old
63
+ */
64
+ if ((lastModifiedDate + 86400000) < Date.now()) {
65
+ //this patch is stale.
66
+ spinner.fail('Cached patch is stale.');
67
+ }
68
+ else {
69
+ const patch = fs_1.readFileSync(patchFilePath, 'utf8');
70
+ data = JSON.parse(patch);
71
+ spinner.info('Cached patch loaded');
72
+ }
73
+ }
74
+ else
75
+ spinner.fail('Cached patch not found');
76
+ }
77
+ const freshPatchFetchPromise = () => new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
78
+ const patchesBaseUrl = (config === null || config === void 0 ? void 0 : config.ghPatch) ? ghUrl : initializer_1.pkg.patches;
79
+ const patchesUrl = patchesBaseUrl + `?wv=${sessionInfo.WA_VERSION}&wav=${sessionInfo.WA_AUTOMATE_VERSION}`;
80
+ if (!spinner)
81
+ spinner = new events_1.Spin(config.sessionId, "FETCH_PATCH", config.disableSpins, true);
82
+ spinner === null || spinner === void 0 ? void 0 : spinner.start(`Downloading ${(config === null || config === void 0 ? void 0 : config.cachedPatch) ? 'cached ' : ''}patches from ${patchesBaseUrl}`, hasSpin ? undefined : 2);
83
+ const START = Date.now();
84
+ var { data, headers } = yield axios_1.default.get(patchesUrl).catch(() => {
85
+ spinner === null || spinner === void 0 ? void 0 : spinner.info('Downloading patches. Retrying.');
86
+ return axios_1.default.get(`${ghUrl}?v=${Date.now()}`);
87
+ });
88
+ const END = Date.now();
89
+ if (!headers['etag']) {
90
+ spinner === null || spinner === void 0 ? void 0 : spinner.info('Generating patch hash');
91
+ headers['etag'] = crypto.createHash('md5').update(typeof data === 'string' ? data : JSON.stringify(data)).digest("hex").slice(-5);
92
+ }
93
+ spinner === null || spinner === void 0 ? void 0 : spinner.succeed(`Downloaded patches in ${(END - START) / 1000}s`);
94
+ if (config === null || config === void 0 ? void 0 : config.cachedPatch) {
95
+ //save patches.json to current working directory
96
+ spinner === null || spinner === void 0 ? void 0 : spinner.info('Saving patches to current working directory');
97
+ fs_1.writeFileSync(patchFilePath, JSON.stringify(data, null, 2));
98
+ spinner === null || spinner === void 0 ? void 0 : spinner.succeed('Saved patches to current working directory');
99
+ }
100
+ return resolve({
101
+ data,
102
+ tag: `${(headers.etag || '').replace(/"/g, '').slice(-5)}`
103
+ });
104
+ }));
105
+ if ((config === null || config === void 0 ? void 0 : config.cachedPatch) && data) {
106
+ queue.add(freshPatchFetchPromise);
107
+ return { data, tag: `CACHED-${(crypto.createHash('md5').update(typeof data === 'string' ? data : JSON.stringify(data)).digest("hex").slice(-5)).replace(/"/g, '').slice(-5)}` };
108
+ }
109
+ else
110
+ return yield freshPatchFetchPromise();
111
+ });
112
+ }
113
+ exports.getPatch = getPatch;
114
+ /**
115
+ * @private
116
+ * @param page
117
+ * @param spinner
118
+ */
119
+ function injectLivePatch(page, patch, spinner) {
120
+ return __awaiter(this, void 0, void 0, function* () {
121
+ const { data, tag } = patch;
122
+ spinner === null || spinner === void 0 ? void 0 : spinner.info('Installing patches');
123
+ yield Promise.all(data.map(patch => page.evaluate(`${patch}`)));
124
+ spinner === null || spinner === void 0 ? void 0 : spinner.succeed(`Patches Installed: ${tag}`);
125
+ });
126
+ }
127
+ exports.injectLivePatch = injectLivePatch;
128
+ /**
129
+ * @private
130
+ */
131
+ function getAndInjectLivePatch(page, spinner, preloadedPatch, config, sessionInfo) {
132
+ return __awaiter(this, void 0, void 0, function* () {
133
+ let patch = preloadedPatch;
134
+ if (!patch)
135
+ patch = yield getPatch(config, spinner, sessionInfo);
136
+ yield injectLivePatch(page, patch, spinner);
137
+ });
138
+ }
139
+ exports.getAndInjectLivePatch = getAndInjectLivePatch;
140
+ /**
141
+ * @private
142
+ */
143
+ function getLicense(config, me, debugInfo, spinner) {
144
+ return __awaiter(this, void 0, void 0, function* () {
145
+ if (!(config === null || config === void 0 ? void 0 : config.licenseKey) || !(me === null || me === void 0 ? void 0 : me._serialized))
146
+ return false;
147
+ const hasSpin = !!spinner;
148
+ if (!spinner)
149
+ spinner = new events_1.Spin(config.sessionId || "session", "FETCH_LICENSE", config.disableSpins, true);
150
+ spinner === null || spinner === void 0 ? void 0 : spinner.start(`Fetching License: ${Array.isArray(config.licenseKey) ? config.licenseKey : config.licenseKey.indexOf("-") == -1 ? config.licenseKey.slice(-4) : config.licenseKey.split("-").slice(-1)[0]}`, hasSpin ? undefined : 2);
151
+ try {
152
+ const START = Date.now();
153
+ const { data } = yield axios_1.default.post(initializer_1.pkg.licenseCheckUrl, Object.assign({ key: config.licenseKey, number: me._serialized }, debugInfo));
154
+ const END = Date.now();
155
+ spinner === null || spinner === void 0 ? void 0 : spinner.succeed(`Downloaded License in ${(END - START) / 1000}s`);
156
+ return data;
157
+ }
158
+ catch (error) {
159
+ spinner === null || spinner === void 0 ? void 0 : spinner.fail(`License request failed: ${error.statusCode || error.status || error.code} ${error.message}`);
160
+ return false;
161
+ }
162
+ });
163
+ }
164
+ exports.getLicense = getLicense;
165
+ function earlyInjectionCheck(page) {
166
+ return __awaiter(this, void 0, void 0, function* () {
167
+ //@ts-ignore
168
+ return yield page.evaluate(() => { if (window.webpackChunkwhatsapp_web_client) {
169
+ window.webpackChunkbuild = window.webpackChunkwhatsapp_web_client;
170
+ }
171
+ else {
172
+ (function () { const f = Object.entries(window).filter(([, o]) => o && o.push && (o.push != [].push)); if (f[0]) {
173
+ window.webpackChunkbuild = window[f[0][0]];
174
+ } })();
175
+ } return (typeof webpackChunkbuild !== "undefined"); });
176
+ });
177
+ }
178
+ exports.earlyInjectionCheck = earlyInjectionCheck;
179
+ function getAndInjectLicense(page, config, me, debugInfo, spinner, preloadedLicense) {
180
+ return __awaiter(this, void 0, void 0, function* () {
181
+ if (!(config === null || config === void 0 ? void 0 : config.licenseKey) || !(me === null || me === void 0 ? void 0 : me._serialized))
182
+ return false;
183
+ let l_err;
184
+ let data = preloadedLicense;
185
+ spinner === null || spinner === void 0 ? void 0 : spinner.info('Checking License');
186
+ try {
187
+ if (!data) {
188
+ spinner === null || spinner === void 0 ? void 0 : spinner.info('Fethcing License...');
189
+ data = yield getLicense(config, me, debugInfo, spinner);
190
+ }
191
+ if (data) {
192
+ spinner === null || spinner === void 0 ? void 0 : spinner.info('Injecting License...');
193
+ const l_success = yield page.evaluate(data => eval(data), data);
194
+ if (!l_success) {
195
+ spinner === null || spinner === void 0 ? void 0 : spinner.info('License injection failed. Getting error..');
196
+ l_err = yield page.evaluate('window.launchError');
197
+ }
198
+ else {
199
+ spinner === null || spinner === void 0 ? void 0 : spinner.info('License injected successfully..');
200
+ const keyType = yield page.evaluate('window.KEYTYPE || false');
201
+ spinner === null || spinner === void 0 ? void 0 : spinner.succeed(`License Valid${keyType ? `: ${keyType}` : ''}`);
202
+ return true;
203
+ }
204
+ }
205
+ else
206
+ l_err = "The key is invalid";
207
+ if (l_err) {
208
+ spinner === null || spinner === void 0 ? void 0 : spinner.fail(`License issue${l_err ? `: ${l_err}` : ""}`);
209
+ }
210
+ return false;
211
+ }
212
+ catch (error) {
213
+ spinner === null || spinner === void 0 ? void 0 : spinner.fail(`License request failed: ${error.statusCode || error.status || error.code} ${error.message}`);
214
+ return false;
215
+ }
216
+ });
217
+ }
218
+ exports.getAndInjectLicense = getAndInjectLicense;
219
+ // export * from './init_patch';
@@ -0,0 +1,55 @@
1
+ import { Message } from "..";
2
+ export interface CurrentDialogProps {
3
+ [k: string]: any;
4
+ }
5
+ export interface DialogState {
6
+ currentStep: number;
7
+ currentProps: any;
8
+ lastInput: any;
9
+ isComplete: boolean;
10
+ isError: boolean;
11
+ errorMessage: string;
12
+ }
13
+ export interface DialogTemplate {
14
+ "dialogId": string;
15
+ "privateOnly": boolean;
16
+ "identifier": string;
17
+ "successMessage": string;
18
+ "startMessage": string;
19
+ "properties": {
20
+ [key: string]: DialogProperty;
21
+ };
22
+ }
23
+ export declare type CheckFunction = (lastReceivedMessage: Message, currentProps: CurrentDialogProps) => boolean;
24
+ export interface DialogProperty {
25
+ "order": number;
26
+ "key": string;
27
+ "prompt": string;
28
+ "type": string;
29
+ "skipCondition"?: CheckFunction;
30
+ "options"?: DialogButtons[] | DialogListMessageSection[];
31
+ "validation": DialogValidation[];
32
+ }
33
+ export interface DialogButtons {
34
+ label: string;
35
+ value: string;
36
+ }
37
+ export interface DialogListMessageSection {
38
+ title: string;
39
+ rows: DialogListMessageRow[];
40
+ }
41
+ export interface DialogListMessageRow {
42
+ title: string;
43
+ description: string;
44
+ value: string;
45
+ }
46
+ export interface DialogValidation {
47
+ "type": ValidationType;
48
+ "value": string | CheckFunction;
49
+ "errorMessage": string;
50
+ }
51
+ export declare enum ValidationType {
52
+ REGEX = "regex",
53
+ LENGTH = "length",
54
+ CHECK = "check"
55
+ }