Best JavaScript code snippet using appium-android-driver
utils.js
Source:utils.js
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")>=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);...
context.js
Source:context.js
...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,...
Using AI Code Generation
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();
Using AI Code Generation
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
Using AI Code Generation
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();
Using AI Code Generation
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};
Using AI Code Generation
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();
Using AI Code Generation
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 () {
Using AI Code Generation
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});
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!