Skip to content

Commit

Permalink
Merge c959736 into 4262ce9
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaomocqk committed Nov 6, 2023
2 parents 4262ce9 + c959736 commit 904a585
Show file tree
Hide file tree
Showing 3 changed files with 115 additions and 9 deletions.
3 changes: 2 additions & 1 deletion packages/plugin-selenium-driver/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@
"@testring/types": "0.6.8",
"@types/deepmerge": "2.2.0",
"@types/node": "18.11.18",
"chromedriver": "*",
"chromedriver": "116",
"deepmerge": "4.2.2",
"extract-zip": "2.0.1",
"selenium-server": "3.141.59",
"webdriverio": "7.20.7"
}
Expand Down
95 changes: 95 additions & 0 deletions packages/plugin-selenium-driver/src/chromium.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/* eslint-disable no-sequences */
/* eslint-disable no-console */
const os = require('os');
const https = require('https');
const path = require('path');
const fs = require('fs');
const extract = require('extract-zip');

const CHROMIUM_DOWNLOAD_PATH = path.join(os.homedir(), 'Downloads');

const DOWNLOAD_URLS = {
darwin: 'https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Mac%2F1159680%2Fchrome-mac.zip?generation=1687199461863686&alt=media',
win32: 'https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Win%2F1159780%2Fchrome-win.zip?generation=1687230822312589&alt=media',
win64: 'https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Win_x64%2F1159777%2Fchrome-win.zip?generation=1687229811750676&alt=media',
};
const platform = os.platform();

class Chromium {
private _completed = 0
private _totalBytes = 0

async install() {
const zipPath = path.join(CHROMIUM_DOWNLOAD_PATH, `chromium-116.zip`);

if (!fs.existsSync(CHROMIUM_DOWNLOAD_PATH)) {
fs.mkdirSync(CHROMIUM_DOWNLOAD_PATH);
}
if (!fs.existsSync(this.path)) {
if (!fs.existsSync(zipPath)) {
const tid = setInterval(() => this._getDownloadPercent(), 6000);
try {
await this._downloadChromiumZip(zipPath);
this._getDownloadPercent()
} finally {
clearInterval(tid);
}
}
await extract(zipPath, { dir: CHROMIUM_DOWNLOAD_PATH });
}
}

get path() {
return path.join(
CHROMIUM_DOWNLOAD_PATH,
platform === 'darwin' ? `chrome-mac/Chromium.app/Contents/MacOS/Chromium` : `chrome-win/chrome.exe`,
);
}

private _getDownloadUrl() {
if (platform === 'darwin') {
return DOWNLOAD_URLS.darwin
}
return os.arch() === 'x64' ? DOWNLOAD_URLS.win64 : DOWNLOAD_URLS.win32;
}

private _downloadChromiumZip(zipPath) {
return new Promise((resolve, reject) => {
const url = this._getDownloadUrl();
https.get(url, (response) => {
if (response.statusCode !== 200) {
const error = new Error(
`Download failed: code ${response.statusCode}. URL: ${url}`,
);
response.resume();
reject(error);
return;
}
const file = fs.createWriteStream(zipPath);
file.on('finish', resolve);
file.on('error', () => {
fs.unlinkSync(zipPath)
reject()
});
response.pipe(file);
this._onProgress(response);
});
})
}

private _onProgress(response) {
if (!this._totalBytes) {
this._totalBytes = parseInt(response.headers['content-length'], 10);
}
response.on('data', (chunk) => {
this._completed += chunk.length
});
}

private _getDownloadPercent() {
const percent = Math.round(this._completed / this._totalBytes * 100) || 0;
console.log(`Downloading chromium app... ${percent}%`)
}
}

export default new Chromium();
26 changes: 18 additions & 8 deletions packages/plugin-selenium-driver/src/plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {spawn} from '@testring/child-process';
import {loggerClient} from '@testring/logger';
import {absoluteExtensionPath} from '@testring/devtool-extension';
import {CDPCoverageCollector} from '@nullcc/code-coverage-client';
import chromium from '../chromium';

import type {Cookie} from '@wdio/protocols';
import type {
Expand Down Expand Up @@ -85,10 +86,13 @@ export class SeleniumPlugin implements IBrowserProxyPlugin {

private incrementWinId = 0;

private waitForChromiumReady: Promise<void>;

constructor(config: Partial<SeleniumPluginConfig> = {}) {
this.config = this.createConfig(config);

if (this.config.host === undefined) {
this._installChromium();
this.runLocalSelenium();
}

Expand Down Expand Up @@ -236,6 +240,11 @@ export class SeleniumPlugin implements IBrowserProxyPlugin {
return [`-Dwebdriver.chrome.driver=${chromeDriverPath}`];
}

private _installChromium() {
this.config.capabilities['goog:chromeOptions'].binary = chromium.path
this.waitForChromiumReady = chromium.install()
}

private async runLocalSelenium() {
const seleniumServer = require('selenium-server');
const seleniumJarPath = seleniumServer.path;
Expand Down Expand Up @@ -350,7 +359,8 @@ export class SeleniumPlugin implements IBrowserProxyPlugin {
);
}

const _config: any = deepmerge.all([{}, this.config, config as any || {}]);
const _config: any = config ? deepmerge.all([{}, this.config, config as any || {}]) : this.config;
await this.waitForChromiumReady;
const client = await remote(_config);

let sessionId: string;
Expand Down Expand Up @@ -1176,20 +1186,20 @@ export class SeleniumPlugin implements IBrowserProxyPlugin {
}

public async emulateDevice(applicant: string, deviceName) {
await this.createClient(applicant);
const client = this.getBrowserClient(applicant);

await client.deleteSession();
this.browserClients.delete(applicant);
if (this.hasBrowserClient(applicant)) {
await this.end(applicant);
}
const userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
await this.createClient(applicant, {
capabilities: {
'goog:chromeOptions': {
mobileEmulation: {
deviceName,
},
},
args: [`--user-agent=${userAgent}`],
}
},
} as any)
} as any);
}
}

Expand Down

0 comments on commit 904a585

Please sign in to comment.