How to use getChromedriverPort method in Appium Android Driver

Best JavaScript code snippet using appium-android-driver

utils.js

Source:utils.js Github

copy

Full Screen

1import {app, nativeImage} from 'electron';2import fs from 'fs';3import path from 'path';4import http from 'http';5import https from 'https';6import zlib from 'zlib';7import config from "./configs/app.config";8import {ipcMain} from 'electron-better-ipc';9import StreamZip from "node-stream-zip";10import pFun from 'p-fun';11import cp from 'child_process';12import fse from "live-plugin-manager/node_modules/fs-extra";13import tar from 'live-plugin-manager/node_modules/tar';14import store from "./configs/settings";15// https://www.jianshu.com/p/4b58711cb72a16let fetch = require("node-fetch");17var eol = require('os').EOL;18// import {DownloaderHelper} from 'node-downloader-helper';19/*20let remote = require('electron').remote; let app = remote.app; let path = require('path'); let fs = require('fs'); let fetch = require("node-fetch");21let http = require('http'); let https = require('https'); let net = require('net'); let zlib = require('zlib');22let StreamZip = require('node-stream-zip'); let fse = require('live-plugin-manager/node_modules/fs-extra'); let tar = require('live-plugin-manager/node_modules/tar');23*/24/**25 * 获取UserData路径26 * @returns {string}27 */28exports.getUserData = () => {29 return app.getPath('userData');30};31/**32 * 获取appData路径33 * @returns {string}34 */35exports.getAppData = () => {36 return app.getPath('appData');37};38/**39 * 获取Electron Cache路径40 * @returns {string}41 */42exports.getElectronCachePath = () => {43 return exports.checkPath(path.join(process.env.LOCALAPPDATA, 'electron', 'Cache'));44};45/**46 * 获取Adblock路径47 * @returns {string}48 */49exports.getAdblockPath = () => {50 return exports.checkPath(path.join(exports.getUserData(), 'Adblocker'));51};52/**53 * 获取扩展路径(本地项目数据目录中)54 * @returns {string}55 */56exports.getExtensionsPathCache = () => {57 return exports.checkPath(path.join(exports.getUserData(), 'Extensions'));58};59/**60 * 获取扩展路径(客户端自带)61 * @returns {string}62 */63exports.getExtensionsPathSys = () => {64 return path.join(__dirname, './../assets/plugins/');65};66/**67 * 获取YiyiNet根目录68 * @returns {string}69 */70exports.getRootPath = () => {71 return path.dirname(process.execPath);72};73exports.checkPath = (filePath) => {74 if (!fs.existsSync(filePath)) {75 fs.mkdirSync(filePath, {recursive: true});76 }77 return filePath;78}79/**80 * 获取chromedriver路径81 */82exports.getChromedriverFilePath = () => {83 return path.join(exports.getRootPath(), exports.getChromedriverExeName());84};85/**86 * 获取工具类保存路径87 */88exports.getToolsPath = () => {89 return exports.checkPath(path.join(exports.getUserData(), 'Tools'));90};91/**92 * 获取YoutubeDl路径93 */94exports.getYoutubeDlExe = () => {95 return path.join(exports.getToolsPath(), 'youtube-dl.exe');96};97/**98 * 获取V2rayCore路径99 */100exports.getV2rayCoreExe = () => {101 let v2rayFolder = exports.checkPath(path.join(exports.getToolsPath(), 'v2ray'));102 return path.join(v2rayFolder, 'v2ray.exe');103};104/**105 * 获取Aria2路径106 */107exports.getAria2Exe = () => {108 let aria2Folder = exports.checkPath(path.join(exports.getToolsPath(), 'aria2'));109 return path.join(aria2Folder, 'aria2c.exe');110};111/**112 * 获取Aria2配置文件路径113 */114exports.getAria2Conf = () => {115 let aria2Folder = exports.checkPath(path.join(exports.getToolsPath(), 'aria2'));116 return path.join(aria2Folder, 'aria2.conf');117};118/**119 * 获取chromedriver文件名(平台兼容)120 */121exports.getChromedriverExeName = () => {122 return 'chromedriver' + (process.platform === 'win32' ? '.exe' : '');123};124// =====================================================================================================================125/**126 * 获取Python所有Exe127 */128exports.getPythonExeName = () => {129 return 'python' + (process.platform === 'win32' ? '.exe' : '');130};131/**132 * 获取Python所在路径133 */134exports.getPythonFolder = () => {135 return exports.checkPath(path.join(exports.getUserData(), 'Python'));136};137/**138 * 获取Python所在路径139 */140exports.getPythonFilePath = () => {141 return path.join(exports.getPythonFolder(), exports.getPythonExeName());142};143/**144 * 获取Python Pip所在路径145 */146exports.getPythonPipPath = () => {147 return path.join(exports.getPythonFolder(), 'Scripts', 'pip.exe');148};149/**150 * 获取Python的Scripts所在路径151 */152exports.getPythonScriptsPath = () => {153 return exports.checkPath(path.join(exports.getUserData(), 'Scripts'));154};155// =====================================================================================================================156/**157 * 获取Chrome所有Exe158 */159exports.getChromeExeName = () => {160 return 'chrome' + (process.platform === 'win32' ? '.exe' : '');161};162/**163 * 获取Chrome所在路径164 */165exports.getChromeFolder = () => {166 return exports.checkPath(path.join(exports.getUserData(), 'Chrome'));167};168/**169 * 获取Chrome所在路径170 */171exports.getChromeFilePath = () => {172 return path.join(exports.getChromeFolder(), exports.getChromeExeName());173};174// =====================================================================================================================175/**176 * 获取Firefox所有Exe177 */178exports.getFirefoxExeName = () => {179 return 'firefox' + (process.platform === 'win32' ? '.exe' : '');180};181/**182 * 获取Firefox所在路径183 */184exports.getFirefoxFolder = () => {185 return exports.checkPath(path.join(exports.getUserData(), 'Firefox'));186};187/**188 * 获取Python所在路径189 */190exports.getFirefoxFilePath = () => {191 return path.join(exports.getFirefoxFolder(), exports.getFirefoxExeName());192};193// =====================================================================================================================194/**195 * 获取Jre所在路径196 */197exports.getJreFolder = () => {198 return exports.checkPath(path.join(exports.getJdkFolder(), 'jre'));199};200/**201 * 获取Jre所在路径(exe路径)202 */203exports.getJrePath = () => {204 return path.join(exports.getJreFolder(), 'bin', 'java.exe');205};206/**207 * 获取Jdk所在路径208 */209exports.getJdkFolder = () => {210 return exports.checkPath(path.join(exports.getUserData(), 'Jdk'));211};212/**213 * 获取Jdk所在路径(exe路径)214 */215exports.getJdkPath = () => {216 return path.join(exports.getJdkFolder(), 'bin', 'java.exe');217};218// =====================================================================================================================219/**220 * 获取7Zip所在路径221 */222exports.get7ZipFolder = () => {223 return exports.checkPath(path.join(exports.getToolsPath(), '7zip'));224};225/**226 * 获取7Zip所在路径(exe路径)227 */228exports.get7ZipPath = () => {229 return path.join(exports.get7ZipFolder(), '7za.exe');230};231// =====================================================================================================================232/**233 * 获取Nox所在路径234 */235exports.getNoxFolder = () => {236 return exports.checkPath(path.join(exports.getUserData(), 'NoxPlayer'));237};238/**239 * 获取Nox所在路径(exe路径)240 */241exports.getNoxPath = () => {242 return path.join(exports.getNoxFolder(), 'bin', 'Nox.exe');243};244/**245 * 获取Nox配置文件所在路径246 */247exports.getNoxConfigPath = () => {248 return path.join(exports.getUserData(), '..', '..', 'Local', 'Nox');249};250/**251 * 获取Nox中的adb.exe所在路径252 */253exports.getNoxAdb = () => {254 return path.join(exports.getNoxFolder(), 'bin', 'adb.exe');255};256// =====================================================================================================================257/**258 * 获取Android Sdk所在路径259 */260exports.getAndroidSdkFolder = () => {261 return exports.checkPath(path.join(exports.getUserData(), 'AndroidSdk'));262};263/**264 * 获取Android Sdk所在路径(adb.exe路径)265 */266exports.getAndroidSdkPath = () => {267 return path.join(exports.getAndroidSdkFolder(), 'platform-tools', 'adb.exe');268};269/**270 * 获取Apk保存路径271 */272exports.getApkFolder = () => {273 return exports.checkPath(path.join(exports.getUserData(), 'Apk'));274};275// =====================================================================================================================276/**277 * 获取Apk保存路径278 */279exports.getNircmdExe = () => {280 return path.join(exports.getToolsPath(), 'nircmdc.exe');281};282// =====================================================================================================================283/**284 * 获取Chrome Profile路径285 */286exports.getChromeProfilePath = () => {287 return exports.checkPath(path.join(exports.getUserData(), '/Profile/Chrome'));288};289/**290 * 获取Firefox Profile路径291 */292exports.getFirefoxProfilePath = () => {293 return exports.checkPath(path.join(exports.getUserData(), '/Profile/Firefox'));294};295// =====================================================================================================================296/*297 * 复制文件298 * @param src {String} 要复制的文件299 * @param dist {String} 复制到目标文件300 */301exports.copyFile = (src, dist) => {302 console.log('复制文件:' + src + ' -> ' + dist);303 fse.copySync(src, dist);304}305/*306 * 复制目录、子目录,及其中的文件307 * @param src {String} 要复制的目录308 * @param dist {String} 复制到目标目录309 */310function copyDir(src, dist, callback) {311 fs.access(dist, function (err) {312 if (err) {313 // 目录不存在时创建目录314 fs.mkdirSync(dist);315 }316 _copy(null, src, dist);317 });318 function _copy(err, src, dist) {319 if (err) {320 callback(err);321 } else {322 fs.readdir(src, function (err, paths) {323 if (err) {324 callback(err)325 } else {326 paths.forEach(function (path) {327 let _src = src + '/' + path;328 let _dist = dist + '/' + path;329 fs.stat(_src, function (err, stat) {330 if (err) {331 callback(err);332 } else {333 // 判断是文件还是目录334 if (stat.isFile()) {335 fs.writeFileSync(_dist, fs.readFileSync(_src));336 } else if (stat.isDirectory()) {337 // 当是目录是,递归复制338 copyDir(_src, _dist, callback)339 }340 }341 })342 })343 }344 })345 }346 }347}348exports.execCmd = (cmd) => {349 console.log('执行cmd命令:' + cmd);350 return new Promise(function (resolve, reject) {351 cp.exec(cmd, {352 maxBuffer: 1024 * 2000353 }, function (err, stdout, stderr) {354 if (err) {355 reject(err);356 } else if (stderr.length > 0) {357 reject(new Error(stderr.toString()));358 } else {359 resolve(stdout);360 }361 });362 });363}364exports.execa = (file, args) => {365 // console.log('执行execa命令:' + file + ' ' + args);366 let execa = require('execa');367 return execa(file, args);368}369/**370 * 采用execa获取命令行数据数组371 * @param file372 * @param args373 * @param options374 * @returns {*}375 */376exports.execaLines = (file, args, options = {}) => {377 // console.log('执行execa命令:' + file + ' ' + args);378 let execa = require('execa');379 return new Promise(function (resolve, reject) {380 execa(file, args, options).then(res => {381 if (res.stderr) {382 reject(res.stderr);383 }384 let outList = res.stdout.split(eol).filter(line => line !== '' && !line.startsWith('List of devices attached'))385 .map(str => str.replace(eol, ''));386 // console.log('outList:' + outList);387 resolve(outList);388 }).catch(err => {389 // console.log(err);390 resolve([]);391 });392 });393}394/**395 * 检查过去的天数396 * @param startDate397 * @returns {number}398 */399exports.pastDays = (startDate) => {400 return (Date.now() - startDate) / 1000 / 60 / 60 / 24;401}402/**403 * 根据地址获取http或者https404 * @param url405 * @returns {any}406 */407exports.getHttpOrHttps = (url) => {408 return !url.charAt(4).localeCompare('s') ? https : http;409}410/**411 * 解析获取最快的链接地址412 * @returns {Promise<PCancelable<unknown> | *>}413 */414exports.fastUrl = async (urlArr, urlpath) => {415 let got = require('got');416 let pFun = require('p-fun');417 let taskArr = [];418 urlpath = urlpath === undefined || urlpath === null ? '' : urlpath;419 urlArr.forEach(url => {420 taskArr.push(got.head(url + urlpath).then(() => url));421 });422 return pFun.any(taskArr);423}424/**425 * 解析获取mozilla最快的链接地址426 * @returns {Promise<PCancelable<unknown> | *>}427 */428exports.fastMozillaUrl = async (urlpath) => {429 let mozillaUrls = ['http://download-origin.cdn.mozilla.net', 'http://archive.mozilla.org', 'http://ftp.mozilla.org',430 'https://archive.mozilla.org', 'https://download-origin.cdn.mozilla.net', 'https://ftp.mozilla.org'];431 return exports.fastUrl(mozillaUrls, urlpath);432}433/**434 * 解析获取NPM最快的链接地址435 * @returns {Promise<PCancelable<unknown> | *>}436 */437exports.fastNpmUrl = async (urlpath) => {438 let npmUrlArr = ['https://npm.taobao.org/mirrors', 'https://mirrors.huaweicloud.com', 'https://cnpmjs.org/mirrors'];439 return exports.fastUrl(npmUrlArr, urlpath);440}441/**442 * 解析获取Github最快的链接地址443 * @returns {Promise<PCancelable<unknown> | *>}444 */445exports.fastGithubUrl = async (urlpath) => {446 // http://element-ui.cn/article/show-101839.aspx447 // https://github.com/FastGitORG/github-accelerator448 // https://doc.fastgit.org/zh-cn/449 let githubUrlArr = ['https://hub.fastgit.org', 'https://github.com.cnpmjs.org', 'https://github.com'450 /*'https://g.ioiox.com/https://github.com', 'https://gh.api.99988866.xyz/https://github.com', 'https://github.wuyanzheshui.workers.dev'*/];451 return exports.fastUrl(githubUrlArr, urlpath);452}453/**454 * 解析获取Github Raw最快的链接地址455 * @returns {Promise<PCancelable<unknown> | *>}456 */457exports.fastGithubRawUrl = async (urlpath) => {458 // http://element-ui.cn/article/show-101839.aspx459 // https://doc.fastgit.org/zh-cn/node.html460 let githubRawUrlArr = ['https://raw.fastgit.org', 'https://raw.githubusercontent.com'];461 return exports.fastUrl(githubRawUrlArr, urlpath);462}463/**464 * 解析获取Python最快的镜像地址465 * @returns {Promise<PCancelable<unknown> | *>}466 */467exports.fastPypiUrl = async (urlpath) => {468 // https://www.cnblogs.com/yuki-nana/p/10898774.html469 let pypiUrls = ['https://mirrors.aliyun.com/pypi/simple/', 'https://pypi.douban.com/simple/', 'https://pypi.tuna.tsinghua.edu.cn/simple',470 'https://pypi.mirrors.ustc.edu.cn/simple/'];471 return exports.fastUrl(pypiUrls, urlpath);472}473/**474 * 检查链接地址是否可用475 * isUrlValid('https://www.baidu.com', (flag)=>{console.log(flag)});476 */477exports.isUrlValid = (url) => {478 const proto = exports.getHttpOrHttps(url);479 return new Promise((resolve, reject) => {480 let req = proto.get(url, response => {481 return resolve(response.statusCode === 200 || (response.statusCode >= 300 && response.statusCode));482 }).on('error', (err) => {483 return resolve(false);484 });485 req.end();486 });487}488/**489 * 解压Zip文件490 * @param zipFile491 * @param folder492 * @returns {Promise<unknown>}493 */494exports.extractZip = (zipFile, folder) => {495 return new Promise((resolve, reject) => {496 const zip = new StreamZip({497 file: zipFile,498 storeEntries: true499 });500 zip.on('error', err => {501 // 如果出错,说明压缩包有问题,将其删除502 // fs.unlinkSync(zipFile);503 zip.close();504 reject(err);505 });506 zip.on('ready', () => {507 zip.extract(null, folder, (err, count) => {508 zip.close();509 resolve();510 });511 });512 });513}514/**515 * 解压Tar文件516 * @param tarFile517 * @param folder518 * @returns {Promise<unknown>}519 */520exports.extractTar = (tarFile, folder) => {521 return new Promise((resolve, reject) => {522 tar.extract({523 cwd: folder,524 file: tarFile525 }).then(() => {526 resolve(folder);527 }).catch((err) => {528 reject(err);529 })530 });531}532/**533 * 下载并保存文件534 * @param url535 * @param filePath536 * @returns {Promise<unknown>}537 */538exports.downloadFile = (url, filePath) => {539 const proto = exports.getHttpOrHttps(url);540 return new Promise((resolve, reject) => {541 let file = fs.createWriteStream(filePath);542 let request = proto.get(url, response => {543 // console.log('response.headers: '); console.dir(response.headers);544 if (response.statusCode !== 200) {545 if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {546 return exports.downloadFile(response.headers.location, filePath).then(resolve).catch(reject);547 } else {548 reject(new Error(`Failed to get '${url}' (${response.statusCode})`));549 return;550 }551 }552 switch (response.headers['content-encoding']) {553 case 'br':554 response.pipe(zlib.createBrotliDecompress()).pipe(file);555 break;556 case 'gzip': // 或者, 只是使用 zlib.createUnzip() 方法去处理这两种情况:557 response.pipe(zlib.createGunzip()).pipe(file);558 break;559 case 'deflate':560 response.pipe(zlib.createInflate()).pipe(file);561 break;562 default:563 response.pipe(file);564 break;565 }566 });567 // The destination stream is ended by the time it's called568 file.on('finish', () => resolve());569 request.on('error', err => {570 file.close();571 fs.unlink(filePath, () => reject(err));572 });573 file.on('error', err => {574 file.close();575 fs.unlink(filePath, () => reject(err));576 });577 request.end();578 });579};580/**581 * 获取Url对应的HTML582 * @param url583 * @returns {Promise<unknown>}584 */585exports.getHtml = async (url) => {586 return new Promise((resolve, reject) => {587 fetch(url, {588 method: 'GET'589 }).then(res => {590 resolve(res.text());591 }).catch(err => {592 reject(err);593 })594 });595}596/**597 * 获取Url对应的JSON598 * @param url599 * @returns {Promise<unknown>}600 */601exports.getJson = async (url) => {602 return new Promise((resolve, reject) => {603 fetch(url, {604 method: 'GET'605 }).then(res => {606 resolve(res.json());607 }).catch(err => {608 reject(err);609 })610 });611}612/**613 * 获取Url跳转的地址614 * @param url615 * @returns {Promise<unknown>}616 */617exports.getRedirected = async (url) => {618 return new Promise((resolve, reject) => {619 fetch(url, {620 method: 'GET',621 redirect: 'manual',622 follow: 0623 }).then(res => {624 resolve(res.headers.get('location') || res.headers.get('content-location'));625 }).catch(err => {626 reject(err);627 })628 });629}630/**631 * 下载小文件632 * @param url633 * @param filePath 文件保存位置,包括文件名634 * @param options635 * @returns {Promise<unknown>}636 */637exports.downloadSmall = async (url, filePath, options) => {638 return new Promise((resolve, reject) => {639 fetch(url, {640 method: 'GET',641 headers: {'Content-Type': 'application/octet-stream'},642 ...options || {},643 }).then(res => res.buffer()).then(_ => {644 fs.writeFile(filePath, _, "binary", function (err) {645 if (err) {646 reject(err);647 } else {648 resolve(filePath);649 }650 });651 }).catch(err => {652 reject(err);653 })654 });655}656/**657 * 下载大文件658 * @param fileURL 文件下载路径659 * @param filePath 文件保存位置,包括文件名660 * @param options node-fetch的参数661 * @returns {Promise<unknown>}662 */663exports.downloadLarge = async (fileURL, filePath, options) => {664 return new Promise((resolve, reject) => {665 //缓存文件路径666 let tmpFileSavePath = filePath + ".tmp";667 let totalBytes = 1, logSecondInterval = 1;668 let startDate = Date.now(), curDate = Date.now();669 let fileName = path.basename(filePath);670 //创建写入流671 let fileStream = fs.createWriteStream(tmpFileSavePath)672 .on('error', function (e) {673 console.error('error==>', e);674 reject(e);675 }).on('ready', function () {676 console.log("准备下载:", fileURL);677 }).on('finish', function () {678 //下载完成后重命名文件679 fs.renameSync(tmpFileSavePath, filePath);680 // console.log('下载完成:', filePath);681 resolve(filePath);682 }).on('drain', function () {683 let downloadedBytes = fileStream.bytesWritten;684 if (Date.now() - startDate >= logSecondInterval * 1000) {685 let speed = (downloadedBytes / 1024 / (Date.now() - curDate) * 1000).toFixed(2);686 console.log('正在下载[' + fileName + '],完成[' + (100 * downloadedBytes / totalBytes).toFixed(2) + '%],当前['687 + (downloadedBytes / 1024 / 1024).toFixed(2) + '/' + (totalBytes / 1024 / 1024).toFixed(2) + ']M,'688 + '速度[' + speed + 'Kb/S],大约还需[' + ((totalBytes - downloadedBytes) / 1024 / speed / 60).toFixed(2) + ']分钟');689 startDate = Date.now();690 // process.stdout.write((downloadedBytes / totalBytes * 100).toFixed(4) + '% ');691 }692 });693 let defaultOption = {694 method: 'GET',695 headers: {696 // 'Content-Type': 'application/octet-stream',697 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'698 },699 // timeout: 60000,700 };701 //请求文件702 fetch(fileURL, {703 ...defaultOption,704 ...options || {}705 }).then(res => {706 // console.log('res:'); console.dir(res);707 if (res.headers.get('redirected')) {708 let redUrl = res.headers.get('location') || res.headers.get('content-location');709 console.log('跳转链接: ' + redUrl + ',原链接:' + fileURL);710 exports.downloadLarge(redUrl, filePath, options);711 } else {712 //获取请求头中的文件大小数据713 totalBytes = res.headers.get("content-length");714 logSecondInterval = Math.max(1, Math.round(totalBytes / 1024 / 1024 / 10));715 res.body/*.pipe(str)*/.pipe(fileStream);716 }717 }).catch(e => {718 reject(e);719 });720 });721};722/**723 * 下载OneDriver共享文件724 * @param fileURL 文件下载路径725 * @param filePath 文件保存位置,包括文件名726 * @param options node-fetch的参数727 * @returns {Promise<void>}728 */729exports.downloadOneDriver = async (fileURL, filePath, options) => {730 // https://github.com/aploium/OneDrive-Direct-Link731 fileURL = fileURL.replace('1drv.ms', '1drv.ws');732 return exports.downloadLarge(fileURL, filePath, options);733};734/**735 * 根据蓝奏云地址下载其文件736 * @param fileURL 文件下载路径737 * @param filePath 文件保存位置,包括文件名738 * @param options node-fetch的参数739 * @returns {Promise<void>}740 */741exports.downloadLanzous = async (fileURL, filePath, options) => {742 // 采用https://api.vvhan.com/lanzou.html接口743 let apiUrl = 'https://api.vvhan.com/api/lz?url=';744 let api = apiUrl + fileURL;745 return new Promise((resolve, reject) => {746 exports.getJson(api).then(json => {747 if (!json.success) {748 reject('通过API[' + apiUrl + ']解析蓝奏云失败');749 } else {750 let defaultOption = {751 headers: {752 'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,ja;q=0.6,ko;q=0.5,de-DE;q=0.4,de;q=0.3,la;q=0.2' // 一定不能删除,否则无法下载753 }754 };755 exports.downloadLarge(json.download, filePath, {756 ...defaultOption,757 ...options || {}758 }).then(() => {759 console.log('蓝奏云文件[' + fileURL + ']下载成功,保存到:' + filePath + ',解析地址API[' + api + ']');760 resolve(filePath);761 }).catch(reject);762 }763 }).catch(reject);764 });765};766/**767 *768 * @param fileURL App下载的蓝奏云地址769 * @param appId AppId770 * @param appName App名称771 * @param version App版本772 * @param options773 * @returns {Promise<void>}774 */775exports.downloadLanzousApk = async (fileURL, appId, appName, version, options) => {776 version = version === undefined || version === null ? '' : '-' + version;777 let apkName = appId + version + '.apk';778 let filePath = path.join(exports.getApkFolder(), apkName);779 return new Promise((resolve, reject) => {780 if (!fs.existsSync(filePath)) {781 exports.downloadLanzous(fileURL, filePath, options).then(() => {782 resolve(filePath);783 }).catch(reject);784 } else {785 resolve(filePath);786 }787 });788};789/**790 * 获取Github基础地址791 * @param type 类型:github, cnpmjs, fastgit或简写792 * @returns {string}793 */794exports.getGithubUrl = (type) => {795 // https://doc.fastgit.org/zh-cn/node.html#%E8%8A%82%E7%82%B9%E5%88%97%E8%A1%A8796 let githubUrlLists = ['https://hub.fastgit.org', 'https://github.com.cnpmjs.org', 'https://github.com'];797 type = type === undefined || type === '' || type === null ? 'fastgit' : type;798 if (type === 'g' || type === 'git' || type === 'github' || type === 'default') {799 return githubUrlLists[2];800 } else if (type === 'c' || type === 'npm' || type === 'cnpm' || type === 'cnpmjs') {801 return githubUrlLists[1];802 } else {803 return githubUrlLists[0];804 }805}806/**807 * 使用不同的镜像路径下载最新release版本808 * @param user809 * @param rep810 * @param fileName 文件名称811 * @param savePath 保存路径(不含文件名)812 * @returns {Promise<void>}813 */814exports.downloadLatestRetry = async (user, rep, fileName, savePath) => {815 return new Promise((resolve, reject) => {816 exports.downloadLatest(user, rep, fileName, savePath, 'cnpmjs').then(fp => {817 resolve(fp);818 }).catch(err => {819 exports.downloadLatest(user, rep, fileName, savePath, 'fastgit').then(fp => {820 resolve(fp);821 }).catch(err2 => {822 exports.downloadLatest(user, rep, fileName, savePath, 'github').then(fp => {823 resolve(fp);824 }).catch(err3 => {825 reject('从cnpmjs, fastgit, github尝试下载均失败:' + err + err2 + err3);826 })827 })828 })829 });830}831/**832 * 下载Github发布的文件833 * @returns {Promise<unknown>}834 * @param user835 * @param rep836 * @param tag837 * @param fileName 文件名称838 * @param savePath 保存路径(不含文件名)839 * @param baseUrl_type 类型:github, cnpmjs, fastgit或简写840 */841exports.downloadGithub = async (user, rep, tag, fileName, savePath, baseUrl_type) => {842 if (baseUrl_type === undefined || baseUrl_type === '' || baseUrl_type === null) {843 baseUrl_type = exports.getGithubUrl();844 } else if (!baseUrl_type.startsWith('http')) {845 baseUrl_type = exports.getGithubUrl(baseUrl_type);846 }847 let downloadUrl = baseUrl_type/*.replace('hub.fas', 'download.fas')*/ + '/' + user + '/'848 + rep + '/releases/download/' + tag + '/' + fileName;849 return new Promise((resolve, reject) => {850 exports.downloadLarge(downloadUrl, path.join(savePath, fileName)).then(file => {851 resolve(file);852 }).catch(err => {853 reject(err);854 });855 });856}857/**858 * 获取Github最新的Tag859 * @returns {Promise<unknown>}860 * @param user861 * @param rep862 * @param baseUrl_type 类型:github, cnpmjs, fastgit或简写863 */864exports.getGithubLatestTag = async (user, rep, type) => {865 return new Promise((resolve, reject) => {866 // https://hub.fastgit.org/zxniuniu/YiyiNet/releases/latest867 let baseUrl = exports.getGithubUrl(type);868 let latestUrl = baseUrl + '/' + user + '/' + rep + '/releases/latest';869 exports.getRedirected(latestUrl).then(newUrl => {870 if (newUrl === null) {871 reject('获取[' + user + '/' + rep + ']版本失败,获取结果为空');872 }else{873 // 获取最新的版本信息874 let queryVer = newUrl.substring(newUrl.lastIndexOf('/') + 1, newUrl.length);875 console.log('获取[' + user + '/' + rep + ']新版本[' + queryVer + ']');876 resolve(queryVer);877 }878 }).catch(err => {879 reject(err);880 });881 });882}883/**884 * 下载Github发布的文件885 * @returns {Promise<unknown>}886 * @param user887 * @param rep888 * @param fileName 文件名称889 * @param savePath 保存路径(不含文件名)890 * @param type 类型:github, cnpmjs, fastgit或简写891 * @param queryVer 指定Tag892 */893exports.downloadLatest = async (user, rep, fileName, savePath, type, queryVer) => {894 let cachePath = exports.getElectronCachePath();895 savePath = savePath === undefined || savePath === '' || savePath === null ? cachePath : savePath;896 if(queryVer === undefined || queryVer === '' || queryVer === null ) {897 queryVer = await exports.getGithubLatestTag(user, rep, type); // .then(queryVer => {898 }899 return new Promise((resolve, reject) => {900 // https://hub.fastgit.org/zxniuniu/YiyiNet/releases/latest901 // let baseUrl = getGithubUrl(type);902 if (fileName.indexOf('{version}') > 0) {903 fileName = fileName.replace('{version}', '{ver}');904 }905 fileName = fileName.replace('{ver}', queryVer.replace('v', '').replace('release-', ''));906 let saveFile = path.join(savePath, fileName);907 // 判断当前文件是否已经下载908 let cacheCfgName = fileName + '.cfg';909 let cacheCfg = path.join(cachePath, cacheCfgName);910 if (fs.existsSync(cacheCfg) && fs.existsSync(saveFile)) {911 // TODO 解决是下载的最新,还是本来就是最新的912 resolve(saveFile);913 } else {914 // 获取到版本后进行下载915 exports.downloadGithub(user, rep, queryVer, fileName, savePath, type).then(file => {916 fs.writeFileSync(cacheCfg, queryVer);917 resolve(file);918 }).catch(err => {919 reject(err);920 });921 /*// https://hub.fastgit.org/zxniuniu/YiyiNet/releases/download/v1.6.3/YiyiNet-web-setup-1.6.3.exe922 let downloadUrl = baseUrl.replace('hub.fas', 'download.fas') + '/' + user + '/'923 + rep + '/releases/download/' + queryVer + '/' + fileName;924 downloadLarge(downloadUrl, saveFile).then(file => {925 fs.writeFileSync(cacheCfg, queryVer);926 resolve(saveFile);927 }).catch(err => {928 reject(err);929 });*/930 }931 /*}).catch(err => {932 reject(err);933 });*/934 });935}936/**937 * 下载Github发布的多个文件938 * @returns {Promise<unknown>}939 * @param user940 * @param rep941 * @param fileNameArray 文件名称,如['a.zip', 'b.zip']942 * @param savePath 保存路径(不含文件名)943 * @param type 类型:github, cnpmjs, fastgit或简写944 */945exports.downloadLatestMultiFile = async (user, rep, fileNameArray, savePath, type) => {946 let queryVer = await exports.getGithubLatestTag(user, rep, type);947 let maxConcurrencyDownload = store.get('MAX_CONCURRENCY_DOWNLOAD', 20);948 let mapper = fileName => exports.downloadLatest(user, rep, fileName, savePath, type, queryVer);949 return new Promise((resolve, reject) => {950 pFun.map(fileNameArray, mapper, {concurrency: Math.min(maxConcurrencyDownload, fileNameArray.length), stopOnError: false})951 .then(result => {952 if (fileNameArray.length === 1) {953 resolve(result[0]);954 } else {955 resolve(result);956 }957 }).catch(err => {958 reject(err);959 });960 });961}962// =====================================================================================================================963/**964 * 睡眠毫秒965 * @param ms 暂停毫秒数966 * @returns {Promise<unknown>}967 */968exports.sleep = (ms) => {969 return new Promise((resolve) => setTimeout(resolve, ms));970}971/**972 * 修改目录权限973 * @param dir974 * @param mode975 */976exports.changePermissions = (dir, mode) => {977 const files = fs.readdirSync(dir);978 files.forEach((file) => {979 const filePath = path.join(dir, file);980 fs.chmodSync(filePath, parseInt(mode, 8));981 if (fs.statSync(filePath).isDirectory()) {982 exports.changePermissions(filePath, mode);983 }984 });985};986/**987 * 移动文件夹988 * @param fromFolder989 * @param toFolder990 * @returns {Promise<unknown>}991 */992exports.moveFolder = (fromFolder, toFolder) => {993 return new Promise((resolve, reject) => {994 fse.move(fromFolder, toFolder, {overwrite: true}, err => {995 if (err) {996 reject(err);997 } else {998 resolve();999 }1000 })1001 });1002}1003/**1004 * 删除文件夹1005 * @param folder1006 * @see https://stackoverflow.com/a/42505874/30273901007 * @returns {Promise<unknown>}1008 */1009exports.removeFolder = (folder) => {1010 return new Promise((resolve, reject) => {1011 fse.remove(folder, err => {1012 if (err) {1013 reject(err);1014 } else {1015 resolve();1016 }1017 });1018 });1019 /*if (fs.existsSync(dir_path)) {1020 fs.readdirSync(dir_path).forEach(function (entry) {1021 let entry_path = path.join(dir_path, entry);1022 if (fs.lstatSync(entry_path).isDirectory()) {1023 delFolder(entry_path);1024 } else {1025 fs.unlinkSync(entry_path);1026 }1027 });1028 fs.rmdirSync(dir_path);1029 }*/1030}1031/**1032 * 根据图标生成指定大小的缩略图,以显示在菜单前1033 * @param name1034 * @param size1035 * @returns {*}1036 */1037exports.getIco = (name, size) => {1038 if (size === undefined) {1039 size = 16;1040 }1041 let img = nativeImage.createFromPath(path.join(__dirname, './../assets/icon/' + name));1042 if (size > 0) {1043 img = img.resize({width: size});1044 }1045 return img;1046};1047/**1048 * 检查Module是否安装,而不加载Module1049 * @param req_module1050 * @returns {boolean}1051 */1052exports.hasModule = (req_module) => {1053 try {1054 require.resolve(req_module);1055 return true;1056 } catch (e) {1057 return false;1058 }1059};1060/**1061 * 是否是调试的地址(用于菜单和打开开发者工具)1062 */1063exports.isDebugUrl = () => {1064 let url = config.mainUrl;1065 return !app.isPackaged || (app.isPackaged && (url.indexOf('localhost') >= 0 || url.indexOf('cnbeta.com') >= 0));1066};1067/**1068 * Require each JS file in the main dir1069 */1070function loadMainJS() {1071 const glob = require('glob');1072 var files = glob.sync(path.join(__dirname, 'main/*.js'));1073 files.forEach(function (file) {1074 require(file);1075 })1076}1077function asarPath() {1078 // https://newsn.net/say/electron-detect-asar.html1079 /*const path = require('path');1080 var path_arr=__dirname.split(path.sep);1081 var entry_relative = path.sep + ""; //入口文件相对于项目根目录1082 var res_relative = path.sep + "res" + path.sep; //资源文件夹相对于入口文件js1083 var res_dir=__dirname + res_relative;1084 if(path_arr.indexOf("app.asar")>=0){1085 res_dir = __dirname + entry_relative + ".." + res_relative;1086 }1087 var res_path=path.join(res_dir, 'res_name.dll');1088 console.log(res_path);1089 __dirname.split(path.sep).indexOf("app.asar")&gt;=0*/1090}1091/**1092 * package.json的内容1093 * @returns {*}1094 */1095exports.packageJson = () => {1096 let packagePath;1097 if (app.isPackaged) {1098 packagePath = path.join(__dirname, '..', 'package.json');1099 } else {1100 packagePath = "./../package.json";1101 }1102 return require(packagePath);1103}1104/**1105 * 切换显示/隐藏1106 */1107exports.toggleShowHide = (mainWindow) => {1108 if (mainWindow !== null) {1109 if (mainWindow.isVisible()) {1110 if (mainWindow.isFocused()) {1111 mainWindow.hide();1112 } else {1113 mainWindow.focus();1114 }1115 } else {1116 mainWindow.show();1117 mainWindow.focus();1118 }1119 }1120}1121ipcMain.answerRenderer('utils', (funcName) => {1122 let result = ''; // Function Not Found1123 if (typeof (eval(funcName)) == "function") {1124 result = eval(funcName + "();");1125 }1126 return result;1127});1128/*const {ipcRenderer: ipc} = require('electron-better-ipc');1129(async () => {1130 const cdport = await ipc.callMain('utils', 'getChromedriverPort');1131 console.log(cdport);...

Full Screen

Full Screen

context.js

Source:context.js Github

copy

Full Screen

...302 if (opts.chromedriverPort) {303 log.debug(`Using user-specified port ${opts.chromedriverPort} for chromedriver`);304 } else {305 // if a single port wasn't given, we'll look for a free one306 opts.chromedriverPort = await getChromedriverPort(opts.chromedriverPorts);307 }308 const details = context ? webviewHelpers.getWebviewDetails(adb, context) : undefined;309 if (!_.isEmpty(details)) {310 log.debug('Passing web view details to the Chromedriver constructor: ' +311 JSON.stringify(details, null, 2));312 }313 const chromedriver = new Chromedriver({314 port: opts.chromedriverPort,315 executable: opts.chromedriverExecutable,316 adb,317 cmdArgs: opts.chromedriverArgs,318 verbose: !!opts.showChromedriverLog,319 executableDir: opts.chromedriverExecutableDir,320 mappingPath: opts.chromedriverChromeMappingFile,...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var androidDriver = new AndroidDriver();2androidDriver.getChromedriverPort();3var androidDriver = new AndroidDriver();4androidDriver.getChromedriverBinary();5var androidDriver = new AndroidDriver();6androidDriver.getChromeArgs();7var androidDriver = new AndroidDriver();8androidDriver.getChromeWebStorageEnabled();9var androidDriver = new AndroidDriver();10androidDriver.getChromeConsoleLogsEnabled();11var androidDriver = new AndroidDriver();12androidDriver.getChromeDriverLogsEnabled();13var androidDriver = new AndroidDriver();14androidDriver.getChromeDriverLogsPath();15var androidDriver = new AndroidDriver();16androidDriver.getChromeBinary();17var androidDriver = new AndroidDriver();18androidDriver.getChromeLogFile();19var androidDriver = new AndroidDriver();20androidDriver.getChromePrefs();21var androidDriver = new AndroidDriver();22androidDriver.getChromeUseExistingChromeDriver();23var androidDriver = new AndroidDriver();24androidDriver.getChromeMinidumpPath();25var androidDriver = new AndroidDriver();26androidDriver.getChromeAndroidPackage();27var androidDriver = new AndroidDriver();28androidDriver.getChromeAndroidActivity();29var androidDriver = new AndroidDriver();30androidDriver.getChromeAndroidProcess();31var androidDriver = new AndroidDriver();32androidDriver.getChromeAndroidDeviceSerial();

Full Screen

Using AI Code Generation

copy

Full Screen

1var appiumAndroidDriver = require('appium-android-driver');2appiumAndroidDriver.getChromedriverPort();3var appiumAndroidDriver = require('appium-android-driver');4appiumAndroidDriver.getChromedriverPort();5var appiumAndroidDriver = require('appium-android-driver');6appiumAndroidDriver.getChromedriverPort();7var appiumAndroidDriver = require('appium-android-driver');8appiumAndroidDriver.getChromedriverPort();9var appiumAndroidDriver = require('appium-android-driver');10appiumAndroidDriver.getChromedriverPort();11var appiumAndroidDriver = require('appium-android-driver');12appiumAndroidDriver.getChromedriverPort();13var appiumAndroidDriver = require('appium-android-driver');14appiumAndroidDriver.getChromedriverPort();15var appiumAndroidDriver = require('appium-android-driver');16appiumAndroidDriver.getChromedriverPort();17var appiumAndroidDriver = require('appium-android-driver');18appiumAndroidDriver.getChromedriverPort();19var appiumAndroidDriver = require('appium-android-driver');20appiumAndroidDriver.getChromedriverPort();21var appiumAndroidDriver = require('appium-android-driver');22appiumAndroidDriver.getChromedriverPort();23var appiumAndroidDriver = require('app

Full Screen

Using AI Code Generation

copy

Full Screen

1var appiumAndroidDriver = require('appium-android-driver');2appiumAndroidDriver.getChromedriverPort();3var appiumAndroidDriver = require('appium-android-driver');4appiumAndroidDriver.getChromedriverPort();5var appiumAndroidDriver = require('appium-android-driver');6appiumAndroidDriver.getChromedriverPort();7var appiumAndroidDriver = require('appium-android-driver');8appiumAndroidDriver.getChromedriverPort();9var appiumAndroidDriver = require('appium-android-driver');10appiumAndroidDriver.getChromedriverPort();11var appiumAndroidDriver = require('appium-android-driver');12appiumAndroidDriver.getChromedriverPort();13var appiumAndroidDriver = require('appium-android-driver');14appiumAndroidDriver.getChromedriverPort();15var appiumAndroidDriver = require('appium-android-driver');16appiumAndroidDriver.getChromedriverPort();17var appiumAndroidDriver = require('appium-android-driver');18appiumAndroidDriver.getChromedriverPort();19var appiumAndroidDriver = require('appium-android-driver');20appiumAndroidDriver.getChromedriverPort();21var appiumAndroidDriver = require('appium-android-driver');22appiumAndroidDriver.getChromedriverPort();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 },5};6 .remote(options)7 .init()8 .getChromedriverPort()9 .then(function (port) {10 console.log("Chromedriver port is: " + port);11 })12 .end();13var webdriverio = require('webdriverio');14var options = {15 desiredCapabilities: {16 },17};18 .remote(options)19 .init()20 .getChromedriverPort()21 .then(function (port) {22 console.log("Chromedriver port is: " + port);23 })24 .end();25var webdriverio = require('webdriverio');26var options = {27 desiredCapabilities: {28 },29};30 .remote(options)31 .init()32 .getChromedriverPort()33 .then(function (port) {34 console.log("Chromedriver port is: " + port);35 })36 .end();37var webdriverio = require('webdriverio');38var options = {39 desiredCapabilities: {40 },41};

Full Screen

Using AI Code Generation

copy

Full Screen

1var driver = new AndroidDriver();2driver.getChromedriverPort();3var driver = new AndroidDriver();4driver.getChromedriverPort();5var driver = new AndroidDriver();6driver.getChromedriverPort();7var driver = new AndroidDriver();8driver.getChromedriverPort();9var driver = new AndroidDriver();10driver.getChromedriverPort();11var driver = new AndroidDriver();12driver.getChromedriverPort();13var driver = new AndroidDriver();14driver.getChromedriverPort();15var driver = new AndroidDriver();16driver.getChromedriverPort();17var driver = new AndroidDriver();18driver.getChromedriverPort();19var driver = new AndroidDriver();20driver.getChromedriverPort();21var driver = new AndroidDriver();22driver.getChromedriverPort();23var driver = new AndroidDriver();24driver.getChromedriverPort();25var driver = new AndroidDriver();26driver.getChromedriverPort();27var driver = new AndroidDriver();28driver.getChromedriverPort();

Full Screen

Using AI Code Generation

copy

Full Screen

1const AndroidDriver = require('appium-android-driver').AndroidDriver;2const driver = new AndroidDriver();3driver.getChromedriverPort();4getChromedriverPort () {5return 9515;6}7const AndroidDriver = require('appium-android-driver').AndroidDriver;8const driver = new AndroidDriver();9driver.getChromedriverPort();10getChromedriverPort () {11return 9515;12}13const AndroidDriver = require('appium-android-driver').AndroidDriver;14const driver = new AndroidDriver();15driver.getChromedriverPort();16getChromedriverPort () {17return 9515;18}19const AndroidDriver = require('appium-android-driver').AndroidDriver;20const driver = new AndroidDriver();21driver.getChromedriverPort();22getChromedriverPort () {23return 9515;24}25const AndroidDriver = require('appium-android-driver').AndroidDriver;26const driver = new AndroidDriver();27driver.getChromedriverPort();28getChromedriverPort () {29return 9515;30}31const AndroidDriver = require('appium-android-driver').AndroidDriver;32const driver = new AndroidDriver();33driver.getChromedriverPort();34getChromedriverPort () {35return 9515;36}37const AndroidDriver = require('appium-android-driver').AndroidDriver;38const driver = new AndroidDriver();39driver.getChromedriverPort();40getChromedriverPort () {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var chai = require('chai');3var chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5chai.should();6var expect = chai.expect;7var assert = chai.assert;8var chromedriverPort = 9515;9androidDriver.getChromedriverPort().then(function (port) {10 chromedriverPort = port;11 console.log("Chromedriver port from Appium Android Driver: " + port);12});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Android Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful