-
-
Notifications
You must be signed in to change notification settings - Fork 602
/
browser.ts
276 lines (255 loc) · 10.2 KB
/
browser.ts
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
/**
* @hidden
*/
/** */
import * as path from 'path';
const fs = require('fs');
const puppeteer = require('puppeteer-extra');
import { puppeteerConfig, useragent, width, height} from '../config/puppeteer.config';
import { Browser, Page } from 'puppeteer';
import { Spin, EvEmitter } from './events';
import { ConfigObject } from '../api/model';
const ON_DEATH = require('death'); //this is intentionally ugly
let browser;
export async function initClient(sessionId?: string, config?:ConfigObject, customUserAgent?:string) {
if(config?.useStealth) puppeteer.use(require('puppeteer-extra-plugin-stealth')());
browser = await initBrowser(sessionId,config);
const waPage = await getWAPage(browser);
if (config?.proxyServerCredentials) {
await waPage.authenticate(config.proxyServerCredentials);
}
await waPage.setUserAgent(customUserAgent||useragent);
await waPage.setViewport({
width: config?.window?.width || width,
height: config?.window?.height || height,
deviceScaleFactor: 1
});
const cacheEnabled = config?.cacheEnabled === false ? false : true;
const blockCrashLogs = config?.blockCrashLogs === false ? false : true;
await waPage.setBypassCSP(config?.bypassCSP || false);
await waPage.setCacheEnabled(cacheEnabled);
const blockAssets = !config?.headless ? false : config?.blockAssets || false;
if(blockAssets){
puppeteer.use(require('puppeteer-extra-plugin-block-resources')({
blockedTypes: new Set(['image', 'stylesheet', 'font'])
}))
}
const interceptAuthentication = !(config?.safeMode);
const proxyAddr = config?.proxyServerCredentials ? `${config.proxyServerCredentials?.username && config.proxyServerCredentials?.password ? `${config.proxyServerCredentials.protocol ||
config.proxyServerCredentials.address.includes('https') ? 'https' :
config.proxyServerCredentials.address.includes('http') ? 'http' :
config.proxyServerCredentials.address.includes('socks5') ? 'socks5' :
config.proxyServerCredentials.address.includes('socks4') ? 'socks4' : 'http'}://${config.proxyServerCredentials.username}:${config.proxyServerCredentials.password}@${config.proxyServerCredentials.address
.replace('https', '')
.replace('http', '')
.replace('socks5', '')
.replace('socks4', '')
.replace('://', '')}` : config.proxyServerCredentials.address}` : false;
let quickAuthed = false;
if(interceptAuthentication || proxyAddr || blockCrashLogs){
await waPage.setRequestInterception(true);
let authCompleteEv = new EvEmitter(sessionId, 'AUTH');
waPage.on('request', async request => {
if (
interceptAuthentication &&
request.url().includes('_priority_components') &&
!quickAuthed
) {
authCompleteEv.emit(true);
await waPage.evaluate('window.WA_AUTHENTICATED=true;');
quickAuthed = true;
}
if (request.url().includes('https://crashlogs.whatsapp.net/') && blockCrashLogs){
request.abort();
}
else if (proxyAddr) require('puppeteer-page-proxy')(request, proxyAddr);
else request.continue();
})
}
// if (blockAssets || blockCrashLogs || proxyAddr) {
// let patterns = [];
// if (interceptAuthentication) {
// authCompleteEv = new EvEmitter(sessionId, 'AUTH');
// patterns.push({ urlPattern: '*_priority_components*' });
// }
// if (blockCrashLogs) patterns.push({ urlPattern: '*crashlogs' });
// if (blockAssets) {
// //@ts-ignore
// await waPage._client.send('Network.enable');
// //@ts-ignore
// waPage._client.send('Network.setBypassServiceWorker', {
// bypass: true,
// });
// patterns = [
// ...patterns,
// ...[
// { urlPattern: '*.css' },
// { urlPattern: '*.jpg' },
// { urlPattern: '*.jpg*' },
// { urlPattern: '*.jpeg' },
// { urlPattern: '*.jpeg*' },
// { urlPattern: '*.webp' },
// { urlPattern: '*.png' },
// { urlPattern: '*.mp3' },
// { urlPattern: '*.svg' },
// { urlPattern: '*.woff' },
// { urlPattern: '*.pdf' },
// { urlPattern: '*.zip' },
// { urlPattern: '*crashlogs' },
// ],
// ];
// }
// //@ts-ignore
// await waPage._client.send('Network.setRequestInterception', {
// patterns,
// });
// //@ts-ignore
// waPage._client.on(
// 'Network.requestIntercepted',
// async ({ interceptionId, request }) => {
// const extensions = [
// '.css',
// '.jpg',
// '.jpeg',
// '.webp',
// '.mp3',
// '.png',
// '.svg',
// '.woff',
// '.pdf',
// '.zip',
// ];
// const req_extension = path.extname(request.url);
// if (
// (blockAssets && extensions.includes(req_extension)) ||
// request.url.includes('.jpg') ||
// (blockCrashLogs && request.url.includes('crashlogs'))
// ) {
// await (waPage as any)._client.send(
// 'Network.continueInterceptedRequest',
// {
// interceptionId,
// rawResponse: '',
// }
// );
// } else {
// if(proxyAddr) {
// console.log("initClient -> proxyAddr", proxyAddr, request.url)
// await useProxy(request, {
// proxy: proxyAddr,
// headers: {
// ...request.headers,
// referer:"https://web.whatsapp.com/",
// host: "https://web.whatsapp.com"
// }});
// } else
// await (waPage as any)._client.send(
// 'Network.continueInterceptedRequest',
// {
// interceptionId,
// }
// );
// }
// }
// );
// }
//check if [session].json exists in __dirname
const sessionjsonpath = (config?.sessionDataPath && config?.sessionDataPath.includes('.data.json')) ? path.join(path.resolve(process.cwd(),config?.sessionDataPath || '')) : path.join(path.resolve(process.cwd(),config?.sessionDataPath || ''), `${sessionId || 'session'}.data.json`);
let sessionjson = '';
let sd = process.env[`${sessionId.toUpperCase()}_DATA_JSON`] ? JSON.parse(process.env[`${sessionId.toUpperCase()}_DATA_JSON`]) : config?.sessionData;
sessionjson = (typeof sd === 'string') ? JSON.parse(Buffer.from(sd, 'base64').toString('ascii')) : sd;
if (fs.existsSync(sessionjsonpath)) {
let s = fs.readFileSync(sessionjsonpath, "utf8");
try {
sessionjson = JSON.parse(s);
} catch (error) {
sessionjson = JSON.parse(Buffer.from(s, 'base64').toString('ascii'));
}
}
if(sessionjson) await waPage.evaluateOnNewDocument(
session => {
localStorage.clear();
Object.keys(session).forEach(key=>localStorage.setItem(key,session[key]));
}, sessionjson);
if(config?.proxyServerCredentials) {
await require('puppeteer-page-proxy')(waPage, proxyAddr);
console.log(`Active proxy: ${config.proxyServerCredentials.address}`)
}
await waPage.goto(puppeteerConfig.WAUrl)
return waPage;
}
export async function injectApi(page: Page) {
await page.addScriptTag({
path: require.resolve(path.join(__dirname, '../lib', 'wapi.js'))
});
await page.addScriptTag({
path: require.resolve(path.join(__dirname, '../lib', 'axios.min.js'))
});
await page.addScriptTag({
path: require.resolve(path.join(__dirname, '../lib', 'jsSha.min.js'))
});
await page.addScriptTag({
path: require.resolve(path.join(__dirname, '../lib', 'base64.js'))
});
return page;
}
async function initBrowser(sessionId?: string, config:any={}) {
if(config?.useChrome && !config?.executablePath) {
const storage = require('node-persist');
await storage.init();
let _savedPath = await storage.getItem('executablePath');
if(!_savedPath) {
config.executablePath = require('chrome-launcher').Launcher.getInstallations()[0];
await storage.setItem('executablePath',config.executablePath)
} else config.executablePath = _savedPath;
}
if(config?.browserRevision) {
const browserFetcher = puppeteer.createBrowserFetcher();
const browserDownloadSpinner = new Spin(sessionId+'_browser', 'Browser',false,false);
try {
browserDownloadSpinner.start('Downloading browser revision: ' + config.browserRevision);
const revisionInfo = await browserFetcher.download(config.browserRevision, function(downloadedBytes,totalBytes){
browserDownloadSpinner.info(`Downloading Browser: ${Math.round(downloadedBytes/1000000)}/${Math.round(totalBytes/1000000)}`);
});
if(revisionInfo.executablePath) {
config.executablePath = revisionInfo.executablePath;
// config.pipe = true;
}
browserDownloadSpinner.succeed('Browser downloaded successfully');
} catch (error){
browserDownloadSpinner.succeed('Something went wrong while downloading the browser');
}
}
// if(config?.proxyServerCredentials?.address) puppeteerConfig.chromiumArgs.push(`--proxy-server=${config.proxyServerCredentials.address}`)
if(config?.browserWsEndpoint) config.browserWSEndpoint = config.browserWsEndpoint;
let args = [...puppeteerConfig.chromiumArgs,...(config?.chromiumArgs||[])];
if(config?.corsFix) args.push('--disable-web-security');
const browser = (config?.browserWSEndpoint) ? await puppeteer.connect({...config}): await puppeteer.launch({
headless: true,
devtools: false,
args,
...config
});
//devtools
if(config&&config.devtools){
const devtools = require('puppeteer-extra-plugin-devtools')();
if(config.devtools.user&&config.devtools.pass) devtools.setAuthCredentials(config.devtools.user, config.devtools.pass)
try {
// const tunnel = await devtools.createTunnel(browser);
const tunnel = devtools.getLocalDevToolsUrl(browser);
console.log('\ndevtools URL: '+tunnel);
} catch (error) {
console.log("TCL: initBrowser -> error", error)
}
}
return browser;
}
async function getWAPage(browser: Browser) {
const pages = await browser.pages();
console.assert(pages.length > 0);
return pages[0];
}
ON_DEATH(async (signal, err) => {
//clean up code here
if (browser) await browser.close();
});