appium-android-driver 5.4.0 → 5.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/build/lib/android-helpers.js +12 -3
  2. package/build/lib/android-helpers.js.map +1 -0
  3. package/build/lib/bootstrap.js.map +1 -0
  4. package/build/lib/commands/actions.js.map +1 -0
  5. package/build/lib/commands/alert.js.map +1 -0
  6. package/build/lib/commands/app-management.js.map +1 -0
  7. package/build/lib/commands/context.js.map +1 -0
  8. package/build/lib/commands/coverage.js.map +1 -0
  9. package/build/lib/commands/element.js.map +1 -0
  10. package/build/lib/commands/emu-console.js.map +1 -0
  11. package/build/lib/commands/execute.js.map +1 -0
  12. package/build/lib/commands/file-actions.js.map +1 -0
  13. package/build/lib/commands/find.js.map +1 -0
  14. package/build/lib/commands/general.js.map +1 -0
  15. package/build/lib/commands/ime.js.map +1 -0
  16. package/build/lib/commands/index.js.map +1 -0
  17. package/build/lib/commands/intent.js.map +1 -0
  18. package/build/lib/commands/log.js.map +1 -0
  19. package/build/lib/commands/media-projection.js.map +1 -0
  20. package/build/lib/commands/network.js.map +1 -0
  21. package/build/lib/commands/performance.js.map +1 -0
  22. package/build/lib/commands/recordscreen.js.map +1 -0
  23. package/build/lib/commands/shell.js.map +1 -0
  24. package/build/lib/commands/streamscreen.js.map +1 -0
  25. package/build/lib/commands/system-bars.js.map +1 -0
  26. package/build/lib/commands/touch.js.map +1 -0
  27. package/build/lib/desired-caps.js.map +1 -0
  28. package/build/lib/driver.js.map +1 -0
  29. package/build/lib/logger.js.map +1 -0
  30. package/build/lib/uiautomator.js.map +1 -0
  31. package/build/lib/unlock-helpers.js.map +1 -0
  32. package/build/lib/utils.js.map +1 -0
  33. package/build/lib/webview-helpers.js.map +1 -0
  34. package/lib/android-helpers.js +8 -2
  35. package/package.json +2 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media-projection.js","names":["commands","DEFAULT_EXT","RECORDING_STARTUP_TIMEOUT_MS","RECORDING_STOP_TIMEOUT_MS","MIN_API_LEVEL","RECORDING_SERVICE_NAME","SETTINGS_HELPER_PKG_ID","RECORDING_ACTIVITY_NAME","RECORDING_ACTION_START","RECORDING_ACTION_STOP","RECORDINGS_ROOT","DEFAULT_FILENAME_FORMAT","uploadRecordedMedia","localFile","remotePath","uploadOptions","_","isEmpty","util","toInMemoryBase64","toString","user","pass","method","headers","fileFieldName","formFields","options","auth","net","uploadFile","adjustMediaExtension","name","toLower","endsWith","verifyMediaProjectionRecordingIsSupported","adb","apiLevel","getApiLevel","Error","MediaProjectionRecorder","constructor","isRunning","stdout","shell","includes","start","opts","cleanup","filename","maxDurationSec","priority","resolution","args","push","B","resolve","reject","setTimeout","pullRecent","recordings","ls","dstPath","path","join","tempDir","openDir","pull","stop","waitForCondition","waitMs","intervalMs","e","mobileStartMediaProjectionRecording","recorder","fname","moment","format","didStart","log","info","mobileIsMediaProjectionRecordingRunning","mobileStopMediaProjectionRecording","recentRecordingPath","size","fs","stat","debug","toReadableSizeString","rimraf","dirname"],"sources":["../../../lib/commands/media-projection.js"],"sourcesContent":["import _ from 'lodash';\nimport { waitForCondition } from 'asyncbox';\nimport { util, fs, net, tempDir } from 'appium/support';\nimport path from 'path';\nimport B from 'bluebird';\nimport { SETTINGS_HELPER_PKG_ID } from '../android-helpers';\nimport moment from 'moment';\n\n\nconst commands = {};\n\n// https://github.com/appium/io.appium.settings#internal-audio--video-recording\nconst DEFAULT_EXT = '.mp4';\nconst RECORDING_STARTUP_TIMEOUT_MS = 3 * 1000;\nconst RECORDING_STOP_TIMEOUT_MS = 3 * 1000;\nconst MIN_API_LEVEL = 29;\nconst RECORDING_SERVICE_NAME = `${SETTINGS_HELPER_PKG_ID}/.recorder.RecorderService`;\nconst RECORDING_ACTIVITY_NAME = `${SETTINGS_HELPER_PKG_ID}/io.appium.settings.Settings`;\nconst RECORDING_ACTION_START = `${SETTINGS_HELPER_PKG_ID}.recording.ACTION_START`;\nconst RECORDING_ACTION_STOP = `${SETTINGS_HELPER_PKG_ID}.recording.ACTION_STOP`;\nconst RECORDINGS_ROOT = `/storage/emulated/0/Android/data/${SETTINGS_HELPER_PKG_ID}/files`;\nconst DEFAULT_FILENAME_FORMAT = 'YYYY-MM-DDTHH-mm-ss';\n\n\nasync function uploadRecordedMedia (localFile, remotePath = null, uploadOptions = {}) {\n if (_.isEmpty(remotePath)) {\n return (await util.toInMemoryBase64(localFile)).toString();\n }\n\n const {user, pass, method, headers, fileFieldName, formFields} = uploadOptions;\n const options = {\n method: method || 'PUT',\n headers,\n fileFieldName,\n formFields,\n };\n if (user && pass) {\n options.auth = {user, pass};\n }\n await net.uploadFile(localFile, remotePath, options);\n return '';\n}\n\nfunction adjustMediaExtension (name) {\n return _.toLower(name).endsWith(DEFAULT_EXT) ? name : `${name}${DEFAULT_EXT}`;\n}\n\nasync function verifyMediaProjectionRecordingIsSupported (adb) {\n const apiLevel = await adb.getApiLevel();\n if (apiLevel < MIN_API_LEVEL) {\n throw new Error(`Media projection-based recording is not available on API Level ${apiLevel}. ` +\n `Minimum required API Level is ${MIN_API_LEVEL}.`);\n }\n}\n\n\nclass MediaProjectionRecorder {\n constructor (adb) {\n this.adb = adb;\n }\n\n async isRunning () {\n const stdout = await this.adb.shell([\n 'dumpsys', 'activity', 'services', RECORDING_SERVICE_NAME\n ]);\n return stdout.includes(RECORDING_SERVICE_NAME);\n }\n\n async start (opts = {}) {\n if (await this.isRunning()) {\n return false;\n }\n\n await this.cleanup();\n const {\n filename,\n maxDurationSec,\n priority,\n resolution,\n } = opts;\n const args = [\n 'am', 'start',\n '-n', RECORDING_ACTIVITY_NAME,\n '-a', RECORDING_ACTION_START,\n ];\n if (filename) {\n args.push('--es', 'filename', filename);\n }\n if (maxDurationSec) {\n args.push('--es', 'max_duration_sec', `${maxDurationSec}`);\n }\n if (priority) {\n args.push('--es', 'priority', priority);\n }\n if (resolution) {\n args.push('--es', 'resolution', resolution);\n }\n await this.adb.shell(args);\n await new B((resolve, reject) => {\n setTimeout(async () => {\n if (!await this.isRunning()) {\n return reject(new Error(\n `The media projection recording is not running after ${RECORDING_STARTUP_TIMEOUT_MS}ms. ` +\n `Please check the logcat output for more details.`\n ));\n }\n resolve();\n }, RECORDING_STARTUP_TIMEOUT_MS);\n });\n return true;\n }\n\n async cleanup () {\n await this.adb.shell([`rm -f ${RECORDINGS_ROOT}/*`]);\n }\n\n async pullRecent () {\n const recordings = await this.adb.ls(RECORDINGS_ROOT, ['-tr']);\n if (_.isEmpty(recordings)) {\n return null;\n }\n\n const dstPath = path.join(await tempDir.openDir(), recordings[0]);\n await this.adb.pull(`${RECORDINGS_ROOT}/${recordings[0]}`, dstPath);\n return dstPath;\n }\n\n async stop () {\n if (!await this.isRunning()) {\n return false;\n }\n\n await this.adb.shell([\n 'am', 'start',\n '-n', RECORDING_ACTIVITY_NAME,\n '-a', RECORDING_ACTION_STOP,\n ]);\n try {\n await waitForCondition(async () => !(await this.isRunning()), {\n waitMs: RECORDING_STOP_TIMEOUT_MS,\n intervalMs: 500,\n });\n } catch (e) {\n throw new Error(\n `The attempt to stop the current media projection recording timed out after ` +\n `${RECORDING_STOP_TIMEOUT_MS}ms`\n );\n }\n return true;\n }\n}\n\n\n/**\n * @typedef {Object} StartRecordingOptions\n *\n * @property {string?} resolution Maximum supported resolution on-device (Detected\n * automatically by the app itself), which usually equals to Full HD 1920x1080 on most\n * phones however you can change it to following supported resolutions\n * as well: \"1920x1080\", \"1280x720\", \"720x480\", \"320x240\", \"176x144\".\n * @property {number?} maxDurationSec [900] Default value: 900 seconds which means\n * maximum allowed duration is 15 minute, you can increase it if your test takes\n * longer than that.\n * @property {string?} priority [high] Means recording thread priority is maximum\n * however if you face performance drops during testing with recording enabled, you\n * can reduce recording priority to \"normal\" or \"low\".\n * @property {string?} filename You can type recording video file name as you want,\n * but recording currently supports only \"mp4\" format so your filename must end with \".mp4\".\n * An invalid file name will fail to start the recording.\n * If not provided then the current timestamp will be used as file name.\n */\n\n/**\n * Record the display of a real devices running Android 10 (API level 29) and higher.\n * The screen activity is recorded to a MPEG-4 file. Audio is also recorded by default\n * (only for apps that allow it in their manifests).\n * If another recording has been already started then the command will exit silently.\n * The previously recorded video file is deleted when a new recording session is started.\n * Recording continues it is stopped explicitly or until the timeout happens.\n *\n * @param {?StartRecordingOptions} options Available options.\n * @returns {boolean} True if a new recording has successfully started.\n * @throws {Error} If recording has failed to start or is not supported on the device under test.\n */\ncommands.mobileStartMediaProjectionRecording = async function mobileStartMediaProjectionRecording (options = {}) {\n await verifyMediaProjectionRecordingIsSupported(this.adb);\n\n const {resolution, priority, maxDurationSec, filename} = options;\n const recorder = new MediaProjectionRecorder(this.adb);\n const fname = adjustMediaExtension(filename || moment().format(DEFAULT_FILENAME_FORMAT));\n const didStart = await recorder.start({\n resolution,\n priority,\n maxDurationSec,\n filename: fname,\n });\n if (didStart) {\n this.log.info(`A new media projection recording '${fname}' has been successfully started`);\n } else {\n this.log.info('Another media projection recording is already in progress. There is nothing to start');\n }\n return didStart;\n};\n\n/**\n * Checks if a media projection-based recording is currently running.\n *\n * @returns {boolean} True if a recording is in progress.\n * @throws {Error} If a recording is not supported on the device under test.\n */\ncommands.mobileIsMediaProjectionRecordingRunning = async function mobileIsMediaProjectionRecordingRunning () {\n await verifyMediaProjectionRecordingIsSupported(this.adb);\n\n const recorder = new MediaProjectionRecorder(this.adb);\n return await recorder.isRunning();\n};\n\n/**\n * @typedef {Object} StopRecordingOptions\n *\n * @property {string?} remotePath The path to the remote location, where the resulting video should be uploaded.\n * The following protocols are supported: http/https, ftp.\n * Null or empty string value (the default setting) means the content of resulting\n * file should be encoded as Base64 and passed as the endpoont response value.\n * An exception will be thrown if the generated media file is too big to\n * fit into the available process memory.\n * @property {string?} user The name of the user for the remote authentication.\n * @property {string?} pass The password for the remote authentication.\n * @property {string?} method The http multipart upload method name. The 'PUT' one is used by default.\n * @property {Object?} headers Additional headers mapping for multipart http(s) uploads\n * @property {string?} fileFieldName [file] The name of the form field, where the file content BLOB should be stored for\n * http(s) uploads\n * @property {Object|Array<Pair>?} formFields Additional form fields for multipart http(s) uploads\n */\n\n/**\n * Stop a media projection-based recording.\n * If no recording has been started before then an error is thrown.\n * If the recording has been already finished before this API has been called\n * then the most recent recorded file is returned.\n *\n * @param {?StopRecordingOptions} options Available options.\n * @returns {string} Base64-encoded content of the recorded media file if 'remotePath'\n * parameter is falsy or an empty string.\n * @throws {Error} If there was an error while stopping a recording,\n * fetching the content of the remote media file,\n * or if a recording is not supported on the device under test.\n */\ncommands.mobileStopMediaProjectionRecording = async function mobileStopMediaProjectionRecording (options = {}) {\n await verifyMediaProjectionRecordingIsSupported(this.adb);\n\n const recorder = new MediaProjectionRecorder(this.adb);\n if (await recorder.stop()) {\n this.log.info('Successfully stopped a media projection recording. Pulling the recorded media');\n } else {\n this.log.info('Media projection recording is not running. There is nothing to stop');\n }\n const recentRecordingPath = await recorder.pullRecent();\n if (!recentRecordingPath) {\n throw new Error(`No recent media projection recording have been found. Did you start any?`);\n }\n\n const {remotePath} = options;\n if (_.isEmpty(remotePath)) {\n const {size} = await fs.stat(recentRecordingPath);\n this.log.debug(`The size of the resulting media projection recording is ${util.toReadableSizeString(size)}`);\n }\n try {\n return await uploadRecordedMedia(recentRecordingPath, remotePath, options);\n } finally {\n await fs.rimraf(path.dirname(recentRecordingPath));\n }\n};\n\n\nexport { commands };\nexport default commands;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAGA,MAAMA,QAAQ,GAAG,EAAjB;;AAGA,MAAMC,WAAW,GAAG,MAApB;AACA,MAAMC,4BAA4B,GAAG,IAAI,IAAzC;AACA,MAAMC,yBAAyB,GAAG,IAAI,IAAtC;AACA,MAAMC,aAAa,GAAG,EAAtB;AACA,MAAMC,sBAAsB,GAAI,GAAEC,sCAAuB,4BAAzD;AACA,MAAMC,uBAAuB,GAAI,GAAED,sCAAuB,8BAA1D;AACA,MAAME,sBAAsB,GAA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AT,GAA8C,eAAeA,kCAAf,CAAmDvD,OAAO,GAAG,EAA7D,EAAiE;EAC7G,MAAMQ,yCAAyC,CAAC,KAAKC,GAAN,CAA/C;EAEA,MAAMsC,QAAQ,GAAG,IAAIlC,uBAAJ,CAA4B,KAAKJ,GAAjC,CAAjB;;EACA,IAAI,MAAMsC,QAAQ,CAACN,IAAT,EAAV,EAA2B;IACzB,KAAKW,GAAL,CAASC,IAAT,CAAc,+EAAd;EACD,CAFD,MAEO;IACL,KAAKD,GAAL,CAASC,IAAT,CAAc,qEAAd;EACD;;EACD,MAAMG,mBAAmB,GAAG,MAAMT,QAAQ,CAACf,UAAT,EAAlC;;EACA,IAAI,CAACwB,mBAAL,EAA0B;IACxB,MAAM,IAAI5C,KAAJ,CAAW,0EAAX,CAAN;EACD;;EAED,MAAM;IAACzB;EAAD,IAAea,OAArB;;EACA,IAAIX,eAAA,CAAEC,OAAF,CAAUH,UAAV,CAAJ,EAA2B;IACzB,MAAM;MAACsE;IAAD,IAAS,MAAMC,WAAA,CAAGC,IAAH,CAAQH,mBAAR,CAArB;IACA,KAAKJ,GAAL,CAASQ,KAAT,CAAgB,2DAA0DrE,aAAA,CAAKsE,oBAAL,CAA0BJ,IAA1B,CAAgC,EAA1G;EACD;;EACD,IAAI;IACF,OAAO,MAAMxE,mBAAmB,CAACuE,mBAAD,EAAsBrE,UAAtB,EAAkCa,OAAlC,CAAhC;EACD,CAFD,SAEU;IACR,MAAM0D,WAAA,CAAGI,MAAH,CAAU1B,aAAA,CAAK2B,OAAL,CAAaP,mBAAb,CAAV,CAAN;EACD;AACF,CAxBD;;eA4BenF,Q"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"network.js","names":["commands","helpers","extensions","AIRPLANE_MODE_MASK","WIFI_MASK","DATA_MASK","GEO_EPSILON","Number","MIN_VALUE","getNetworkConnection","log","info","airplaneModeOn","adb","isAirplaneModeOn","connection","wifiOn","isWifiOn","dataOn","isDataOn","setNetworkConnection","type","shouldEnableAirplaneMode","shouldEnableWifi","shouldEnableDataConnection","currentState","isAirplaneModeEnabled","isWiFiEnabled","isDataEnabled","wrapBootstrapDisconnect","setAirplaneMode","broadcastAirplaneMode","setWifiState","setDataState","isEmulator","wifi","toggleData","data","setWifiAndData","toggleWiFi","toggleFlightMode","flightMode","setGeoLocation","location","getGeoLocation","e","warn","message","latitude","longitude","altitude","mobileRefreshGpsCache","opts","timeoutMs","refreshGeoLocationCache","parseFloat","KeyCode","UP","DOWN","RIGHT","CENTER","toggleLocationServices","api","getApiLevel","providers","getLocationProviders","isGpsEnabled","indexOf","toggleGPSLocationProvider","seq","push","keyevent","toggleSetting","errors","NotYetImplementedError","setting","preKeySeq","_","isNull","openSettingsActivity","key","doKey","appPackage","appActivity","getFocusedPackageAndActivity","waitForNotActivity","ign","back","B","delay","wrapped","bootstrap","ignoreUnexpectedShutdown","restart","start","disableAndroidWatchers","acceptSslCerts","Object","assign"],"sources":["../../../lib/commands/network.js"],"sourcesContent":["import _ from 'lodash';\nimport { errors } from 'appium/driver';\nimport B from 'bluebird';\n\nlet commands = {}, helpers = {}, extensions = {};\n\nconst AIRPLANE_MODE_MASK = 0b001;\nconst WIFI_MASK = 0b010;\nconst DATA_MASK = 0b100;\n// The value close to zero, but not zero, is needed\n// to trick JSON generation and send a float value instead of an integer,\n// This allows strictly-typed clients, like Java, to properly\n// parse it. Otherwise float 0.0 is always represented as integer 0 in JS.\n// The value must not be greater than DBL_EPSILON (https://opensource.apple.com/source/Libc/Libc-498/include/float.h)\nconst GEO_EPSILON = Number.MIN_VALUE;\n\ncommands.getNetworkConnection = async function getNetworkConnection () {\n this.log.info('Getting network connection');\n let airplaneModeOn = await this.adb.isAirplaneModeOn();\n let connection = airplaneModeOn ? AIRPLANE_MODE_MASK : 0;\n\n // no need to check anything else if we are in airplane mode\n if (!airplaneModeOn) {\n let wifiOn = await this.isWifiOn();\n connection |= (wifiOn ? WIFI_MASK : 0);\n let dataOn = await this.adb.isDataOn();\n connection |= (dataOn ? DATA_MASK : 0);\n }\n\n return connection;\n};\n\n/**\n * decoupling to override the behaviour in other drivers like UiAutomator2.\n */\ncommands.isWifiOn = async function isWifiOn () {\n return await this.adb.isWifiOn();\n};\n\ncommands.setNetworkConnection = async function setNetworkConnection (type) {\n this.log.info('Setting network connection');\n // decode the input\n const shouldEnableAirplaneMode = (type & AIRPLANE_MODE_MASK) !== 0;\n const shouldEnableWifi = (type & WIFI_MASK) !== 0;\n const shouldEnableDataConnection = (type & DATA_MASK) !== 0;\n\n const currentState = await this.getNetworkConnection();\n const isAirplaneModeEnabled = (currentState & AIRPLANE_MODE_MASK) !== 0;\n const isWiFiEnabled = (currentState & WIFI_MASK) !== 0;\n const isDataEnabled = (currentState & DATA_MASK) !== 0;\n\n if (shouldEnableAirplaneMode !== isAirplaneModeEnabled) {\n await this.wrapBootstrapDisconnect(async () => {\n await this.adb.setAirplaneMode(shouldEnableAirplaneMode);\n });\n await this.wrapBootstrapDisconnect(async () => {\n await this.adb.broadcastAirplaneMode(shouldEnableAirplaneMode);\n });\n } else {\n this.log.info(`Not changing airplane mode, since it is already ` +\n `${shouldEnableAirplaneMode ? 'enabled' : 'disabled'}`);\n }\n\n if (shouldEnableWifi === isWiFiEnabled && shouldEnableDataConnection === isDataEnabled) {\n this.log.info('Not changing data connection/Wi-Fi states, since they are already set to expected values');\n if (await this.adb.isAirplaneModeOn()) {\n return AIRPLANE_MODE_MASK | currentState;\n }\n return ~AIRPLANE_MODE_MASK & currentState;\n }\n\n await this.wrapBootstrapDisconnect(async () => {\n if (shouldEnableWifi !== isWiFiEnabled) {\n await this.setWifiState(shouldEnableWifi);\n } else {\n this.log.info(`Not changing Wi-Fi state, since it is already ` +\n `${shouldEnableWifi ? 'enabled' : 'disabled'}`);\n }\n\n if (shouldEnableAirplaneMode) {\n this.log.info('Not changing data connection state, because airplane mode is enabled');\n } else if (shouldEnableDataConnection === isDataEnabled) {\n this.log.info(`Not changing data connection state, since it is already ` +\n `${shouldEnableDataConnection ? 'enabled' : 'disabled'}`);\n } else {\n await this.adb.setDataState(shouldEnableDataConnection, this.isEmulator());\n }\n });\n\n return await this.getNetworkConnection();\n};\n\n/**\n * decoupling to override behaviour in other drivers like UiAutomator2.\n */\ncommands.setWifiState = async function setWifiState (wifi) {\n await this.adb.setWifiState(wifi, this.isEmulator());\n};\n\ncommands.toggleData = async function toggleData () {\n let data = !(await this.adb.isDataOn());\n this.log.info(`Turning network data ${data ? 'on' : 'off'}`);\n await this.wrapBootstrapDisconnect(async () => {\n await this.adb.setWifiAndData({data}, this.isEmulator());\n });\n};\n\ncommands.toggleWiFi = async function toggleWiFi () {\n let wifi = !(await this.adb.isWifiOn());\n this.log.info(`Turning WiFi ${wifi ? 'on' : 'off'}`);\n await this.wrapBootstrapDisconnect(async () => {\n await this.adb.setWifiAndData({wifi}, this.isEmulator());\n });\n};\n\ncommands.toggleFlightMode = async function toggleFlightMode () {\n /*\n * TODO: Implement isRealDevice(). This method fails on\n * real devices, it should throw a NotYetImplementedError\n */\n let flightMode = !(await this.adb.isAirplaneModeOn());\n this.log.info(`Turning flight mode ${flightMode ? 'on' : 'off'}`);\n await this.wrapBootstrapDisconnect(async () => {\n await this.adb.setAirplaneMode(flightMode);\n });\n await this.wrapBootstrapDisconnect(async () => {\n await this.adb.broadcastAirplaneMode(flightMode);\n });\n};\n\ncommands.setGeoLocation = async function setGeoLocation (location) {\n await this.adb.setGeoLocation(location, this.isEmulator());\n try {\n return await this.getGeoLocation();\n } catch (e) {\n this.log.warn(`Could not get the current geolocation info: ${e.message}`);\n this.log.warn(`Returning the default zero'ed values`);\n return {\n latitude: GEO_EPSILON,\n longitude: GEO_EPSILON,\n altitude: GEO_EPSILON,\n };\n }\n};\n\n/**\n * @typedef {Object} GpsCacheRefreshOptions\n * @property {number} timeoutMs [20000] The maximum number of milliseconds\n * to block until GPS cache is refreshed. Providing zero or a negative\n * value to it skips waiting completely.\n */\n\n/**\n * Sends an async request to refresh the GPS cache.\n * This feature only works if the device under test has\n * Google Play Services installed. In case the vanilla\n * LocationManager is used the device API level must be at\n * version 30 (Android R) or higher.\n *\n * @param {GpsCacheRefreshOptions} opts\n */\ncommands.mobileRefreshGpsCache = async function mobileRefreshGpsCache (opts = {}) {\n const { timeoutMs } = opts;\n await this.adb.refreshGeoLocationCache(timeoutMs);\n};\n\ncommands.getGeoLocation = async function getGeoLocation () {\n const {latitude, longitude, altitude} = await this.adb.getGeoLocation();\n return {\n latitude: parseFloat(latitude) || GEO_EPSILON,\n longitude: parseFloat(longitude) || GEO_EPSILON,\n altitude: parseFloat(altitude) || GEO_EPSILON,\n };\n};\n// https://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_DPAD_CENTER\n// in the android docs, this is how the keycodes are defined\nconst KeyCode = {\n UP: 19,\n DOWN: 20,\n RIGHT: 22,\n CENTER: 23\n};\ncommands.toggleLocationServices = async function toggleLocationServices () {\n this.log.info('Toggling location services');\n let api = await this.adb.getApiLevel();\n if (this.isEmulator()) {\n let providers = await this.adb.getLocationProviders();\n let isGpsEnabled = providers.indexOf('gps') !== -1;\n await this.adb.toggleGPSLocationProvider(!isGpsEnabled);\n return;\n }\n\n if (api > 15) {\n let seq = [KeyCode.UP, KeyCode.UP];\n if (api === 16) {\n // This version of Android has a \"parent\" button in its action bar\n seq.push(KeyCode.DOWN);\n } else if (api < 28) {\n // Newer versions of Android have the toggle in the Action bar\n seq = [KeyCode.RIGHT, KeyCode.RIGHT, KeyCode.UP];\n /*\n * Once the Location services switch is OFF, it won't receive focus\n * when going back to the Location Services settings screen unless we\n * send a dummy keyevent (UP) *before* opening the settings screen\n */\n await this.adb.keyevent(KeyCode.UP);\n } else if (api >= 28) {\n // Even newer versions of android have the toggle in a bar below the action bar\n // this means a single right click will cause it to be selected.\n seq = [KeyCode.RIGHT];\n await this.adb.keyevent(KeyCode.UP);\n }\n await this.toggleSetting('LOCATION_SOURCE_SETTINGS', seq);\n } else {\n // There's no global location services toggle on older Android versions\n throw new errors.NotYetImplementedError();\n }\n};\n\nhelpers.toggleSetting = async function toggleSetting (setting, preKeySeq) {\n /*\n * preKeySeq is the keyevent sequence to send over ADB in order\n * to position the cursor on the right option.\n * By default it's [up, up, down] because we usually target the 1st item in\n * the screen, and sometimes when opening settings activities the cursor is\n * already positionned on the 1st item, but we can't know for sure\n */\n if (_.isNull(preKeySeq)) {\n preKeySeq = [KeyCode.UP, KeyCode.UP, KeyCode.DOWN];\n }\n\n await this.openSettingsActivity(setting);\n\n for (let key of preKeySeq) {\n await this.doKey(key);\n }\n\n let {appPackage, appActivity} = await this.adb.getFocusedPackageAndActivity();\n\n /*\n * Click and handle potential ADB disconnect that occurs on official\n * emulator when the network connection is disabled\n */\n await this.wrapBootstrapDisconnect(async () => {\n await this.doKey(KeyCode.CENTER);\n });\n\n /*\n * In one particular case (enable Location Services), a pop-up is\n * displayed on some platforms so the user accepts or refuses that Google\n * collects location data. So we wait for that pop-up to open, if it\n * doesn't then proceed\n */\n try {\n await this.adb.waitForNotActivity(appPackage, appActivity, 5000);\n await this.doKey(KeyCode.RIGHT);\n await this.doKey(KeyCode.CENTER);\n await this.adb.waitForNotActivity(appPackage, appActivity, 5000);\n } catch (ign) {}\n\n await this.adb.back();\n};\n\nhelpers.doKey = async function doKey (key) {\n // TODO: Confirm we need this delay. Seems to work without it.\n await B.delay(2000);\n await this.adb.keyevent(key);\n};\n\nhelpers.wrapBootstrapDisconnect = async function wrapBootstrapDisconnect (wrapped) {\n if (!this.bootstrap) {\n return await wrapped();\n }\n\n this.bootstrap.ignoreUnexpectedShutdown = true;\n try {\n await wrapped();\n await this.adb.restart();\n await this.bootstrap.start(this.opts.appPackage, this.opts.disableAndroidWatchers, this.opts.acceptSslCerts);\n } finally {\n this.bootstrap.ignoreUnexpectedShutdown = false;\n }\n};\n\nObject.assign(extensions, commands, helpers);\nexport { commands, helpers };\nexport default extensions;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AACA;;AAEA,IAAIA,QAAQ,GAAG,EAAf;AAAA,IAAmBC,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,MAAM,KAAK/C,GAAL,CAASwE,kBAAT,CAA4BH,UAA5B,EAAwCC,WAAxC,EAAqD,IAArD,CAAN;EACD,CALD,CAKE,OAAOG,GAAP,EAAY,CAAE;;EAEhB,MAAM,KAAKzE,GAAL,CAAS0E,IAAT,EAAN;AACD,CA1CD;;AA4CAtF,OAAO,CAACgF,KAAR,GAAgB,eAAeA,KAAf,CAAsBD,GAAtB,EAA2B;EAEzC,MAAMQ,iBAAA,CAAEC,KAAF,CAAQ,IAAR,CAAN;EACA,MAAM,KAAK5E,GAAL,CAAS0D,QAAT,CAAkBS,GAAlB,CAAN;AACD,CAJD;;AAMA/E,OAAO,CAAC4B,uBAAR,GAAkC,eAAeA,uBAAf,CAAwC6D,OAAxC,EAAiD;EACjF,IAAI,CAAC,KAAKC,SAAV,EAAqB;IACnB,OAAO,MAAMD,OAAO,EAApB;EACD;;EAED,KAAKC,SAAL,CAAeC,wBAAf,GAA0C,IAA1C;;EACA,IAAI;IACF,MAAMF,OAAO,EAAb;IACA,MAAM,KAAK7E,GAAL,CAASgF,OAAT,EAAN;IACA,MAAM,KAAKF,SAAL,CAAeG,KAAf,CAAqB,KAAK1C,IAAL,CAAU8B,UAA/B,EAA2C,KAAK9B,IAAL,CAAU2C,sBAArD,EAA6E,KAAK3C,IAAL,CAAU4C,cAAvF,CAAN;EACD,CAJD,SAIU;IACR,KAAKL,SAAL,CAAeC,wBAAf,GAA0C,KAA1C;EACD;AACF,CAbD;;AAeAK,MAAM,CAACC,MAAP,CAAchG,UAAd,EAA0BF,QAA1B,EAAoCC,OAApC;eAEeC,U"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"performance.js","names":["commands","helpers","extensions","NETWORK_KEYS","CPU_KEYS","BATTERY_KEYS","MEMORY_KEYS","SUPPORTED_PERFORMANCE_DATA_TYPES","Object","freeze","cpuinfo","memoryinfo","batteryinfo","networkinfo","MEMINFO_TITLES","NATIVE","DALVIK","EGL","GL","MTRACK","TOTAL","HEAP","RETRY_PAUSE_MS","parseMeminfoForApi19To29","entries","valDict","type","subType","nativePss","nativePrivateDirty","nativeHeapSize","nativeHeapAllocatedSize","dalvikPss","dalvikPrivateDirty","eglPss","eglPrivateDirty","glPss","glPrivateDirty","length","totalPss","totalPrivateDirty","parseMeminfoForApiBelow19","parseMeminfoForApiAbove29","nativeRss","dalvikRss","totalRss","getPerformanceDataTypes","_","keys","getPerformanceData","packageName","dataType","retries","toLower","getBatteryInfo","getCPUInfo","getMemoryInfo","getNetworkTrafficInfo","Error","JSON","stringify","retryInterval","output","adb","shell","e","stderr","log","info","usagesPattern","RegExp","escapeRegExp","match","exec","debug","cmd","data","power","parseInt","split","trim","Number","isNaN","clone","toString","apiLevel","getApiLevel","line","filter","Boolean","headers","values","map","header","returnValue","bucketDuration","bucketStart","activeTime","rxBytes","rxPackets","txBytes","txPackets","operations","index","fromXtstats","indexOf","start","delimiter","end","pendingBytes","substring","arrayList","j","k","returnIndex","i","isEqual","isUndefined","assign"],"sources":["../../../lib/commands/performance.js"],"sourcesContent":["import _ from 'lodash';\nimport { retryInterval } from 'asyncbox';\n\nconst commands = {}, helpers = {}, extensions = {};\n\nconst NETWORK_KEYS = [\n ['bucketStart', 'activeTime', 'rxBytes', 'rxPackets', 'txBytes', 'txPackets', 'operations', 'bucketDuration'],\n ['st', 'activeTime', 'rb', 'rp', 'tb', 'tp', 'op', 'bucketDuration']\n];\nconst CPU_KEYS = ['user', 'kernel'];\nconst BATTERY_KEYS = ['power'];\nconst MEMORY_KEYS = [\n 'totalPrivateDirty', 'nativePrivateDirty', 'dalvikPrivateDirty',\n 'eglPrivateDirty', 'glPrivateDirty',\n 'totalPss', 'nativePss', 'dalvikPss', 'eglPss', 'glPss',\n 'nativeHeapAllocatedSize', 'nativeHeapSize',\n 'nativeRss', 'dalvikRss', 'totalRss'\n];\nconst SUPPORTED_PERFORMANCE_DATA_TYPES = Object.freeze({\n cpuinfo: 'the amount of cpu by user and kernel process - cpu information for applications on real devices and simulators',\n memoryinfo: 'the amount of memory used by the process - memory information for applications on real devices and simulators',\n batteryinfo: 'the remaining battery power - battery power information for applications on real devices and simulators',\n networkinfo: 'the network statistics - network rx/tx information for applications on real devices and simulators'\n});\nconst MEMINFO_TITLES = Object.freeze({\n NATIVE: 'Native',\n DALVIK: 'Dalvik',\n EGL: 'EGL',\n GL: 'GL',\n MTRACK: 'mtrack',\n TOTAL: 'TOTAL',\n HEAP: 'Heap'\n});\nconst RETRY_PAUSE_MS = 1000;\n\n/**\n * API level between 18 and 30\n * ['<System Type>', '<Memory Type>', <pss total>, <private dirty>, <private clean>, <swapPss dirty>, <heap size>, <heap alloc>, <heap free>]\n * except 'TOTAL', which skips the second type name\n * !!! valDict gets mutated\n */\nfunction parseMeminfoForApi19To29 (entries, valDict) {\n const [type, subType] = entries;\n if (type === MEMINFO_TITLES.NATIVE && subType === MEMINFO_TITLES.HEAP) {\n [,, valDict.nativePss, valDict.nativePrivateDirty,,, valDict.nativeHeapSize, valDict.nativeHeapAllocatedSize] = entries;\n } else if (type === MEMINFO_TITLES.DALVIK && subType === MEMINFO_TITLES.HEAP) {\n [,, valDict.dalvikPss, valDict.dalvikPrivateDirty] = entries;\n } else if (type === MEMINFO_TITLES.EGL && subType === MEMINFO_TITLES.MTRACK) {\n [,, valDict.eglPss, valDict.eglPrivateDirty] = entries;\n } else if (type === MEMINFO_TITLES.GL && subType === MEMINFO_TITLES.MTRACK) {\n [,, valDict.glPss, valDict.glPrivateDirty] = entries;\n } else if (type === MEMINFO_TITLES.TOTAL && entries.length === 8) {\n // there are two totals, and we only want the full listing, which has 8 entries\n [, valDict.totalPss, valDict.totalPrivateDirty] = entries;\n }\n}\n\n/**\n * ['<System Type', '<pps>', '<shared dirty>', '<private dirty>', '<heap size>', '<heap alloc>', '<heap free>']\n * !!! valDict gets mutated\n */\nfunction parseMeminfoForApiBelow19 (entries, valDict) {\n const type = entries[0];\n if (type === MEMINFO_TITLES.NATIVE) {\n [, valDict.nativePss,, valDict.nativePrivateDirty, valDict.nativeHeapSize, valDict.nativeHeapAllocatedSize] = entries;\n } else if (type === MEMINFO_TITLES.DALVIK) {\n [, valDict.dalvikPss,, valDict.dalvikPrivateDirty] = entries;\n } else if (type === MEMINFO_TITLES.EGL) {\n [, valDict.eglPss,, valDict.eglPrivateDirty] = entries;\n } else if (type === MEMINFO_TITLES.GL) {\n [, valDict.glPss,, valDict.glPrivateDirty] = entries;\n } else if (type === MEMINFO_TITLES.TOTAL) {\n [, valDict.totalPss,, valDict.totalPrivateDirty] = entries;\n }\n}\n\n/**\n * API level 30 and above\n * ['<System Type>', '<Memory Type>', <pss total>, <private dirty>, <private clean>, <swapPss dirty>, <rss total>, <heap size>, <heap alloc>, <heap free>]\n * !!! valDict gets mutated\n */\nfunction parseMeminfoForApiAbove29 (entries, valDict) {\n const [type, subType] = entries;\n if (type === MEMINFO_TITLES.NATIVE && subType === MEMINFO_TITLES.HEAP) {\n [,, valDict.nativePss, valDict.nativePrivateDirty,,, valDict.nativeRss, valDict.nativeHeapSize, valDict.nativeHeapAllocatedSize] = entries;\n } else if (type === MEMINFO_TITLES.DALVIK && subType === MEMINFO_TITLES.HEAP) {\n [,, valDict.dalvikPss, valDict.dalvikPrivateDirty,,, valDict.dalvikRss] = entries;\n } else if (type === MEMINFO_TITLES.EGL && subType === MEMINFO_TITLES.MTRACK) {\n [,, valDict.eglPss, valDict.eglPrivateDirty] = entries;\n } else if (type === MEMINFO_TITLES.GL && subType === MEMINFO_TITLES.MTRACK) {\n [,, valDict.glPss, valDict.glPrivateDirty] = entries;\n } else if (type === MEMINFO_TITLES.TOTAL && entries.length === 9) {\n // has 9 entries\n [, valDict.totalPss, valDict.totalPrivateDirty,,, valDict.totalRss] = entries;\n }\n}\n\n//\n// returns the information type of the system state which is supported to read as like cpu, memory, network traffic, and battery.\n// output - array like below\n// [cpuinfo, batteryinfo, networkinfo, memoryinfo]\n//\ncommands.getPerformanceDataTypes = function getPerformanceDataTypes () {\n return _.keys(SUPPORTED_PERFORMANCE_DATA_TYPES);\n};\n\n/**\n * @returns The information type of the system state which is supported to read as like cpu, memory, network traffic, and battery.\n * input - (packageName) the package name of the application\n * (dataType) the type of system state which wants to read. It should be one of the keys of the SUPPORTED_PERFORMANCE_DATA_TYPES\n * (dataReadTimeout) the number of attempts to read\n * output - table of the performance data, The first line of the table represents the type of data. The remaining lines represent the values of the data.\n *\n * in case of battery info : [[power], [23]]\n * in case of memory info : [[totalPrivateDirty, nativePrivateDirty, dalvikPrivateDirty, eglPrivateDirty, glPrivateDirty, totalPss,\n * nativePss, dalvikPss, eglPss, glPss, nativeHeapAllocatedSize, nativeHeapSize], [18360, 8296, 6132, null, null, 42588, 8406, 7024, null, null, 26519, 10344]]\n * in case of network info : [[bucketStart, activeTime, rxBytes, rxPackets, txBytes, txPackets, operations, bucketDuration,],\n * [1478091600000, null, 1099075, 610947, 928, 114362, 769, 0, 3600000], [1478095200000, null, 1306300, 405997, 509, 46359, 370, 0, 3600000]]\n * in case of network info : [[st, activeTime, rb, rp, tb, tp, op, bucketDuration], [1478088000, null, null, 32115296, 34291, 2956805, 25705, 0, 3600],\n * [1478091600, null, null, 2714683, 11821, 1420564, 12650, 0, 3600], [1478095200, null, null, 10079213, 19962, 2487705, 20015, 0, 3600],\n * [1478098800, null, null, 4444433, 10227, 1430356, 10493, 0, 3600]]\n * in case of cpu info : [[user, kernel], [0.9, 1.3]]\n */\ncommands.getPerformanceData = async function getPerformanceData (packageName, dataType, retries = 2) {\n switch (_.toLower(dataType)) {\n case 'batteryinfo':\n return await this.getBatteryInfo(retries);\n case 'cpuinfo':\n return await this.getCPUInfo(packageName, retries);\n case 'memoryinfo':\n return await this.getMemoryInfo(packageName, retries);\n case 'networkinfo':\n return await this.getNetworkTrafficInfo(retries);\n default:\n throw new Error(`No performance data of type '${dataType}' found. ` +\n `Only the following values are supported: ${JSON.stringify(SUPPORTED_PERFORMANCE_DATA_TYPES, ' ', 2)}`);\n }\n};\n\nhelpers.getCPUInfo = async function getCPUInfo (packageName, retries = 2) {\n // TODO: figure out why this is\n // sometimes, the function of 'adb.shell' fails. when I tested this function on the target of 'Galaxy Note5',\n // adb.shell(dumpsys cpuinfo) returns cpu datas for other application packages, but I can't find the data for packageName.\n // It usually fails 30 times and success for the next time,\n // Since then, he has continued to succeed.\n return await retryInterval(retries, RETRY_PAUSE_MS, async () => {\n let output;\n try {\n output = await this.adb.shell(['dumpsys', 'cpuinfo']);\n } catch (e) {\n if (e.stderr) {\n this.log.info(e.stderr);\n }\n throw e;\n }\n // `output` will be something like\n // +0% 2209/io.appium.android.apis: 0.1% user + 0.2% kernel / faults: 70 minor\n const usagesPattern =\n new RegExp(`^.+\\\\/${_.escapeRegExp(packageName)}:\\\\D+([\\\\d.]+)%\\\\s+user\\\\s+\\\\+\\\\s+([\\\\d.]+)%\\\\s+kernel`, 'm');\n const match = usagesPattern.exec(output);\n if (!match) {\n this.log.debug(output);\n throw new Error(`Unable to parse cpu usage data for '${packageName}'. Check the server log for more details`);\n }\n return [CPU_KEYS, [match[1], match[2]]];\n });\n};\n\nhelpers.getBatteryInfo = async function getBatteryInfo (retries = 2) {\n return await retryInterval(retries, RETRY_PAUSE_MS, async () => {\n let cmd = ['dumpsys', 'battery', '|', 'grep', 'level'];\n let data = await this.adb.shell(cmd);\n if (!data) throw new Error('No data from dumpsys'); //eslint-disable-line curly\n\n let power = parseInt((data.split(':')[1] || '').trim(), 10);\n\n if (!Number.isNaN(power)) {\n return [_.clone(BATTERY_KEYS), [power.toString()]];\n } else {\n throw new Error(`Unable to parse battery data: '${data}'`);\n }\n });\n};\n\nhelpers.getMemoryInfo = async function getMemoryInfo (packageName, retries = 2) {\n return await retryInterval(retries, RETRY_PAUSE_MS, async () => {\n const cmd = [\n 'dumpsys', 'meminfo', `'${packageName}'`,\n '|', 'grep', '-E',\n `'${MEMINFO_TITLES.NATIVE}|${MEMINFO_TITLES.DALVIK}|${MEMINFO_TITLES.EGL}` +\n `|${MEMINFO_TITLES.GL}|${MEMINFO_TITLES.TOTAL}'`\n ];\n const data = await this.adb.shell(cmd);\n if (!data) {\n throw new Error('No data from dumpsys');\n }\n const valDict = {totalPrivateDirty: ''};\n const apiLevel = await this.adb.getApiLevel();\n for (const line of data.split('\\n')) {\n const entries = line.trim().split(/\\s+/).filter(Boolean);\n if (apiLevel >= 30) {\n parseMeminfoForApiAbove29(entries, valDict);\n } else if (apiLevel > 18 && apiLevel < 30) {\n parseMeminfoForApi19To29(entries, valDict);\n } else {\n parseMeminfoForApiBelow19(entries, valDict);\n }\n }\n if (valDict.totalPrivateDirty && valDict.totalPrivateDirty !== 'nodex') {\n const headers = _.clone(MEMORY_KEYS);\n const values = headers.map((header) => valDict[header]);\n return [headers, values];\n }\n\n throw new Error(`Unable to parse memory data: '${data}'`);\n });\n};\n\nhelpers.getNetworkTrafficInfo = async function getNetworkTrafficInfo (retries = 2) {\n return await retryInterval(retries, RETRY_PAUSE_MS, async () => {\n let returnValue = [];\n let bucketDuration, bucketStart, activeTime, rxBytes, rxPackets, txBytes, txPackets, operations;\n\n let cmd = ['dumpsys', 'netstats'];\n let data = await this.adb.shell(cmd);\n if (!data) throw new Error('No data from dumpsys'); //eslint-disable-line curly\n\n // In case of network traffic information, it is different for the return data between emulator and real device.\n // the return data of emulator\n // Xt stats:\n // Pending bytes: 39250\n // History since boot:\n // ident=[[type=WIFI, subType=COMBINED, networkId=\"WiredSSID\"]] uid=-1 set=ALL tag=0x0\n // NetworkStatsHistory: bucketDuration=3600000\n // bucketStart=1478098800000 activeTime=31824 rxBytes=21502 rxPackets=78 txBytes=17748 txPackets=90 operations=0\n //\n // 7.1\n // Xt stats:\n // Pending bytes: 481487\n // History since boot:\n // ident=[{type=MOBILE, subType=COMBINED, subscriberId=310260..., metered=true}] uid=-1 set=ALL tag=0x0\n // NetworkStatsHistory: bucketDuration=3600\n // st=1483984800 rb=0 rp=0 tb=12031 tp=184 op=0\n // st=1483988400 rb=0 rp=0 tb=38476 tp=587 op=0\n // st=1483999200 rb=315616 rp=400 tb=94800 tp=362 op=0\n // st=1484002800 rb=15826 rp=20 tb=4738 tp=16 op=0\n //\n // the return data of real device\n // Xt stats:\n // Pending bytes: 0\n // History since boot:\n // ident=[{type=MOBILE, subType=COMBINED, subscriberId=450050...}] uid=-1 set=ALL tag=0x0\n // NetworkStatsHistory: bucketDuration=3600\n // st=1478088000 rb=32115296 rp=34291 tb=2956805 tp=25705 op=0\n // st=1478091600 rb=2714683 rp=11821 tb=1420564 tp=12650 op=0\n // st=1478095200 rb=10079213 rp=19962 tb=2487705 tp=20015 op=0\n // st=1478098800 rb=4444433 rp=10227 tb=1430356 tp=10493 op=0\n let index = 0;\n let fromXtstats = data.indexOf('Xt stats:');\n\n let start = data.indexOf('Pending bytes:', fromXtstats);\n let delimiter = data.indexOf(':', start + 1);\n let end = data.indexOf('\\n', delimiter + 1);\n let pendingBytes = data.substring(delimiter + 1, end).trim();\n\n if (end > delimiter) {\n start = data.indexOf('bucketDuration', end + 1);\n delimiter = data.indexOf('=', start + 1);\n end = data.indexOf('\\n', delimiter + 1);\n bucketDuration = data.substring(delimiter + 1, end).trim();\n }\n\n if (start >= 0) {\n data = data.substring(end + 1, data.length);\n let arrayList = data.split('\\n');\n\n if (arrayList.length > 0) {\n start = -1;\n\n for (let j = 0; j < NETWORK_KEYS.length; ++j) {\n start = arrayList[0].indexOf(NETWORK_KEYS[j][0]);\n\n if (start >= 0) {\n index = j;\n returnValue[0] = [];\n\n for (let k = 0; k < NETWORK_KEYS[j].length; ++k) {\n returnValue[0][k] = NETWORK_KEYS[j][k];\n }\n break;\n }\n }\n\n let returnIndex = 1;\n for (let i = 0; i < arrayList.length; i++) {\n data = arrayList[i];\n start = data.indexOf(NETWORK_KEYS[index][0]);\n\n if (start >= 0) {\n delimiter = data.indexOf('=', start + 1);\n end = data.indexOf(' ', delimiter + 1);\n bucketStart = data.substring(delimiter + 1, end).trim();\n\n if (end > delimiter) {\n start = data.indexOf(NETWORK_KEYS[index][1], end + 1);\n if (start >= 0) {\n delimiter = data.indexOf('=', start + 1);\n end = data.indexOf(' ', delimiter + 1);\n activeTime = data.substring(delimiter + 1, end).trim();\n }\n }\n\n if (end > delimiter) {\n start = data.indexOf(NETWORK_KEYS[index][2], end + 1);\n if (start >= 0) {\n delimiter = data.indexOf('=', start + 1);\n end = data.indexOf(' ', delimiter + 1);\n rxBytes = data.substring(delimiter + 1, end).trim();\n }\n }\n\n if (end > delimiter) {\n start = data.indexOf(NETWORK_KEYS[index][3], end + 1);\n if (start >= 0) {\n delimiter = data.indexOf('=', start + 1);\n end = data.indexOf(' ', delimiter + 1);\n rxPackets = data.substring(delimiter + 1, end).trim();\n }\n }\n\n if (end > delimiter) {\n start = data.indexOf(NETWORK_KEYS[index][4], end + 1);\n if (start >= 0) {\n delimiter = data.indexOf('=', start + 1);\n end = data.indexOf(' ', delimiter + 1);\n txBytes = data.substring(delimiter + 1, end).trim();\n }\n }\n\n if (end > delimiter) {\n start = data.indexOf(NETWORK_KEYS[index][5], end + 1);\n if (start >= 0) {\n delimiter = data.indexOf('=', start + 1);\n end = data.indexOf(' ', delimiter + 1);\n txPackets = data.substring(delimiter + 1, end).trim();\n }\n }\n\n if (end > delimiter) {\n start = data.indexOf(NETWORK_KEYS[index][6], end + 1);\n if (start >= 0) {\n delimiter = data.indexOf('=', start + 1);\n end = data.length;\n operations = data.substring(delimiter + 1, end).trim();\n\n }\n }\n returnValue[returnIndex++] = [bucketStart, activeTime, rxBytes, rxPackets, txBytes, txPackets, operations, bucketDuration];\n }\n }\n }\n }\n\n if (!_.isEqual(pendingBytes, '') && !_.isUndefined(pendingBytes) && !_.isEqual(pendingBytes, 'nodex')) {\n return returnValue;\n } else {\n throw new Error(`Unable to parse network traffic data: '${data}'`);\n }\n });\n};\n\nObject.assign(extensions, commands, helpers);\nexport {\n commands, helpers, SUPPORTED_PERFORMANCE_DATA_TYPES, CPU_KEYS, MEMORY_KEYS,\n BATTERY_KEYS, NETWORK_KEYS,\n};\nexport default extensions;\n\n"],"mappings":";;;;;;;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,EAAwB,OAAxB,CAArE,EAAuG;MACrG,OAAOf,WAAP;IACD,CAFD,MAEO;MACL,MAAM,IAAIpC,KAAJ,CAAW,0CAAyCkB,IAAK,GAAzD,CAAN;IACD;EACF,CArJY,CAAb;AAsJD,CAvJD;;AAyJApE,MAAM,CAAC8G,MAAP,CAAcpH,UAAd,EAA0BF,QAA1B,EAAoCC,OAApC;eAKeC,U"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recordscreen.js","names":["commands","RETRY_PAUSE","RETRY_TIMEOUT","MAX_RECORDING_TIME_SEC","MAX_TIME_SEC","DEFAULT_RECORDING_TIME_SEC","PROCESS_SHUTDOWN_TIMEOUT","SCREENRECORD_BINARY","DEFAULT_EXT","MIN_EMULATOR_API_LEVEL","FFMPEG_BINARY","system","isWindows","uploadRecordedMedia","localFile","remotePath","uploadOptions","_","isEmpty","util","toInMemoryBase64","toString","user","pass","method","headers","fileFieldName","formFields","options","auth","net","uploadFile","verifyScreenRecordIsSupported","adb","isEmulator","apiLevel","getApiLevel","Error","scheduleScreenRecord","recordingProperties","log","stopped","timer","videoSize","bitRate","timeLimit","bugReport","currentTimeLimit","hasValue","currentTimeLimitInt","parseInt","isNaN","pathOnDevice","uuidV4","substring","recordingProc","screenrecord","on","currentDuration","getDuration","asSeconds","toFixed","debug","timeLimitInt","chunkDuration","e","error","stack","start","waitForCondition","fileExists","waitMs","intervalMs","records","push","recordingProcess","mergeScreenRecords","mediaFiles","fs","which","configContent","map","x","join","configFile","path","resolve","dirname","writeFile","result","Math","floor","Date","args","info","exec","terminateBackgroundScreenRecording","force","pids","getPIDsByName","p","shell","err","message","startRecordingScreen","forceRestart","stopRecordingScreen","warn","_screenRecordingProperties","record","rimraf","timeout","parseFloat","timing","Timer","isRunning","stop","errorAndThrow","tmpRoot","tempDir","openDir","localRecords","posix","basename","pull","last","resultFilePath","length","size","stat","toReadableSizeString"],"sources":["../../../lib/commands/recordscreen.js"],"sourcesContent":["import _ from 'lodash';\nimport { waitForCondition } from 'asyncbox';\nimport { util, fs, net, tempDir, system, timing } from 'appium/support';\nimport { exec } from 'teen_process';\nimport path from 'path';\n\n\nconst commands = {};\n\nconst RETRY_PAUSE = 300;\nconst RETRY_TIMEOUT = 5000;\nconst MAX_RECORDING_TIME_SEC = 60 * 3;\nconst MAX_TIME_SEC = 60 * 30;\nconst DEFAULT_RECORDING_TIME_SEC = MAX_RECORDING_TIME_SEC;\nconst PROCESS_SHUTDOWN_TIMEOUT = 10 * 1000;\nconst SCREENRECORD_BINARY = 'screenrecord';\nconst DEFAULT_EXT = '.mp4';\nconst MIN_EMULATOR_API_LEVEL = 27;\nconst FFMPEG_BINARY = `ffmpeg${system.isWindows() ? '.exe' : ''}`;\n\nasync function uploadRecordedMedia (localFile, remotePath = null, uploadOptions = {}) {\n if (_.isEmpty(remotePath)) {\n return (await util.toInMemoryBase64(localFile)).toString();\n }\n\n const {user, pass, method, headers, fileFieldName, formFields} = uploadOptions;\n const options = {\n method: method || 'PUT',\n headers,\n fileFieldName,\n formFields,\n };\n if (user && pass) {\n options.auth = {user, pass};\n }\n await net.uploadFile(localFile, remotePath, options);\n return '';\n}\n\nasync function verifyScreenRecordIsSupported (adb, isEmulator) {\n const apiLevel = await adb.getApiLevel();\n if (isEmulator && apiLevel < MIN_EMULATOR_API_LEVEL) {\n throw new Error(`Screen recording does not work on emulators running Android API level less than ${MIN_EMULATOR_API_LEVEL}`);\n }\n if (apiLevel < 19) {\n throw new Error(`Screen recording not available on API Level ${apiLevel}. Minimum API Level is 19.`);\n }\n}\n\nasync function scheduleScreenRecord (adb, recordingProperties, log = null) {\n if (recordingProperties.stopped) {\n return;\n }\n\n const {\n timer,\n videoSize,\n bitRate,\n timeLimit,\n bugReport,\n } = recordingProperties;\n\n let currentTimeLimit = MAX_RECORDING_TIME_SEC;\n if (util.hasValue(recordingProperties.currentTimeLimit)) {\n const currentTimeLimitInt = parseInt(recordingProperties.currentTimeLimit, 10);\n if (!isNaN(currentTimeLimitInt) && currentTimeLimitInt < MAX_RECORDING_TIME_SEC) {\n currentTimeLimit = currentTimeLimitInt;\n }\n }\n const pathOnDevice = `/sdcard/${util.uuidV4().substring(0, 8)}${DEFAULT_EXT}`;\n const recordingProc = adb.screenrecord(pathOnDevice, {\n videoSize,\n bitRate,\n timeLimit: currentTimeLimit,\n bugReport,\n });\n\n recordingProc.on('end', () => {\n if (recordingProperties.stopped || !util.hasValue(timeLimit)) {\n return;\n }\n const currentDuration = timer.getDuration().asSeconds.toFixed(0);\n log?.debug(`The overall screen recording duration is ${currentDuration}s so far`);\n const timeLimitInt = parseInt(timeLimit, 10);\n if (isNaN(timeLimitInt) || currentDuration >= timeLimitInt) {\n log?.debug('There is no need to start the next recording chunk');\n return;\n }\n\n recordingProperties.currentTimeLimit = timeLimitInt - currentDuration;\n const chunkDuration = recordingProperties.currentTimeLimit < MAX_RECORDING_TIME_SEC\n ? recordingProperties.currentTimeLimit\n : MAX_RECORDING_TIME_SEC;\n log?.debug(`Starting the next ${chunkDuration}s-chunk ` +\n `of screen recording in order to achieve ${timeLimitInt}s total duration`);\n (async () => {\n try {\n await scheduleScreenRecord(adb, recordingProperties, log);\n } catch (e) {\n log?.error(e.stack);\n recordingProperties.stopped = true;\n }\n })();\n });\n\n await recordingProc.start(0);\n try {\n await waitForCondition(async () => await adb.fileExists(pathOnDevice),\n {waitMs: RETRY_TIMEOUT, intervalMs: RETRY_PAUSE});\n } catch (e) {\n throw new Error(`The expected screen record file '${pathOnDevice}' does not exist after ${RETRY_TIMEOUT}ms. ` +\n `Is ${SCREENRECORD_BINARY} utility available and operational on the device under test?`);\n }\n\n recordingProperties.records.push(pathOnDevice);\n recordingProperties.recordingProcess = recordingProc;\n}\n\nasync function mergeScreenRecords (mediaFiles, log = null) {\n try {\n await fs.which(FFMPEG_BINARY);\n } catch (e) {\n throw new Error(`${FFMPEG_BINARY} utility is not available in PATH. Please install it from https://www.ffmpeg.org/`);\n }\n const configContent = mediaFiles\n .map((x) => `file '${x}'`)\n .join('\\n');\n const configFile = path.resolve(path.dirname(mediaFiles[0]), 'config.txt');\n await fs.writeFile(configFile, configContent, 'utf8');\n log?.debug(`Generated ffmpeg merging config '${configFile}' with items:\\n${configContent}`);\n const result = path.resolve(path.dirname(mediaFiles[0]), `merge_${Math.floor(new Date())}${DEFAULT_EXT}`);\n const args = ['-safe', '0', '-f', 'concat', '-i', configFile, '-c', 'copy', result];\n log?.info(`Initiating screen records merging using the command '${FFMPEG_BINARY} ${args.join(' ')}'`);\n await exec(FFMPEG_BINARY, args);\n return result;\n}\n\nasync function terminateBackgroundScreenRecording (adb, force = true) {\n const pids = (await adb.getPIDsByName(SCREENRECORD_BINARY))\n .map((p) => `${p}`);\n if (_.isEmpty(pids)) {\n return false;\n }\n\n try {\n await adb.shell(['kill', force ? '-15' : '-2', ...pids]);\n await waitForCondition(async () => _.isEmpty(await adb.getPIDsByName(SCREENRECORD_BINARY)), {\n waitMs: PROCESS_SHUTDOWN_TIMEOUT,\n intervalMs: 500,\n });\n return true;\n } catch (err) {\n throw new Error(`Unable to stop the background screen recording: ${err.message}`);\n }\n}\n\n\n/**\n * @typedef {Object} StartRecordingOptions\n *\n * @property {?string} remotePath - The path to the remote location, where the captured video should be uploaded.\n * The following protocols are supported: http/https, ftp.\n * Null or empty string value (the default setting) means the content of resulting\n * file should be encoded as Base64 and passed as the endpount response value.\n * An exception will be thrown if the generated media file is too big to\n * fit into the available process memory.\n * This option only has an effect if there is screen recording process in progreess\n * and `forceRestart` parameter is not set to `true`.\n * @property {?string} user - The name of the user for the remote authentication. Only works if `remotePath` is provided.\n * @property {?string} pass - The password for the remote authentication. Only works if `remotePath` is provided.\n * @property {?string} method [PUT] - The http multipart upload method name. Only works if `remotePath` is provided.\n * @property {?Object} headers - Additional headers mapping for multipart http(s) uploads\n * @property {?string} fileFieldName [file] - The name of the form field, where the file content BLOB should be stored for\n * http(s) uploads\n * @property {?Object|Array<Pair>} formFields - Additional form fields for multipart http(s) uploads\n * @property {?string} videoSize - The format is widthxheight.\n * The default value is the device's native display resolution (if supported),\n * 1280x720 if not. For best results,\n * use a size supported by your device's Advanced Video Coding (AVC) encoder.\n * For example, \"1280x720\"\n * @property {?boolean} bugReport - Set it to `true` in order to display additional information on the video overlay,\n * such as a timestamp, that is helpful in videos captured to illustrate bugs.\n * This option is only supported since API level 27 (Android P).\n * @property {?string|number} timeLimit - The maximum recording time, in seconds. The default value is 180 (3 minutes).\n * The maximum value is 1800 (30 minutes). If the passed value is greater than 180 then\n * the algorithm will try to schedule multiple screen recording chunks and merge the\n * resulting videos into a single media file using `ffmpeg` utility.\n * If the utility is not available in PATH then the most recent screen recording chunk is\n * going to be returned.\n * @property {?string|number} bitRate - The video bit rate for the video, in bits per second.\n * The default value is 4000000 (4 Mbit/s). You can increase the bit rate to improve video quality,\n * but doing so results in larger movie files.\n * @property {?boolean} forceRestart - Whether to try to catch and upload/return the currently running screen recording\n * (`false`, the default setting) or ignore the result of it and start a new recording\n * immediately (`true`).\n */\n\n/**\n * Record the display of a real devices running Android 4.4 (API level 19) and higher.\n * Emulators are supported since API level 27 (Android P).\n * It records screen activity to an MPEG-4 file. Audio is not recorded with the video file.\n * If screen recording has been already started then the command will stop it forcefully and start a new one.\n * The previously recorded video file will be deleted.\n *\n * @param {?StartRecordingOptions} options - The available options.\n * @returns {string} Base64-encoded content of the recorded media file if\n * any screen recording is currently running or an empty string.\n * @throws {Error} If screen recording has failed to start or is not supported on the device under test.\n */\ncommands.startRecordingScreen = async function startRecordingScreen (options = {}) {\n await verifyScreenRecordIsSupported(this.adb, this.isEmulator());\n\n let result = '';\n const {videoSize, timeLimit = DEFAULT_RECORDING_TIME_SEC, bugReport, bitRate, forceRestart} = options;\n if (!forceRestart) {\n result = await this.stopRecordingScreen(options);\n }\n\n if (await terminateBackgroundScreenRecording(this.adb, true)) {\n this.log.warn(`There were some ${SCREENRECORD_BINARY} process leftovers running ` +\n `in the background. Make sure you stop screen recording each time after it is started, ` +\n `otherwise the recorded media might quickly exceed all the free space on the device under test.`);\n }\n\n if (!_.isEmpty(this._screenRecordingProperties)) {\n for (const record of (this._screenRecordingProperties.records || [])) {\n await this.adb.rimraf(record);\n }\n this._screenRecordingProperties = null;\n }\n\n const timeout = parseFloat(timeLimit);\n if (isNaN(timeout) || timeout > MAX_TIME_SEC || timeout <= 0) {\n throw new Error(`The timeLimit value must be in range [1, ${MAX_TIME_SEC}] seconds. ` +\n `The value of '${timeLimit}' has been passed instead.`);\n }\n\n this._screenRecordingProperties = {\n timer: new timing.Timer().start(),\n videoSize,\n timeLimit,\n currentTimeLimit: timeLimit,\n bitRate,\n bugReport,\n records: [],\n recordingProcess: null,\n stopped: false,\n };\n await scheduleScreenRecord(this.adb, this._screenRecordingProperties, this.log);\n return result;\n};\n\n/**\n * @typedef {Object} StopRecordingOptions\n *\n * @property {?string} remotePath - The path to the remote location, where the resulting video should be uploaded.\n * The following protocols are supported: http/https, ftp.\n * Null or empty string value (the default setting) means the content of resulting\n * file should be encoded as Base64 and passed as the endpount response value.\n * An exception will be thrown if the generated media file is too big to\n * fit into the available process memory.\n * @property {?string} user - The name of the user for the remote authentication.\n * @property {?string} pass - The password for the remote authentication.\n * @property {?string} method - The http multipart upload method name. The 'PUT' one is used by default.\n * @property {?Object} headers - Additional headers mapping for multipart http(s) uploads\n * @property {?string} fileFieldName [file] - The name of the form field, where the file content BLOB should be stored for\n * http(s) uploads\n * @property {?Object|Array<Pair>} formFields - Additional form fields for multipart http(s) uploads\n */\n\n/**\n * Stop recording the screen.\n * If no screen recording has been started before then the method returns an empty string.\n *\n * @param {?StopRecordingOptions} options - The available options.\n * @returns {string} Base64-encoded content of the recorded media file if 'remotePath'\n * parameter is falsy or an empty string.\n * @throws {Error} If there was an error while getting the name of a media file\n * or the file content cannot be uploaded to the remote location\n * or screen recording is not supported on the device under test.\n */\ncommands.stopRecordingScreen = async function stopRecordingScreen (options = {}) {\n await verifyScreenRecordIsSupported(this.adb, this.isEmulator());\n\n if (!_.isEmpty(this._screenRecordingProperties)) {\n this._screenRecordingProperties.stopped = true;\n }\n\n try {\n await terminateBackgroundScreenRecording(this.adb, false);\n } catch (err) {\n this.log.warn(err.message);\n if (!_.isEmpty(this._screenRecordingProperties)) {\n this.log.warn('The resulting video might be corrupted');\n }\n }\n\n if (_.isEmpty(this._screenRecordingProperties)) {\n this.log.info(`Screen recording has not been previously started by Appium. There is nothing to stop`);\n return '';\n }\n\n if (this._screenRecordingProperties.recordingProcess && this._screenRecordingProperties.recordingProcess.isRunning) {\n try {\n await this._screenRecordingProperties.recordingProcess.stop('SIGINT', PROCESS_SHUTDOWN_TIMEOUT);\n } catch (e) {\n this.log.errorAndThrow(`Unable to stop screen recording within ${PROCESS_SHUTDOWN_TIMEOUT}ms`);\n }\n this._screenRecordingProperties.recordingProcess = null;\n }\n\n if (_.isEmpty(this._screenRecordingProperties.records)) {\n this.log.errorAndThrow(`No screen recordings have been stored on the device so far. ` +\n `Are you sure the ${SCREENRECORD_BINARY} utility works as expected?`);\n }\n\n const tmpRoot = await tempDir.openDir();\n try {\n const localRecords = [];\n for (const pathOnDevice of this._screenRecordingProperties.records) {\n localRecords.push(path.resolve(tmpRoot, path.posix.basename(pathOnDevice)));\n await this.adb.pull(pathOnDevice, _.last(localRecords));\n await this.adb.rimraf(pathOnDevice);\n }\n let resultFilePath = _.last(localRecords);\n if (localRecords.length > 1) {\n this.log.info(`Got ${localRecords.length} screen recordings. Trying to merge them`);\n try {\n resultFilePath = await mergeScreenRecords(localRecords, this.log);\n } catch (e) {\n this.log.warn(`Cannot merge the recorded files. The most recent screen recording is going to be returned as the result. ` +\n `Original error: ${e.message}`);\n }\n }\n if (_.isEmpty(options.remotePath)) {\n const {size} = await fs.stat(resultFilePath);\n this.log.debug(`The size of the resulting screen recording is ${util.toReadableSizeString(size)}`);\n }\n return await uploadRecordedMedia(resultFilePath, options.remotePath, options);\n } finally {\n await fs.rimraf(tmpRoot);\n this._screenRecordingProperties = null;\n }\n};\n\n\nexport { commands };\nexport default commands;\n"],"mapp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F;;IACD,IAAItF,eAAA,CAAEC,OAAF,CAAUU,OAAO,CAACb,UAAlB,CAAJ,EAAmC;MACjC,MAAM;QAACiH;MAAD,IAAS,MAAMlD,WAAA,CAAGmD,IAAH,CAAQH,cAAR,CAArB;MACA,KAAKtF,GAAL,CAASsB,KAAT,CAAgB,iDAAgD3C,aAAA,CAAK+G,oBAAL,CAA0BF,IAA1B,CAAgC,EAAhG;IACD;;IACD,OAAO,MAAMnH,mBAAmB,CAACiH,cAAD,EAAiBlG,OAAO,CAACb,UAAzB,EAAqCa,OAArC,CAAhC;EACD,CAtBD,SAsBU;IACR,MAAMkD,WAAA,CAAGgC,MAAH,CAAUQ,OAAV,CAAN;IACA,KAAKV,0BAAL,GAAkC,IAAlC;EACD;AACF,CA9DD;;eAkEe5G,Q"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shell.js","names":["ADB_SHELL_FEATURE","commands","mobileShell","opts","ensureFeatureEnabled","command","args","timeout","includeStderr","_","isString","errors","InvalidArgumentError","adbArgs","adb","executable","defaultArgs","isArray","log","debug","path","util","quote","stdout","stderr","exec","err","errorAndThrow","message"],"sources":["../../../lib/commands/shell.js"],"sourcesContent":["import _ from 'lodash';\nimport { exec } from 'teen_process';\nimport { util } from 'appium/support';\nimport { errors } from 'appium/driver';\n\nconst ADB_SHELL_FEATURE = 'adb_shell';\n\nlet commands = {};\n\ncommands.mobileShell = async function mobileShell (opts = {}) {\n this.ensureFeatureEnabled(ADB_SHELL_FEATURE);\n\n const {\n command,\n args = [],\n timeout = 20000,\n includeStderr,\n } = opts;\n\n if (!_.isString(command)) {\n throw new errors.InvalidArgumentError(`The 'command' argument is mandatory`);\n }\n\n const adbArgs = [\n ...this.adb.executable.defaultArgs,\n 'shell',\n command,\n ...(_.isArray(args) ? args : [args])\n ];\n this.log.debug(`Running '${this.adb.executable.path} ${util.quote(adbArgs)}'`);\n try {\n const {stdout, stderr} = await exec(this.adb.executable.path, adbArgs, {timeout});\n if (includeStderr) {\n return {\n stdout,\n stderr\n };\n }\n return stdout;\n } catch (err) {\n this.log.errorAndThrow(`Cannot execute the '${command}' shell command. ` +\n `Original error: ${err.message}. ` +\n `StdOut: ${err.stdout}. StdErr: ${err.stderr}`);\n }\n};\n\nexport { commands };\nexport default commands;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AAEA,MAAMA,iBAAiB,GAAG,WAA1B;AAEA,IAAIC,QAAQ,GAAG,EAAf;;;AAEAA,QAAQ,CAACC,WAAT,GAAuB,eAAeA,WAAf,CAA4BC,IAAI,GAAG,EAAnC,EAAuC;EAC5D,KAAKC,oBAAL,CAA0BJ,iBAA1B;EAEA,MAAM;IACJK,OADI;IAEJC,IAAI,GAAG,EAFH;IAGJC,OAAO,GAAG,KAHN;IAIJC;EAJI,IAKFL,IALJ;;EAOA,IAAI,CAACM,eAAA,CAAEC,QAAF,CAAWL,OAAX,CAAL,EAA0B;IACxB,MAAM,IAAIM,cAAA,CAAOC,oBAAX,CAAiC,qCAAjC,CAAN;EACD;;EAED,MAAMC,OAAO,GAAG,CACd,GAAG,KAAKC,GAAL,CAASC,UAAT,CAAoBC,WADT,EAEd,OAFc,EAGdX,OAHc,EAId,IAAII,eAAA,CAAEQ,OAAF,CAAUX,IAAV,IAAkBA,IAAlB,GAAyB,CAACA,IAAD,CAA7B,CAJc,CAAhB;EAMA,KAAKY,GAAL,CAASC,KAAT,CAAgB,YAAW,KAAKL,GAAL,CAASC,UAAT,CAAoBK,IAAK,IAAGC,aAAA,CAAKC,KAAL,CAAWT,OAAX,CAAoB,GAA3E;;EACA,IAAI;IACF,MAAM;MAACU,MAAD;MAASC;IAAT,IAAmB,MAAM,IAAAC,kBAAA,EAAK,KAAKX,GAAL,CAASC,UAAT,CAAoBK,IAAzB,EAA+BP,OAA/B,EAAwC;MAACN;IAAD,CAAxC,CAA/B;;IACA,IAAIC,aAAJ,EAAmB;MACjB,OAAO;QACLe,MADK;QAELC;MAFK,CAAP;IAID;;IACD,OAAOD,MAAP;EACD,CATD,CASE,OAAOG,GAAP,EAAY;IACZ,KAAKR,GAAL,CAASS,aAAT,CAAwB,uBAAsBtB,OAAQ,mBAA/B,GACpB,mBAAkBqB,GAAG,CAACE,OAAQ,IADV,GAEpB,WAAUF,GAAG,CAACH,MAAO,aAAYG,GAAG,CAACF,MAAO,EAF/C;EAGD;AACF,CAnCD;;eAsCevB,Q"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streamscreen.js","names":["commands","RECORDING_INTERVAL_SEC","STREAMING_STARTUP_TIMEOUT_MS","GSTREAMER_BINARY","system","isWindows","GST_INSPECT_BINARY","REQUIRED_GST_PLUGINS","avdec_h264","h264parse","jpegenc","tcpserversink","multipartmux","SCREENRECORD_BINARY","GST_TUTORIAL_URL","DEFAULT_HOST","TCP_HOST","DEFAULT_PORT","DEFAULT_QUALITY","DEFAULT_BITRATE","BOUNDARY_STRING","ADB_SCREEN_STREAMING_FEATURE","createStreamingLogger","streamName","udid","logger","getLogger","_","truncate","length","omission","verifyStreamingRequirements","adb","trim","shell","Error","gstreamerCheckPromises","binaryName","push","fs","which","e","B","all","moduleCheckPromises","name","modName","toPairs","stdout","exec","includes","getDeviceInfo","log","output","result","key","pattern","match","debug","parseInt","curDeviceId","initDeviceStreamingProc","deviceInfo","opts","width","height","bitRate","adjustedWidth","adjustedHeight","adjustedBitrate","screenRecordCmd","adbArgs","executable","defaultArgs","deviceStreaming","spawn","path","on","code","signal","isStarted","deviceStreamingLogger","errorsListener","chunk","stderr","toString","startupListener","isEmpty","info","util","quote","waitForCondition","waitMs","intervalMs","errorAndThrow","message","removeListener","initGstreamerPipeline","deviceStreamingProc","quality","tcpPort","considerRotation","logPipelineDetails","gstreamerPipeline","SubProcess","Math","max","fps","stdio","gstreamerLogger","gstOutputListener","didFail","rep","start","checkPortStatus","ign","extractRemoteAddress","req","headers","socket","remoteAddress","connection","mobileStartScreenStreaming","options","ensureFeatureEnabled","host","port","pathname","isUndefined","_screenStreamingProps","kill","mjpegSocket","mjpegServer","resolve","reject","net","createConnection","http","createServer","res","currentPathname","url","parse","writeHead","Connection","write","end","Pragma","pipe","warn","listen","error","timeout","isRunning","stop","destroy","listening","close","mobileStopScreenStreaming","e1"],"sources":["../../../lib/commands/streamscreen.js"],"sourcesContent":["import _ from 'lodash';\nimport { fs, system, logger, util } from 'appium/support';\nimport { exec, SubProcess } from 'teen_process';\nimport { checkPortStatus } from 'portscanner';\nimport http from 'http';\nimport net from 'net';\nimport B from 'bluebird';\nimport { waitForCondition } from 'asyncbox';\nimport { spawn } from 'child_process';\nimport url from 'url';\n\nconst commands = {};\n\nconst RECORDING_INTERVAL_SEC = 5;\nconst STREAMING_STARTUP_TIMEOUT_MS = 5000;\nconst GSTREAMER_BINARY = `gst-launch-1.0${system.isWindows() ? '.exe' : ''}`;\nconst GST_INSPECT_BINARY = `gst-inspect-1.0${system.isWindows() ? '.exe' : ''}`;\nconst REQUIRED_GST_PLUGINS = {\n avdec_h264: 'gst-libav',\n h264parse: 'gst-plugins-bad',\n jpegenc: 'gst-plugins-good',\n tcpserversink: 'gst-plugins-base',\n multipartmux: 'gst-plugins-good',\n};\nconst SCREENRECORD_BINARY = 'screenrecord';\nconst GST_TUTORIAL_URL = 'https://gstreamer.freedesktop.org/documentation/installing/index.html';\nconst DEFAULT_HOST = '127.0.0.1';\nconst TCP_HOST = '127.0.0.1';\nconst DEFAULT_PORT = 8093;\nconst DEFAULT_QUALITY = 70;\nconst DEFAULT_BITRATE = 4000000; // 4 Mbps\nconst BOUNDARY_STRING = '--2ae9746887f170b8cf7c271047ce314c';\n\nconst ADB_SCREEN_STREAMING_FEATURE = 'adb_screen_streaming';\n\nfunction createStreamingLogger (streamName, udid) {\n return logger.getLogger(`${streamName}@` + _.truncate(udid, {\n length: 8,\n omission: '',\n }));\n}\n\nasync function verifyStreamingRequirements (adb) {\n if (!_.trim(await adb.shell(['which', SCREENRECORD_BINARY]))) {\n throw new Error(\n `The required '${SCREENRECORD_BINARY}' binary is not available on the device under test`);\n }\n\n const gstreamerCheckPromises = [];\n for (const binaryName of [GSTREAMER_BINARY, GST_INSPECT_BINARY]) {\n gstreamerCheckPromises.push((async () => {\n try {\n await fs.which(binaryName);\n } catch (e) {\n throw new Error(`The '${binaryName}' binary is not available in the PATH on the host system. ` +\n `See ${GST_TUTORIAL_URL} for more details on how to install it.`);\n }\n })());\n }\n await B.all(gstreamerCheckPromises);\n\n const moduleCheckPromises = [];\n for (const [name, modName] of _.toPairs(REQUIRED_GST_PLUGINS)) {\n moduleCheckPromises.push((async () => {\n const {stdout} = await exec(GST_INSPECT_BINARY, [name]);\n if (!_.includes(stdout, modName)) {\n throw new Error(\n `The required GStreamer plugin '${name}' from '${modName}' module is not installed. ` +\n `See ${GST_TUTORIAL_URL} for more details on how to install it.`);\n }\n })());\n }\n await B.all(moduleCheckPromises);\n}\n\nasync function getDeviceInfo (adb, log = null) {\n const output = await adb.shell(['dumpsys', 'display']);\n const result = {};\n for (const [key, pattern] of [\n ['width', /\\bdeviceWidth=(\\d+)/],\n ['height', /\\bdeviceHeight=(\\d+)/],\n ['fps', /\\bfps=(\\d+)/],\n ]) {\n const match = pattern.exec(output);\n if (!match) {\n log?.debug(output);\n throw new Error(`Cannot parse the device ${key} from the adb command output. ` +\n `Check the server log for more details.`);\n }\n result[key] = parseInt(match[1], 10);\n }\n result.udid = adb.curDeviceId;\n return result;\n}\n\nasync function initDeviceStreamingProc (adb, log, deviceInfo, opts = {}) {\n const {\n width,\n height,\n bitRate,\n } = opts;\n const adjustedWidth = parseInt(width, 10) || deviceInfo.width;\n const adjustedHeight = parseInt(height, 10) || deviceInfo.height;\n const adjustedBitrate = parseInt(bitRate, 10) || DEFAULT_BITRATE;\n let screenRecordCmd = SCREENRECORD_BINARY +\n ` --output-format=h264` +\n // 5 seconds is fine to detect rotation changes\n ` --time-limit=${RECORDING_INTERVAL_SEC}`;\n if (width || height) {\n screenRecordCmd += ` --size=${adjustedWidth}x${adjustedHeight}`;\n }\n if (bitRate) {\n screenRecordCmd += ` --bit-rate=${adjustedBitrate}`;\n }\n const adbArgs = [\n ...adb.executable.defaultArgs,\n 'exec-out',\n // The loop is required, because by default the maximum record duration\n // for screenrecord is always limited\n `while true; do ${screenRecordCmd} -; done`,\n ];\n const deviceStreaming = spawn(adb.executable.path, adbArgs);\n deviceStreaming.on('exit', (code, signal) => {\n log.debug(`Device streaming process exited with code ${code}, signal ${signal}`);\n });\n\n let isStarted = false;\n const deviceStreamingLogger = createStreamingLogger(SCREENRECORD_BINARY, deviceInfo.udid);\n const errorsListener = (chunk) => {\n const stderr = chunk.toString();\n if (_.trim(stderr)) {\n deviceStreamingLogger.debug(stderr);\n }\n };\n deviceStreaming.stderr.on('data', errorsListener);\n\n const startupListener = (chunk) => {\n if (!isStarted) {\n isStarted = !_.isEmpty(chunk);\n }\n };\n deviceStreaming.stdout.on('data', startupListener);\n\n try {\n log.info(`Starting device streaming: ${util.quote([adb.executable.path, ...adbArgs])}`);\n await waitForCondition(() => isStarted, {\n waitMs: STREAMING_STARTUP_TIMEOUT_MS,\n intervalMs: 300,\n });\n } catch (e) {\n log.errorAndThrow(\n `Cannot start the screen streaming process. Original error: ${e.message}`);\n } finally {\n deviceStreaming.stderr.removeListener('data', errorsListener);\n deviceStreaming.stdout.removeListener('data', startupListener);\n }\n return deviceStreaming;\n}\n\nasync function initGstreamerPipeline (deviceStreamingProc, deviceInfo, log, opts = {}) {\n const {\n width,\n height,\n quality,\n tcpPort,\n considerRotation,\n logPipelineDetails,\n } = opts;\n const adjustedWidth = parseInt(width, 10) || deviceInfo.width;\n const adjustedHeight = parseInt(height, 10) || deviceInfo.height;\n const gstreamerPipeline = new SubProcess(GSTREAMER_BINARY, [\n '-v',\n 'fdsrc', 'fd=0',\n '!', 'video/x-h264,' +\n `width=${considerRotation ? Math.max(adjustedWidth, adjustedHeight) : adjustedWidth},` +\n `height=${considerRotation ? Math.max(adjustedWidth, adjustedHeight) : adjustedHeight},` +\n `framerate=${deviceInfo.fps}/1,` +\n 'byte-stream=true',\n '!', 'h264parse',\n '!', 'queue', 'leaky=downstream',\n '!', 'avdec_h264',\n '!', 'queue', 'leaky=downstream',\n '!', 'jpegenc', `quality=${quality}`,\n '!', 'multipartmux', `boundary=${BOUNDARY_STRING}`,\n '!', 'tcpserversink', `host=${TCP_HOST}`, `port=${tcpPort}`,\n ], {\n stdio: [deviceStreamingProc.stdout, 'pipe', 'pipe']\n });\n gstreamerPipeline.on('exit', (code, signal) => {\n log.debug(`Pipeline streaming process exited with code ${code}, signal ${signal}`);\n });\n const gstreamerLogger = createStreamingLogger('gst', deviceInfo.udid);\n const gstOutputListener = (stdout, stderr) => {\n if (_.trim(stderr || stdout)) {\n gstreamerLogger.debug(stderr || stdout);\n }\n };\n gstreamerPipeline.on('output', gstOutputListener);\n let didFail = false;\n try {\n log.info(`Starting GStreamer pipeline: ${gstreamerPipeline.rep}`);\n await gstreamerPipeline.start(0);\n await waitForCondition(async () => {\n try {\n return (await checkPortStatus(tcpPort, TCP_HOST)) === 'open';\n } catch (ign) {\n return false;\n }\n }, {\n waitMs: STREAMING_STARTUP_TIMEOUT_MS,\n intervalMs: 300,\n });\n } catch (e) {\n didFail = true;\n log.errorAndThrow(\n `Cannot start the screen streaming pipeline. Original error: ${e.message}`);\n } finally {\n if (!logPipelineDetails || didFail) {\n gstreamerPipeline.removeListener('output', gstOutputListener);\n }\n }\n return gstreamerPipeline;\n}\n\nfunction extractRemoteAddress (req) {\n return req.headers['x-forwarded-for']\n || req.socket.remoteAddress\n || req.connection.remoteAddress\n || req.connection.socket.remoteAddress;\n}\n\n\n/**\n * @typedef {Object} StartScreenStreamingOptions\n *\n * @property {?number} width - The scaled width of the device's screen. If unset then the script will assign it\n * to the actual screen width measured in pixels.\n * @property {?number} height - The scaled height of the device's screen. If unset then the script will assign it\n * to the actual screen height measured in pixels.\n * @property {?number} bitRate - The video bit rate for the video, in bits per second.\n * The default value is 4000000 (4 Mb/s). You can increase the bit rate to improve video quality,\n * but doing so results in larger movie files.\n * @property {?string} host [127.0.0.1] - The IP address/host name to start the MJPEG server on.\n * You can set it to `0.0.0.0` to trigger the broadcast on all available network interfaces.\n * @property {?string} pathname - The HTTP request path the MJPEG server should be available on.\n * If unset then any pathname on the given `host`/`port` combination will work. Note that the value\n * should always start with a single slash: `/`\n * @property {?number} tcpPort [8094] - The port number to start the internal TCP MJPEG broadcast on.\n * This type of broadcast always starts on the loopback interface (`127.0.0.1`).\n * @property {?number} port [8093] - The port number to start the MJPEG server on.\n * @property {?number} quality [70] - The quality value for the streamed JPEG images.\n * This number should be in range [1, 100], where 100 is the best quality.\n * @property {?boolean} considerRotation [false] - If set to `true` then GStreamer pipeline will\n * increase the dimensions of the resulting images to properly fit images in both landscape and\n * portrait orientations. Set it to `true` if the device rotation is not going to be the same during the\n * broadcasting session.\n * @property {?boolean} logPipelineDetails [false] - Whether to log GStreamer pipeline events into\n * the standard log output. Might be useful for debugging purposes.\n */\n\n/**\n * Starts device screen broadcast by creating MJPEG server.\n * Multiple calls to this method have no effect unless the previous streaming\n * session is stopped.\n * This method only works if the `adb_screen_streaming` feature is\n * enabled on the server side.\n *\n * @param {?StartScreenStreamingOptions} options - The available options.\n * @throws {Error} If screen streaming has failed to start or\n * is not supported on the host system or\n * the corresponding server feature is not enabled.\n */\ncommands.mobileStartScreenStreaming = async function mobileStartScreenStreaming (options = {}) {\n this.ensureFeatureEnabled(ADB_SCREEN_STREAMING_FEATURE);\n\n const {\n width,\n height,\n bitRate,\n host = DEFAULT_HOST,\n port = DEFAULT_PORT,\n pathname,\n tcpPort = DEFAULT_PORT + 1,\n quality = DEFAULT_QUALITY,\n considerRotation = false,\n logPipelineDetails = false,\n } = options;\n\n if (_.isUndefined(this._screenStreamingProps)) {\n await verifyStreamingRequirements(this.adb);\n }\n if (!_.isEmpty(this._screenStreamingProps)) {\n this.log.info(`The screen streaming session is already running. ` +\n `Stop it first in order to start a new one.`);\n return;\n }\n if ((await checkPortStatus(port, host)) === 'open') {\n this.log.info(`The port #${port} at ${host} is busy. ` +\n `Assuming the screen streaming is already running`);\n return;\n }\n if ((await checkPortStatus(tcpPort, TCP_HOST)) === 'open') {\n this.log.errorAndThrow(`The port #${tcpPort} at ${TCP_HOST} is busy. ` +\n `Make sure there are no leftovers from previous sessions.`);\n }\n this._screenStreamingProps = null;\n\n const deviceInfo = await getDeviceInfo(this.adb, this.log);\n const deviceStreamingProc = await initDeviceStreamingProc(this.adb, this.log, deviceInfo, {\n width,\n height,\n bitRate,\n });\n let gstreamerPipeline;\n try {\n gstreamerPipeline = await initGstreamerPipeline(deviceStreamingProc, deviceInfo, this.log, {\n width,\n height,\n quality,\n tcpPort,\n considerRotation,\n logPipelineDetails,\n });\n } catch (e) {\n if (deviceStreamingProc.kill(0)) {\n deviceStreamingProc.kill();\n }\n throw e;\n }\n\n let mjpegSocket;\n let mjpegServer;\n try {\n await new B((resolve, reject) => {\n mjpegSocket = net.createConnection(tcpPort, TCP_HOST, () => {\n this.log.info(`Successfully connected to MJPEG stream at tcp://${TCP_HOST}:${tcpPort}`);\n mjpegServer = http.createServer((req, res) => {\n const remoteAddress = extractRemoteAddress(req);\n const currentPathname = url.parse(req.url).pathname;\n this.log.info(`Got an incoming screen bradcasting request from ${remoteAddress} ` +\n `(${req.headers['user-agent'] || 'User Agent unknown'}) at ${currentPathname}`);\n\n if (pathname && currentPathname !== pathname) {\n this.log.info('Rejecting the broadcast request since it does not match the given pathname');\n res.writeHead(404, {\n Connection: 'close',\n 'Content-Type': 'text/plain; charset=utf-8',\n });\n res.write(`'${currentPathname}' did not match any known endpoints`);\n res.end();\n return;\n }\n\n this.log.info('Starting MJPEG broadcast');\n res.writeHead(200, {\n 'Cache-Control': 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0',\n Pragma: 'no-cache',\n Connection: 'close',\n 'Content-Type': `multipart/x-mixed-replace; boundary=${BOUNDARY_STRING}`\n });\n\n mjpegSocket.pipe(res);\n });\n mjpegServer.on('error', (e) => {\n this.log.warn(e);\n reject(e);\n });\n mjpegServer.on('close', () => {\n this.log.debug(`MJPEG server at http://${host}:${port} has been closed`);\n });\n mjpegServer.on('listening', () => {\n this.log.info(`Successfully started MJPEG server at http://${host}:${port}`);\n resolve();\n });\n mjpegServer.listen(port, host);\n });\n mjpegSocket.on('error', (e) => {\n this.log.error(e);\n reject(e);\n });\n }).timeout(STREAMING_STARTUP_TIMEOUT_MS,\n `Cannot connect to the streaming server within ${STREAMING_STARTUP_TIMEOUT_MS}ms`);\n } catch (e) {\n if (deviceStreamingProc.kill(0)) {\n deviceStreamingProc.kill();\n }\n if (gstreamerPipeline.isRunning) {\n await gstreamerPipeline.stop();\n }\n if (mjpegSocket) {\n mjpegSocket.destroy();\n }\n if (mjpegServer && mjpegServer.listening) {\n mjpegServer.close();\n }\n throw e;\n }\n\n this._screenStreamingProps = {\n deviceStreamingProc,\n gstreamerPipeline,\n mjpegSocket,\n mjpegServer,\n };\n};\n\n/**\n * Stop screen streaming.\n * If no screen streaming server has been started then nothing is done.\n */\ncommands.mobileStopScreenStreaming = async function mobileStopScreenStreaming (/* options = {} */) {\n if (_.isEmpty(this._screenStreamingProps)) {\n if (!_.isUndefined(this._screenStreamingProps)) {\n this.log.debug(`Screen streaming is not running. There is nothing to stop`);\n }\n return;\n }\n\n const {\n deviceStreamingProc,\n gstreamerPipeline,\n mjpegSocket,\n mjpegServer,\n } = this._screenStreamingProps;\n\n try {\n mjpegSocket.end();\n if (mjpegServer.listening) {\n mjpegServer.close();\n }\n if (deviceStreamingProc.kill(0)) {\n deviceStreamingProc.kill('SIGINT');\n }\n if (gstreamerPipeline.isRunning) {\n try {\n await gstreamerPipeline.stop('SIGINT');\n } catch (e) {\n this.log.warn(e);\n try {\n await gstreamerPipeline.stop('SIGKILL');\n } catch (e1) {\n this.log.error(e1);\n }\n }\n }\n this.log.info(`Successfully terminated the screen streaming MJPEG server`);\n } finally {\n this._screenStreamingProps = null;\n }\n};\n\n\nexport default commands;\n"],"mappings":";;;;;;;;;;;A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-bars.js","names":["WINDOW_TITLE_PATTERN","FRAME_PATTERN","VIEW_VISIBILITY_PATTERN","VIEW_VISIBLE","STATUS_BAR_WINDOW_NAME_PREFIX","NAVIGATION_BAR_WINDOW_NAME_PREFIX","DEFAULT_WINDOW_PROPERTIES","visible","x","y","width","height","commands","parseWindowProperties","name","props","log","result","_","cloneDeep","propLines","join","frameMatch","exec","debug","Error","parseFloat","visibilityMatch","parseInt","parseWindows","lines","windows","currentWindowName","line","split","map","trimEnd","match","trim","length","isArray","push","isEmpty","statusBar","navigationBar","toPairs","startsWith","unmatchedWindows","filter","isNil","window","namePrefix","info","keys","getSystemBars","stdout","adb","shell","e","message"],"sources":["../../../lib/commands/system-bars.js"],"sourcesContent":["import _ from 'lodash';\n\nconst WINDOW_TITLE_PATTERN = /^\\s+Window\\s#\\d+\\sWindow\\{[0-9a-f]+\\s\\w+\\s([\\w-]+)\\}:$/;\nconst FRAME_PATTERN = /\\bm?[Ff]rame=\\[([0-9.-]+),([0-9.-]+)\\]\\[([0-9.-]+),([0-9.-]+)\\]/;\nconst VIEW_VISIBILITY_PATTERN = /\\bmViewVisibility=(0x[0-9a-fA-F]+)/;\n// https://developer.android.com/reference/android/view/View#VISIBLE\nconst VIEW_VISIBLE = 0x0;\nconst STATUS_BAR_WINDOW_NAME_PREFIX = 'StatusBar';\nconst NAVIGATION_BAR_WINDOW_NAME_PREFIX = 'NavigationBar';\nconst DEFAULT_WINDOW_PROPERTIES = {\n visible: false,\n x: 0, y: 0, width: 0, height: 0,\n};\n\nconst commands = {};\n\n/**\n * @typedef {Object} WindowProperties\n * @property {boolean} visible Whether the window is visible\n * @property {number} x Window x coordinate\n * @property {number} y Window y coordinate\n * @property {number} width Window width\n * @property {number} height Window height\n */\n\n/**\n * Parses window properties from adb dumpsys output\n *\n * @param {string} name The name of the window whose properties are being parsed\n * @param {Array<string>} props The list of particular window property lines.\n * Check the corresponding unit tests for more details on the input format.\n * @param {Object?} log Logger instance\n * @returns {WindowProperties} Parsed properties object\n * @throws {Error} If there was an issue while parsing the properties string\n */\nfunction parseWindowProperties (name, props, log = null) {\n const result = _.cloneDeep(DEFAULT_WINDOW_PROPERTIES);\n const propLines = props.join('\\n');\n const frameMatch = FRAME_PATTERN.exec(propLines);\n if (!frameMatch) {\n log?.debug(propLines);\n throw new Error(`Cannot parse the frame size from '${name}' window properties`);\n }\n result.x = parseFloat(frameMatch[1]);\n result.y = parseFloat(frameMatch[2]);\n result.width = parseFloat(frameMatch[3]) - result.x;\n result.height = parseFloat(frameMatch[4]) - result.y;\n const visibilityMatch = VIEW_VISIBILITY_PATTERN.exec(propLines);\n if (!visibilityMatch) {\n log?.debug(propLines);\n throw new Error(`Cannot parse the visibility value from '${name}' window properties`);\n }\n result.visible = parseInt(visibilityMatch[1], 16) === VIEW_VISIBLE;\n return result;\n}\n\n/**\n * Extracts status and navigation bar information from the window manager output.\n *\n * @param {Array<string>} lines Output from dumpsys command.\n * Check the corresponding unit tests for more details on the input format.\n * @param {Object?} log Logger instance\n * @return {Object} An object containing two items where keys are statusBar and navigationBar,\n * and values are corresponding WindowProperties objects\n * @throws {Error} If no window properties could be parsed\n */\nfunction parseWindows (lines, log = null) {\n const windows = {};\n let currentWindowName = null;\n for (const line of lines.split('\\n').map(_.trimEnd)) {\n const match = WINDOW_TITLE_PATTERN.exec(line);\n if (match) {\n currentWindowName = match[1];\n windows[currentWindowName] = [];\n continue;\n }\n if (_.trim(line).length === 0) {\n currentWindowName = null;\n continue;\n }\n\n if (currentWindowName && _.isArray(windows[currentWindowName])) {\n windows[currentWindowName].push(line);\n }\n }\n if (_.isEmpty(windows)) {\n log?.debug(lines.join('\\n'));\n throw new Error('Cannot parse any window information from the dumpsys output');\n }\n\n const result = {statusBar: null, navigationBar: null};\n for (const [name, props] of _.toPairs(windows)) {\n if (name.startsWith(STATUS_BAR_WINDOW_NAME_PREFIX)) {\n result.statusBar = parseWindowProperties(name, props, log);\n } else if (name.startsWith(NAVIGATION_BAR_WINDOW_NAME_PREFIX)) {\n result.navigationBar = parseWindowProperties(name, props, log);\n }\n }\n const unmatchedWindows = [\n ['statusBar', STATUS_BAR_WINDOW_NAME_PREFIX],\n ['navigationBar', NAVIGATION_BAR_WINDOW_NAME_PREFIX]\n ].filter(([name]) => _.isNil(result[name]));\n for (const [window, namePrefix] of unmatchedWindows) {\n log?.info(`No windows have been found whose title matches to ` +\n `'${namePrefix}'. Assuming it is invisible. ` +\n `Only the following windows are available: ${_.keys(windows)}`);\n result[window] = _.cloneDeep(DEFAULT_WINDOW_PROPERTIES);\n }\n return result;\n}\n\ncommands.getSystemBars = async function getSystemBars () {\n let stdout;\n try {\n stdout = await this.adb.shell(['dumpsys', 'window', 'windows']);\n } catch (e) {\n throw new Error(`Cannot retrieve system bars details. Original error: ${e.message}`);\n }\n return parseWindows(stdout, this.log);\n};\n\n// for unit tests\nexport { parseWindows, parseWindowProperties };\nexport default commands;\n"],"mappings":";;;;;;;;;;;;;AAAA;;AAEA,MAAMA,oBAAoB,GAAG,wDAA7B;AACA,MAAMC,aAAa,GAAG,iEAAtB;AACA,MAAMC,uBAAuB,GAAG,oCAAhC;AAEA,MAAMC,YAAY,GAAG,GAArB;AACA,MAAMC,6BAA6B,GAAG,WAAtC;AACA,MAAMC,iCAAiC,GAAG,eAA1C;AACA,MAAMC,yBAAyB,GAAG;EAChCC,OAAO,EAAE,KADuB;EAEhCC,CAAC,EAAE,CAF6B;EAE1BC,CAAC,EAAE,CAFuB;EAEpBC,KAAK,EAAE,CAFa;EAEVC,MAAM,EAAE;AAFE,CAAlC;AAKA,MAAMC,QAAQ,GAAG,EAAjB;;AAqBA,SAASC,qBAAT,CAAgCC,IAAhC,EAAsCC,KAAtC,EAA6CC,GAAG,GAAG,IAAnD,EAAyD;EACvD,MAAMC,MAAM,GAAGC,eAAA,CAAEC,SAAF,CAAYb,yBAAZ,CAAf;;EACA,MAAMc,SAAS,GAAGL,KAAK,CAACM,IAAN,CAAW,IAAX,CAAlB;EACA,MAAMC,UAAU,G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EACF;;EACD,MAAM+B,gBAAgB,GAAG,CACvB,CAAC,WAAD,EAAc3C,6BAAd,CADuB,EAEvB,CAAC,eAAD,EAAkBC,iCAAlB,CAFuB,EAGvB2C,MAHuB,CAGhB,CAAC,CAAClC,IAAD,CAAD,KAAYI,eAAA,CAAE+B,KAAF,CAAQhC,MAAM,CAACH,IAAD,CAAd,CAHI,CAAzB;;EAIA,KAAK,MAAM,CAACoC,MAAD,EAASC,UAAT,CAAX,IAAmCJ,gBAAnC,EAAqD;IACnD/B,GAAG,SAAH,IAAAA,GAAG,WAAH,YAAAA,GAAG,CAAEoC,IAAL,CAAW,oDAAD,GACP,IAAGD,UAAW,+BADP,GAEP,6CAA4CjC,eAAA,CAAEmC,IAAF,CAAOtB,OAAP,CAAgB,EAF/D;IAGAd,MAAM,CAACiC,MAAD,CAAN,GAAiBhC,eAAA,CAAEC,SAAF,CAAYb,yBAAZ,CAAjB;EACD;;EACD,OAAOW,MAAP;AACD;;AAEDL,QAAQ,CAAC0C,aAAT,GAAyB,eAAeA,aAAf,GAAgC;EACvD,IAAIC,MAAJ;;EACA,IAAI;IACFA,MAAM,GAAG,MAAM,KAAKC,GAAL,CAASC,KAAT,CAAe,CAAC,SAAD,EAAY,QAAZ,EAAsB,SAAtB,CAAf,CAAf;EACD,CAFD,CAEE,OAAOC,CAAP,EAAU;IACV,MAAM,IAAIjC,KAAJ,CAAW,wDAAuDiC,CAAC,CAACC,OAAQ,EAA5E,CAAN;EACD;;EACD,OAAO9B,YAAY,CAAC0B,MAAD,EAAS,KAAKvC,GAAd,CAAnB;AACD,CARD;;eAYeJ,Q"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"touch.js","names":["commands","helpers","extensions","getCoordDefault","val","util","hasValue","getSwipeTouchDuration","waitGesture","duration","options","ms","doTouchAction","action","opts","element","x","y","count","tap","touchDown","touchUp","touchMove","B","delay","touchLongClick","log","warn","errorAndThrow","doTouchDrag","gestures","longPress","moveTo","startX","startY","endX","endY","getLocationInView","apiLevel","adb","getApiLevel","Math","max","drag","fixRelease","release","_","last","clone","ref","gesture","reverse","loc","size","getSize","width","height","pick","performGesture","e","isErrorType","errors","NoSuchElementError","debug","getSwipeOptions","touchCount","destElement","locResult","sizeResult","offsetX","abs","offsetY","firstElLocation","performTouch","length","swipeOpts","swipe","actions","map","head","pop","slice","press","shift","wait","fixedGestures","parseTouch","g","multi","touchStateObjects","asyncmap","includes","offset","elementId","pos","touchStateObject","timeOffset","parseInt","prevPos","time","state","isUndefined","androidHelpers","truncateDecimals","touch","performMultiAction","Error","states","doPerformMultiAction","bootstrap","sendAction","Object","assign"],"sources":["../../../lib/commands/touch.js"],"sourcesContent":["import _ from 'lodash';\nimport androidHelpers from '../android-helpers';\nimport B from 'bluebird';\nimport { errors, isErrorType } from 'appium/driver';\nimport { asyncmap } from 'asyncbox';\nimport { util } from 'appium/support';\n\nlet commands = {}, helpers = {}, extensions = {};\n\nfunction getCoordDefault (val) {\n // going the long way and checking for undefined and null since\n // we can't be assured `elId` is a string and not an int. Same\n // thing with destElement below.\n return util.hasValue(val) ? val : 0.5;\n}\n\nfunction getSwipeTouchDuration (waitGesture) {\n // the touch action api uses ms, we want seconds\n // 0.8 is the default time for the operation\n let duration = 0.8;\n if (typeof waitGesture.options.ms !== 'undefined' && waitGesture.options.ms) {\n duration = waitGesture.options.ms / 1000;\n if (duration === 0) {\n // set to a very low number, since they wanted it fast\n // but below 0.1 becomes 0 steps, which causes errors\n duration = 0.1;\n }\n }\n return duration;\n}\n\ncommands.doTouchAction = async function doTouchAction (action, opts = {}) {\n const { element, x, y, count, ms, duration } = opts;\n // parseTouch precalculates absolute element positions\n // so there is no need to pass `element` to the affected gestures\n switch (action) {\n case 'tap':\n return await this.tap(null, x, y, count);\n case 'press':\n return await this.touchDown(null, x, y);\n case 'release':\n return await this.touchUp(element, x, y);\n case 'moveTo':\n return await this.touchMove(null, x, y);\n case 'wait':\n return await B.delay(ms);\n case 'longPress':\n return await this.touchLongClick(null, x, y, duration || 1000);\n case 'cancel':\n // TODO: clarify behavior of 'cancel' action and fix this\n this.log.warn('Cancel action currently has no effect');\n break;\n default:\n this.log.errorAndThrow(`unknown action ${action}`);\n }\n};\n\n// drag is *not* press-move-release, so we need to translate\n// drag works fine for scroll, as well\nhelpers.doTouchDrag = async function doTouchDrag (gestures) {\n let longPress = gestures[0];\n let moveTo = gestures[1];\n let startX = longPress.options.x || 0,\n startY = longPress.options.y || 0,\n endX = moveTo.options.x || 0,\n endY = moveTo.options.y || 0;\n if (longPress.options.element) {\n let {x, y} = await this.getLocationInView(longPress.options.element);\n startX += x || 0;\n startY += y || 0;\n }\n if (moveTo.options.element) {\n let {x, y} = await this.getLocationInView(moveTo.options.element);\n endX += x || 0;\n endY += y || 0;\n }\n\n let apiLevel = await this.adb.getApiLevel();\n // lollipop takes a little longer to get things rolling\n let duration = apiLevel >= 5 ? 2 : 1;\n // make sure that if the long press has a duration, we use it.\n if (longPress.options && longPress.options.duration) {\n duration = Math.max(longPress.options.duration / 1000, duration);\n }\n\n // `drag` will take care of whether there is an element or not at that level\n return await this.drag(startX, startY, endX, endY, duration, 1, longPress.options.element, moveTo.options.element);\n};\n\n// Release gesture needs element or co-ordinates to release it from that position\n// or else release gesture is performed from center of the screen, so to fix it\n// This method sets co-ordinates/element to release gesture if it has no options set already.\nhelpers.fixRelease = async function fixRelease (gestures) {\n let release = _.last(gestures);\n // sometimes there are no options\n release.options = release.options || {};\n // nothing to do if release options are already set\n if (release.options.element || (release.options.x && release.options.y)) {\n return;\n }\n // without coordinates, `release` uses the center of the screen, which,\n // generally speaking, is not what we want\n // therefore: loop backwards and use the last command with an element and/or\n // offset coordinates\n gestures = _.clone(gestures);\n let ref = null;\n for (let gesture of gestures.reverse()) {\n let opts = gesture.options;\n if (opts.element || (opts.x && opts.y)) {\n ref = gesture;\n break;\n }\n }\n if (ref) {\n let opts = ref.options;\n if (opts.element) {\n let loc = await this.getLocationInView(opts.element);\n if (opts.x && opts.y) {\n // this is an offset from the element\n release.options = {\n x: loc.x + opts.x,\n y: loc.y + opts.y\n };\n } else {\n // this is the center of the element\n let size = await this.getSize(opts.element);\n release.options = {\n x: loc.x + size.width / 2,\n y: loc.y + size.height / 2\n };\n }\n } else {\n release.options = _.pick(opts, 'x', 'y');\n }\n }\n return release;\n};\n\n// Perform one gesture\nhelpers.performGesture = async function performGesture (gesture) {\n try {\n return await this.doTouchAction(gesture.action, gesture.options || {});\n } catch (e) {\n // sometime the element is not available when releasing, retry without it\n if (isErrorType(e, errors.NoSuchElementError) && gesture.action === 'release' &&\n gesture.options.element) {\n delete gesture.options.element;\n this.log.debug(`retrying release without element opts: ${gesture.options}.`);\n return await this.doTouchAction(gesture.action, gesture.options || {});\n }\n throw e;\n }\n};\n\ncommands.getSwipeOptions = async function getSwipeOptions (gestures, touchCount = 1) {\n let startX = getCoordDefault(gestures[0].options.x),\n startY = getCoordDefault(gestures[0].options.y),\n endX = getCoordDefault(gestures[2].options.x),\n endY = getCoordDefault(gestures[2].options.y),\n duration = getSwipeTouchDuration(gestures[1]),\n element = gestures[0].options.element,\n destElement = gestures[2].options.element || gestures[0].options.element;\n\n // there's no destination element handling in bootstrap and since it applies to all platforms, we handle it here\n if (util.hasValue(destElement)) {\n let locResult = await this.getLocationInView(destElement);\n let sizeResult = await this.getSize(destElement);\n let offsetX = (Math.abs(endX) < 1 && Math.abs(endX) > 0) ? sizeResult.width * endX : endX;\n let offsetY = (Math.abs(endY) < 1 && Math.abs(endY) > 0) ? sizeResult.height * endY : endY;\n endX = locResult.x + offsetX;\n endY = locResult.y + offsetY;\n // if the target element was provided, the coordinates for the destination need to be relative to it.\n if (util.hasValue(element)) {\n let firstElLocation = await this.getLocationInView(element);\n endX -= firstElLocation.x;\n endY -= firstElLocation.y;\n }\n }\n // clients are responsible to use these options correctly\n return {startX, startY, endX, endY, duration, touchCount, element};\n};\n\ncommands.performTouch = async function performTouch (gestures) {\n // press-wait-moveTo-release is `swipe`, so use native method\n if (gestures.length === 4 &&\n gestures[0].action === 'press' &&\n gestures[1].action === 'wait' &&\n gestures[2].action === 'moveTo' &&\n gestures[3].action === 'release') {\n\n let swipeOpts = await this.getSwipeOptions(gestures);\n return await this.swipe(swipeOpts.startX, swipeOpts.startY, swipeOpts.endX,\n swipeOpts.endY, swipeOpts.duration, swipeOpts.touchCount,\n swipeOpts.element);\n }\n let actions = _.map(gestures, 'action');\n\n if (actions[0] === 'longPress' && actions[1] === 'moveTo' && actions[2] === 'release') {\n // some things are special\n return await this.doTouchDrag(gestures);\n } else {\n if (actions.length === 2) {\n // `press` without a wait is too slow and gets interpretted as a `longPress`\n if (_.head(actions) === 'press' && _.last(actions) === 'release') {\n actions[0] = 'tap';\n gestures[0].action = 'tap';\n }\n\n // the `longPress` and `tap` methods release on their own\n if ((_.head(actions) === 'tap' || _.head(actions) === 'longPress') && _.last(actions) === 'release') {\n gestures.pop();\n actions.pop();\n }\n } else {\n // longpress followed by anything other than release should become a press and wait\n if (actions[0] === 'longPress') {\n actions = ['press', 'wait', ...actions.slice(1)];\n\n let press = gestures.shift();\n press.action = 'press';\n let wait = {\n action: 'wait',\n options: {ms: press.options.duration || 1000}\n };\n delete press.options.duration;\n gestures = [press, wait, ...gestures];\n }\n }\n\n let fixedGestures = await this.parseTouch(gestures, false);\n // fix release action then perform all actions\n if (actions[actions.length - 1] === 'release') {\n actions[actions.length - 1] = await this.fixRelease(gestures);\n }\n for (let g of fixedGestures) {\n await this.performGesture(g);\n }\n }\n};\n\nhelpers.parseTouch = async function parseTouch (gestures, multi) {\n // because multi-touch releases at the end by default\n if (multi && _.last(gestures).action === 'release') {\n gestures.pop();\n }\n\n let touchStateObjects = await asyncmap(gestures, async (gesture) => {\n let options = gesture.options || {};\n if (_.includes(['press', 'moveTo', 'tap', 'longPress'], gesture.action)) {\n options.offset = false;\n let elementId = gesture.options.element;\n if (elementId) {\n let pos = await this.getLocationInView(elementId);\n if (gesture.options.x || gesture.options.y) {\n options.x = pos.x + (gesture.options.x || 0);\n options.y = pos.y + (gesture.options.y || 0);\n } else {\n const {width, height} = await this.getSize(elementId);\n options.x = pos.x + (width / 2);\n options.y = pos.y + (height / 2);\n }\n let touchStateObject = {\n action: gesture.action,\n options,\n timeOffset: 0.005,\n };\n return touchStateObject;\n } else {\n options.x = (gesture.options.x || 0);\n options.y = (gesture.options.y || 0);\n\n let touchStateObject = {\n action: gesture.action,\n options,\n timeOffset: 0.005,\n };\n return touchStateObject;\n }\n } else {\n let offset = 0.005;\n if (gesture.action === 'wait') {\n options = gesture.options;\n offset = (parseInt(gesture.options.ms, 10) / 1000);\n }\n let touchStateObject = {\n action: gesture.action,\n options,\n timeOffset: offset,\n };\n return touchStateObject;\n }\n }, false);\n // we need to change the time (which is now an offset)\n // and the position (which may be an offset)\n let prevPos = null,\n time = 0;\n for (let state of touchStateObjects) {\n if (_.isUndefined(state.options.x) && _.isUndefined(state.options.y) && prevPos !== null) {\n // this happens with wait\n state.options.x = prevPos.x;\n state.options.y = prevPos.y;\n }\n if (state.options.offset && prevPos) {\n // the current position is an offset\n state.options.x += prevPos.x;\n state.options.y += prevPos.y;\n }\n delete state.options.offset;\n if (!_.isUndefined(state.options.x) && !_.isUndefined(state.options.y)) {\n prevPos = state.options;\n }\n\n if (multi) {\n let timeOffset = state.timeOffset;\n time += timeOffset;\n state.time = androidHelpers.truncateDecimals(time, 3);\n\n // multi gestures require 'touch' rather than 'options'\n if (!_.isUndefined(state.options.x) && !_.isUndefined(state.options.y)) {\n state.touch = {\n x: state.options.x,\n y: state.options.y\n };\n }\n delete state.options;\n }\n delete state.timeOffset;\n }\n return touchStateObjects;\n};\n\n\ncommands.performMultiAction = async function performMultiAction (actions, elementId) {\n // Android needs at least two actions to be able to perform a multi pointer gesture\n if (actions.length === 1) {\n throw new Error('Multi Pointer Gestures need at least two actions. ' +\n 'Use Touch Actions for a single action.');\n }\n\n const states = await asyncmap(actions, async (action) => await this.parseTouch(action, true), false);\n\n return await this.doPerformMultiAction(elementId, states);\n};\n\n/**\n * Reason for isolating doPerformMultiAction from performMultiAction is for reusing performMultiAction\n * across android-drivers (like appium-uiautomator2-driver) and to avoid code duplication.\n * Other android-drivers (like appium-uiautomator2-driver) need to override doPerformMultiAction\n * to facilitate performMultiAction.\n */\ncommands.doPerformMultiAction = async function doPerformMultiAction (elementId, states) {\n let opts;\n if (elementId) {\n opts = {\n elementId,\n actions: states\n };\n return await this.bootstrap.sendAction('element:performMultiPointerGesture', opts);\n } else {\n opts = {\n actions: states\n };\n return await this.bootstrap.sendAction('performMultiPointerGesture', opts);\n }\n};\n\nObject.assign(extensions, commands, helpers);\nexport { commands, helpers };\nexport default extensions;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEA,IAAIA,QAAQ,GAAG,EAAf;AAAA,IAAmBC,OAAO,GAAG,EAA7B;AAAA,IAAiCC,UAAU,GAAG,EAA9C;;;;AAEA,SAASC,eAAT,CAA0BC,GAA1B,EAA+B;EAI7B,OAAOC,aAAA,CAAKC,QAAL,CAAcF,GAAd,IAAqBA,GAArB,GAA2B,GAAlC;AACD;;AAED,SAASG,qBAAT,CAAgCC,WAAhC,EAA6C;EAG3C,IAAIC,QAAQ,GAAG,GAAf;;EACA,IAAI,OAAOD,WAAW,CAACE,OAAZ,CAAoBC,EAA3B,KAAkC,WAAlC,IAAiDH,WAAW,CAACE,OAAZ,CAAoBC,EAAzE,EAA6E;IAC3EF,QAAQ,GAAGD,WAAW,CAACE,OAAZ,CAAoBC,EAApB,GAAyB,IAApC;;IACA,IAAIF,QAAQ,KAAK,CAAjB,EAAoB;MAGlBA,QAAQ,GAAG,GAAX;IACD;EACF;;EACD,OAAOA,QAAP;AACD;;AAEDT,QAAQ,CAACY,aAAT,GAAyB,eAAeA,aAAf,CAA8BC,MAA9B,EAAsCC,IAAI,GAAG,EAA7C,EAAiD;EACxE,MAAM;IAAEC,OAAF;IAAWC,CAAX;IAAcC,CAAd;IAAiBC,KAAjB;IAAwBP,EAAxB;IAA4BF;EA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f,CAA0B,oCAA1B,EAAgEhG,IAAhE,CAAb;EACD,CAND,MAMO;IACLA,IAAI,GAAG;MACL+D,OAAO,EAAE8B;IADJ,CAAP;IAGA,OAAO,MAAM,KAAKE,SAAL,CAAeC,UAAf,CAA0B,4BAA1B,EAAwDhG,IAAxD,CAAb;EACD;AACF,CAdD;;AAgBAiG,MAAM,CAACC,MAAP,CAAc9G,UAAd,EAA0BF,QAA1B,EAAoCC,OAApC;eAEeC,U"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"desired-caps.js","names":["commonCapConstraints","platformName","isString","inclusionCaseInsensitive","presence","app","appActivity","appPackage","appWaitActivity","appWaitPackage","appWaitDuration","isNumber","deviceReadyTimeout","androidCoverage","androidDeviceReadyTimeout","androidDeviceSocket","androidInstallTimeout","adbPort","remoteAdbHost","adbExecTimeout","avd","avdLaunchTimeout","avdReadyTimeout","avdArgs","avdEnv","isObject","useKeystore","isBoolean","keystorePath","keystorePassword","keyAlias","keyPassword","webviewDevtoolsPort","ensureWebviewsHavePages","enableWebviewDetailsCollection","chromeDriverPort","chromedriverPort","chromedriverPorts","isArray","chromedriverArgs","chromedriverExecutable","chromedriverExecutableDir","chromedriverChromeMappingFile","chromedriverUseSystemExecutable","chromedriverDisableBuildCheck","chromeLoggingPrefs","autoWebviewTimeout","intentAction","intentCategory","intentFlags","optionalIntentArguments","dontStopAppOnReset","unicodeKeyboard","resetKeyboard","noSign","recreateChromeDriverSessions","autoLaunch","nativeWebScreenshot","androidScreenshotPath","androidInstallPath","clearSystemFiles","extractChromeAndroidPackageFromContextName","autoGrantPermissions","sharedPreferences","networkSpeed","gpsEnabled","isHeadless","showChromedriverLog","skipUnlock","clearDeviceLogsOnStart","unlockType","unlockKey","unlockStrategy","otherApps","uninstallOtherPackages","allowTestPackages","pageLoadStrategy","localeScript","skipDeviceInitialization","remoteAppsCacheLimit","buildToolsVersion","skipLogcatCapture","chromeOptions","enablePerformanceLogging","userProfile","browserName","enforceAppInstall","suppressKillServer","allowOfflineDevices","ignoreHiddenApiPolicyError","unlockSuccessTimeout","mockLocationApp","logcatFormat","logcatFilterSpecs","allowDelayAdb","uiautomatorCapConstraints","ignoreUnimportantViews","disableAndroidWatchers","acceptSslCerts","androidNaturalOrientation","disableWindowAnimation","bootstrapPort","desiredCapConstraints","Object","assign"],"sources":["../../lib/desired-caps.js"],"sourcesContent":["let commonCapConstraints = {\n platformName: {\n isString: true,\n inclusionCaseInsensitive: ['Android'],\n presence: true\n },\n app: {\n isString: true\n },\n appActivity: {\n isString: true\n },\n appPackage: {\n isString: true\n },\n appWaitActivity: {\n isString: true\n },\n appWaitPackage: {\n isString: true\n },\n appWaitDuration: {\n isNumber: true\n },\n deviceReadyTimeout: {\n isNumber: true\n },\n androidCoverage: {\n isString: true\n },\n androidDeviceReadyTimeout: {\n isNumber: true\n },\n androidDeviceSocket: {\n isString: true\n },\n androidInstallTimeout: {\n isNumber: true\n },\n adbPort: {\n isNumber: true\n },\n remoteAdbHost: {\n isString: true\n },\n adbExecTimeout: {\n isNumber: true\n },\n avd: {\n isString: true\n },\n avdLaunchTimeout: {\n isNumber: true\n },\n avdReadyTimeout: {\n isNumber: true\n },\n avdArgs: {\n // could be a string or an array\n },\n avdEnv: {\n isObject: true\n },\n useKeystore: {\n isBoolean: true\n },\n keystorePath: {\n isString: true\n },\n keystorePassword: {\n isString: true\n },\n keyAlias: {\n isString: true\n },\n keyPassword: {\n isString: true\n },\n webviewDevtoolsPort: {\n isNumber: true\n },\n ensureWebviewsHavePages: {\n isBoolean: true\n },\n enableWebviewDetailsCollection: {\n isBoolean: true\n },\n // this one is deprecated\n chromeDriverPort: {\n isNumber: true\n },\n // duplicate of above with better spelling\n chromedriverPort: {\n isNumber: true\n },\n chromedriverPorts: {\n isArray: true\n },\n chromedriverArgs: {\n isObject: true,\n },\n chromedriverExecutable: {\n isString: true\n },\n chromedriverExecutableDir: {\n isString: true\n },\n chromedriverChromeMappingFile: {\n isString: true\n },\n chromedriverUseSystemExecutable: {\n isBoolean: true\n },\n chromedriverDisableBuildCheck: {\n isBoolean: true\n },\n chromeLoggingPrefs: {\n isObject: true\n },\n autoWebviewTimeout: {\n isNumber: true\n },\n intentAction: {\n isString: true\n },\n intentCategory: {\n isString: true\n },\n intentFlags: {\n isString: true\n },\n optionalIntentArguments: {\n isString: true\n },\n dontStopAppOnReset: {\n isBoolean: true\n },\n unicodeKeyboard: {\n isBoolean: true\n },\n resetKeyboard: {\n isBoolean: true\n },\n noSign: {\n isBoolean: true\n },\n recreateChromeDriverSessions: {\n isBoolean: false\n },\n autoLaunch: {\n isBoolean: true\n },\n nativeWebScreenshot: {\n isBoolean: true\n },\n androidScreenshotPath: {\n isString: true\n },\n androidInstallPath: {\n isString: true\n },\n clearSystemFiles: {\n isBoolean: true\n },\n extractChromeAndroidPackageFromContextName: {\n isBoolean: true\n },\n autoGrantPermissions: {\n isBoolean: true\n },\n sharedPreferences: {\n isObject: true\n },\n networkSpeed: {\n isString: true\n },\n gpsEnabled: {\n isBoolean: true\n },\n isHeadless: {\n isBoolean: true\n },\n showChromedriverLog: {\n isBoolean: true\n },\n skipUnlock: {\n isBoolean: true\n },\n clearDeviceLogsOnStart: {\n isBoolean: true\n },\n unlockType: {\n isString: true\n },\n unlockKey: {\n isString: true\n },\n unlockStrategy: {\n isString: true,\n inclusionCaseInsensitive: ['locksettings', 'uiautomator'],\n },\n otherApps: {\n isString: true\n },\n uninstallOtherPackages: {\n isString: true\n },\n allowTestPackages: {\n isBoolean: true\n },\n pageLoadStrategy: {\n isString: true\n },\n localeScript: {\n isString: true\n },\n skipDeviceInitialization: {\n isBoolean: true\n },\n remoteAppsCacheLimit: {\n isNumber: true\n },\n buildToolsVersion: {\n isString: true\n },\n skipLogcatCapture: {\n isBoolean: true\n },\n chromeOptions: {\n isObject: true\n },\n enablePerformanceLogging: {\n isBoolean: true\n },\n userProfile: {\n isNumber: true\n },\n browserName: {\n isString: true\n },\n enforceAppInstall: {\n isBoolean: true\n },\n suppressKillServer: {\n isBoolean: true\n },\n allowOfflineDevices: {\n isBoolean: true\n },\n ignoreHiddenApiPolicyError: {\n isBoolean: true\n },\n unlockSuccessTimeout: {\n isNumber: true\n },\n mockLocationApp: {\n isString: true\n },\n logcatFormat: {\n isString: true\n },\n logcatFilterSpecs: {\n isArray: true\n },\n allowDelayAdb: {\n isBoolean: true\n }\n};\n\nlet uiautomatorCapConstraints = {\n ignoreUnimportantViews: {\n isBoolean: true\n },\n disableAndroidWatchers: {\n isBoolean: true\n },\n acceptSslCerts: {\n isBoolean: true\n },\n androidNaturalOrientation: {\n isBoolean: true\n },\n disableWindowAnimation: {\n isBoolean: true\n },\n bootstrapPort: {\n isNumber: true\n },\n};\n\nlet desiredCapConstraints = {};\n\nObject.assign(desiredCapConstraints, commonCapConstraints,\n uiautomatorCapConstraints);\n\nexport default desiredCapConstraints;\nexport { commonCapConstraints };\n"],"mappings":";;;;;;;;;AAAA,IAAIA,oBAAoB,GAAG;EACzBC,YAAY,EAAE;IACZC,QAAQ,EAAE,IADE;IAEZC,wBAAwB,EAAE,CAAC,SAAD,CAFd;IAGZC,QAAQ,EAAE;EAHE,CADW;EAMzBC,GAAG,EAAE;IACHH,QAAQ,EAAE;EADP,CANoB;EASzBI,WAAW,EAAE;IACXJ,QAAQ,EAAE;EADC,CATY;EAYzBK,UAAU,EAAE;IACVL,QAAQ,EAAE;EADA,CAZa;EAezBM,eAAe,EAAE;IACfN,QAAQ,EAAE;EADK,CAfQ;EAkBzBO,cAAc,EAAE;IACdP,QAAQ,EAAE;EADI,CAlBS;EAqBzBQ,eAAe,EAAE;IACfC,QAAQ,EAAE;EADK,CArBQ;EAwBzBC,kBAAkB,EAAE;IAClBD,QAAQ,EAAE;EADQ,CAxBK;EA2BzBE,eAAe,EAAE;IACfX,QAAQ,EAAE;EADK,CA3BQ;EA8BzBY,yBAAyB,EAAE;IACzBH,QAAQ,EAAE;EADe,CA9BF;EAiCzBI,mBAAmB,EAAE;IACnBb,QAAQ,EAAE;EADS,CA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AndroidDriver","BaseDriver","constructor","opts","shouldValidateCaps","locatorStrategies","desiredCapConstraints","desiredConstraints","sessionChromedrivers","jwpProxyActive","jwpProxyAvoid","_","clone","settings","DeviceSettings","ignoreUnimportantViews","onSettingsUpdate","bind","chromedriver","apkStrings","unlocker","helpers","cmd","fn","toPairs","commands","prototype","curContext","defaultContextName","createSession","args","sessionId","caps","serverDetails","platform","webStorageEnabled","takesScreenshot","javascriptEnabled","databaseEnabled","networkConnectionEnabled","locationContextEnabled","warnings","desired","Object","assign","defaultOpts","action","category","flags","disableAndroidWatchers","tmpDir","tempDir","staticDir","fullReset","autoLaunch","adbPort","DEFAULT_ADB_PORT","bootstrapPort","androidInstallTimeout","defaults","useUnlockHelperApp","isUndefined","unlockType","noReset","fastReset","skipUninstall","isChromeSession","adjustBrowserSessionCaps","nativeWebScreenshot","push","reboot","setAvdFromCapabilities","udid","emPort","getDeviceInfoFromCaps","adb","createADB","suppressKillServer","remoteAdbHost","clearDeviceLogsOnStart","adbExecTimeout","allowOfflineDevices","getApiLevel","log","warn","isPackageOrBundle","app","appPackage","configureApp","checkAppPresent","appOnDevice","info","checkPackagePresent","util","hasValue","networkSpeed","isEmulator","ensureNetworkSpeed","gpsEnabled","toggleGPSLocationProvider","startAndroidSession","e","deleteSession","ign","avd","deviceName","errorAndThrow","platformVersion","avdDevice","replace","isChromeBrowser","browserName","key","value","setCompressedLayoutHierarchy","defaultIME","initDevice","curDeviceId","deviceUDID","getPlatformVersion","deviceScreenSize","getScreenSize","deviceModel","getModel","deviceManufacturer","getManufacturer","disableWindowAnimation","isAnimationOn","setHiddenApiPolicy","ignoreHiddenApiPolicyError","setAnimationState","_wasWindowAnimationDisabled","initAUT","bootstrap","websocket","start","acceptSslCerts","onUnexpectedShutdown","err","ignoreUnexpectedShutdown","startUnexpectedShutdown","skipUnlock","unlock","update","startChromeSession","startAUT","orientation","debug","setOrientation","initAutoWebview","autoWebview","viewName","defaultWebviewName","timeout","autoWebviewTimeout","retryInterval","setContext","launchInfo","getLaunchInfo","uninstallOtherPackages","validateDesiredCaps","parseArray","SETTINGS_HELPER_PKG_ID","otherApps","message","B","all","map","installOtherApks","resetApp","uninstallApk","installApk","apkStringsForLanguage","pushStrings","language","sharedPreferences","setSharedPreferences","fs","exists","shell","compress","sendAction","compressLayout","isEmpty","_screenRecordingProperties","stopRecordingScreen","removeAllSessionWebSocketHandlers","server","mobileStopScreenStreaming","stopChromedriverProxies","unicodeKeyboard","resetKeyboard","setIME","dontStopAppOnReset","forceStop","goToHome","shutdown","stopLogcat","setDefaultHiddenApiPolicy","avdName","killEmulator","sharedPrefs","name","JSON","stringify","remotePath","remoteFile","localPath","builder","getPrefsBuilder","build","prefs","toFile","unlink","SharedPrefsBuilder","proxyActive","getProxyAvoidList","canProxy","isFunction","proxyReqRes"],"sources":["../../lib/driver.js"],"sourcesContent":["import { BaseDriver, DeviceSettings } from 'appium/driver';\nimport desiredConstraints from './desired-caps';\nimport commands from './commands/index';\nimport {\n helpers, ensureNetworkSpeed,\n SETTINGS_HELPER_PKG_ID,\n} from './android-helpers';\nimport _ from 'lodash';\nimport { DEFAULT_ADB_PORT } from 'appium-adb';\nimport { fs, tempDir, util } from 'appium/support';\nimport { retryInterval } from 'asyncbox';\nimport { SharedPrefsBuilder } from 'shared-preferences-builder';\nimport B from 'bluebird';\n\nconst APP_EXTENSION = '.apk';\nconst DEVICE_PORT = 4724;\n\n// This is a set of methods and paths that we never want to proxy to\n// Chromedriver\nconst NO_PROXY = [\n ['POST', new RegExp('^/session/[^/]+/context')],\n ['GET', new RegExp('^/session/[^/]+/context')],\n ['POST', new RegExp('^/session/[^/]+/appium')],\n ['GET', new RegExp('^/session/[^/]+/appium')],\n ['POST', new RegExp('^/session/[^/]+/touch/perform')],\n ['POST', new RegExp('^/session/[^/]+/touch/multi/perform')],\n ['POST', new RegExp('^/session/[^/]+/orientation')],\n ['GET', new RegExp('^/session/[^/]+/orientation')],\n ['POST', new RegExp('^/session/[^/]+/execute')],\n ['POST', new RegExp('^/session/[^/]+/execute/sync')],\n ['GET', new RegExp('^/session/[^/]+/network_connection')],\n ['POST', new RegExp('^/session/[^/]+/network_connection')],\n];\n\nclass AndroidDriver extends BaseDriver {\n constructor (opts = {}, shouldValidateCaps = true) {\n super(opts, shouldValidateCaps);\n\n this.locatorStrategies = [\n 'xpath',\n 'id',\n 'class name',\n 'accessibility id',\n '-android uiautomator'\n ];\n this.desiredCapConstraints = desiredConstraints;\n this.sessionChromedrivers = {};\n this.jwpProxyActive = false;\n this.jwpProxyAvoid = _.clone(NO_PROXY);\n this.settings = new DeviceSettings({ignoreUnimportantViews: false},\n this.onSettingsUpdate.bind(this));\n this.chromedriver = null;\n this.apkStrings = {};\n this.unlocker = helpers.unlocker;\n\n for (let [cmd, fn] of _.toPairs(commands)) {\n AndroidDriver.prototype[cmd] = fn;\n }\n\n // needs to be after the line which assigns commands to AndroidDriver.prototype, so that `this.defaultContextName` is defined.\n this.curContext = this.defaultContextName();\n }\n\n async createSession (...args) {\n // the whole createSession flow is surrounded in a try-catch statement\n // if creating a session fails at any point, we teardown everything we\n // set up before throwing the error.\n try {\n let [sessionId, caps] = await super.createSession(...args);\n\n let serverDetails = {\n platform: 'LINUX',\n webStorageEnabled: false,\n takesScreenshot: true,\n javascriptEnabled: true,\n databaseEnabled: false,\n networkConnectionEnabled: true,\n locationContextEnabled: false,\n warnings: {},\n desired: this.caps\n };\n\n this.caps = Object.assign(serverDetails, this.caps);\n\n // assigning defaults\n let defaultOpts = {\n action: 'android.intent.action.MAIN',\n category: 'android.intent.category.LAUNCHER',\n flags: '0x10200000',\n disableAndroidWatchers: false,\n tmpDir: await tempDir.staticDir(),\n fullReset: false,\n autoLaunch: true,\n adbPort: DEFAULT_ADB_PORT,\n bootstrapPort: DEVICE_PORT,\n androidInstallTimeout: 90000,\n };\n _.defaults(this.opts, defaultOpts);\n this.useUnlockHelperApp = _.isUndefined(this.caps.unlockType);\n\n // not user visible via caps\n if (this.opts.noReset === true) {\n this.opts.fullReset = false;\n }\n if (this.opts.fullReset === true) {\n this.opts.noReset = false;\n }\n this.opts.fastReset = !this.opts.fullReset && !this.opts.noReset;\n this.opts.skipUninstall = this.opts.fastReset || this.opts.noReset;\n\n if (this.isChromeSession) {\n helpers.adjustBrowserSessionCaps(this.opts);\n }\n\n if (this.opts.nativeWebScreenshot) {\n this.jwpProxyAvoid.push(['GET', new RegExp('^/session/[^/]+/screenshot')]);\n }\n\n if (this.opts.reboot) {\n this.setAvdFromCapabilities(caps);\n }\n\n // get device udid for this session\n let {udid, emPort} = await helpers.getDeviceInfoFromCaps(this.opts);\n this.opts.udid = udid;\n this.opts.emPort = emPort;\n\n // set up an instance of ADB\n this.adb = await helpers.createADB({\n udid: this.opts.udid,\n emPort: this.opts.emPort,\n adbPort: this.opts.adbPort,\n suppressKillServer: this.opts.suppressKillServer,\n remoteAdbHost: this.opts.remoteAdbHost,\n clearDeviceLogsOnStart: this.opts.clearDeviceLogsOnStart,\n adbExecTimeout: this.opts.adbExecTimeout,\n allowOfflineDevices: this.opts.allowOfflineDevices,\n });\n\n if (await this.adb.getApiLevel() >= 23) {\n this.log.warn(\"Consider setting 'automationName' capability to \" +\n \"'uiautomator2' on Android >= 6, since UIAutomator framework \" +\n 'is not maintained anymore by the OS vendor.');\n }\n\n if (this.helpers.isPackageOrBundle(this.opts.app)) {\n // user provided package instead of app for 'app' capability, massage options\n this.opts.appPackage = this.opts.app;\n this.opts.app = null;\n }\n\n if (this.opts.app) {\n // find and copy, or download and unzip an app url or path\n this.opts.app = await this.helpers.configureApp(this.opts.app, APP_EXTENSION);\n await this.checkAppPresent();\n } else if (this.appOnDevice) {\n // the app isn't an actual app file but rather something we want to\n // assume is on the device and just launch via the appPackage\n this.log.info(`App file was not listed, instead we're going to run ` +\n `${this.opts.appPackage} directly on the device`);\n await this.checkPackagePresent();\n }\n\n // Some cloud services using appium launch the avd themselves, so we ensure netspeed\n // is set for emulators by calling adb.networkSpeed before running the app\n if (util.hasValue(this.opts.networkSpeed)) {\n if (!this.isEmulator()) {\n this.log.warn('Sorry, networkSpeed capability is only available for emulators');\n } else {\n const networkSpeed = ensureNetworkSpeed(this.adb, this.opts.networkSpeed);\n await this.adb.networkSpeed(networkSpeed);\n }\n }\n // check if we have to enable/disable gps before running the application\n if (util.hasValue(this.opts.gpsEnabled)) {\n if (this.isEmulator()) {\n this.log.info(`Trying to ${this.opts.gpsEnabled ? 'enable' : 'disable'} gps location provider`);\n await this.adb.toggleGPSLocationProvider(this.opts.gpsEnabled);\n } else {\n this.log.warn('Sorry! gpsEnabled capability is only available for emulators');\n }\n }\n\n await this.startAndroidSession(this.opts);\n return [sessionId, this.caps];\n } catch (e) {\n // ignoring delete session exception if any and throw the real error\n // that happened while creating the session.\n try {\n await this.deleteSession();\n } catch (ign) {}\n throw e;\n }\n }\n\n isEmulator () {\n return helpers.isEmulator(this.adb, this.opts);\n }\n\n setAvdFromCapabilities (caps) {\n if (this.opts.avd) {\n this.log.info('avd name defined, ignoring device name and platform version');\n } else {\n if (!caps.deviceName) {\n this.log.errorAndThrow('avd or deviceName should be specified when reboot option is enables');\n }\n if (!caps.platformVersion) {\n this.log.errorAndThrow('avd or platformVersion should be specified when reboot option is enabled');\n }\n let avdDevice = caps.deviceName.replace(/[^a-zA-Z0-9_.]/g, '-');\n this.opts.avd = `${avdDevice}__${caps.platformVersion}`;\n }\n }\n\n get appOnDevice () {\n return this.helpers.isPackageOrBundle(this.opts.app) || (!this.opts.app &&\n this.helpers.isPackageOrBundle(this.opts.appPackage));\n }\n\n get isChromeSession () {\n return helpers.isChromeBrowser(this.opts.browserName);\n }\n\n async onSettingsUpdate (key, value) {\n if (key === 'ignoreUnimportantViews') {\n await this.setCompressedLayoutHierarchy(value);\n }\n }\n\n async startAndroidSession () {\n this.log.info(`Starting Android session`);\n // set up the device to run on (real or emulator, etc)\n this.defaultIME = await helpers.initDevice(this.adb, this.opts);\n\n // set actual device name, udid, platform version, screen size, model and manufacturer details.\n this.caps.deviceName = this.adb.curDeviceId;\n this.caps.deviceUDID = this.opts.udid;\n this.caps.platformVersion = await this.adb.getPlatformVersion();\n this.caps.deviceScreenSize = await this.adb.getScreenSize();\n this.caps.deviceModel = await this.adb.getModel();\n this.caps.deviceManufacturer = await this.adb.getManufacturer();\n\n if (this.opts.disableWindowAnimation) {\n if (await this.adb.isAnimationOn()) {\n if (await this.adb.getApiLevel() >= 28) { // API level 28 is Android P\n // Don't forget to reset the relaxing in delete session\n this.log.warn('Relaxing hidden api policy to manage animation scale');\n await this.adb.setHiddenApiPolicy('1', !!this.opts.ignoreHiddenApiPolicyError);\n }\n\n this.log.info('Disabling window animation as it is requested by \"disableWindowAnimation\" capability');\n await this.adb.setAnimationState(false);\n this._wasWindowAnimationDisabled = true;\n } else {\n this.log.info('Window animation is already disabled');\n }\n }\n\n // set up app under test\n await this.initAUT();\n\n // start UiAutomator\n this.bootstrap = new helpers.bootstrap(this.adb, this.opts.bootstrapPort, this.opts.websocket);\n await this.bootstrap.start(this.opts.appPackage, this.opts.disableAndroidWatchers, this.opts.acceptSslCerts);\n // handling unexpected shutdown\n (async () => {\n try {\n await this.bootstrap.onUnexpectedShutdown;\n } catch (err) {\n if (!this.bootstrap.ignoreUnexpectedShutdown) {\n await this.startUnexpectedShutdown(err);\n }\n }\n })();\n\n\n if (!this.opts.skipUnlock) {\n // Let's try to unlock the device\n await helpers.unlock(this, this.adb, this.caps);\n }\n\n // Set CompressedLayoutHierarchy on the device based on current settings object\n // this has to happen _after_ bootstrap is initialized\n if (this.opts.ignoreUnimportantViews) {\n await this.settings.update({ignoreUnimportantViews: this.opts.ignoreUnimportantViews});\n }\n\n if (this.isChromeSession) {\n // start a chromedriver session and proxy to it\n await this.startChromeSession();\n } else {\n if (this.opts.autoLaunch) {\n // start app\n await this.startAUT();\n }\n }\n\n if (util.hasValue(this.opts.orientation)) {\n this.log.debug(`Setting initial orientation to '${this.opts.orientation}'`);\n await this.setOrientation(this.opts.orientation);\n }\n\n await this.initAutoWebview();\n }\n\n async initAutoWebview () {\n if (this.opts.autoWebview) {\n let viewName = this.defaultWebviewName();\n let timeout = (this.opts.autoWebviewTimeout) || 2000;\n\n this.log.info(`Setting auto webview to context '${viewName}' with timeout ${timeout}ms`);\n\n // try every 500ms until timeout is over\n await retryInterval(timeout / 500, 500, async () => {\n await this.setContext(viewName);\n });\n }\n }\n\n async initAUT () {\n // populate appPackage, appActivity, appWaitPackage, appWaitActivity,\n // and the device being used\n // in the opts and caps (so it gets back to the user on session creation)\n let launchInfo = await helpers.getLaunchInfo(this.adb, this.opts);\n Object.assign(this.opts, launchInfo);\n Object.assign(this.caps, launchInfo);\n\n // Uninstall any uninstallOtherPackages which were specified in caps\n if (this.opts.uninstallOtherPackages) {\n helpers.validateDesiredCaps(this.opts);\n // Only SETTINGS_HELPER_PKG_ID package is used by UIA1\n await helpers.uninstallOtherPackages(\n this.adb,\n helpers.parseArray(this.opts.uninstallOtherPackages),\n [SETTINGS_HELPER_PKG_ID]\n );\n }\n\n // Install any \"otherApps\" that were specified in caps\n if (this.opts.otherApps) {\n let otherApps;\n try {\n otherApps = helpers.parseArray(this.opts.otherApps);\n } catch (e) {\n this.log.errorAndThrow(`Could not parse \"otherApps\" capability: ${e.message}`);\n }\n otherApps = await B.all(otherApps.map((app) => this.helpers.configureApp(app, APP_EXTENSION)));\n await helpers.installOtherApks(otherApps, this.adb, this.opts);\n }\n\n // install app\n if (!this.opts.app) {\n if (this.opts.fullReset) {\n this.log.errorAndThrow('Full reset requires an app capability, use fastReset if app is not provided');\n }\n this.log.debug('No app capability. Assuming it is already on the device');\n if (this.opts.fastReset) {\n await helpers.resetApp(this.adb, this.opts);\n }\n return;\n }\n if (!this.opts.skipUninstall) {\n await this.adb.uninstallApk(this.opts.appPackage);\n }\n await helpers.installApk(this.adb, this.opts);\n const apkStringsForLanguage = await helpers.pushStrings(this.opts.language, this.adb, this.opts);\n if (this.opts.language) {\n this.apkStrings[this.opts.language] = apkStringsForLanguage;\n }\n\n // This must run after installing the apk, otherwise it would cause the\n // install to fail. And before running the app.\n if (!_.isUndefined(this.opts.sharedPreferences)) {\n await this.setSharedPreferences(this.opts);\n }\n }\n\n async checkAppPresent () {\n this.log.debug('Checking whether app is actually present');\n if (!(await fs.exists(this.opts.app))) {\n this.log.errorAndThrow(`Could not find app apk at ${this.opts.app}`);\n }\n }\n\n async checkPackagePresent () {\n this.log.debug('Checking whether package is present on the device');\n if (!(await this.adb.shell(['pm', 'list', 'packages', this.opts.appPackage]))) {\n this.log.errorAndThrow(`Could not find package ${this.opts.appPackage} on the device`);\n }\n }\n\n // Set CompressedLayoutHierarchy on the device\n async setCompressedLayoutHierarchy (compress) {\n await this.bootstrap.sendAction('compressedLayoutHierarchy', {compressLayout: compress});\n }\n\n async deleteSession () {\n this.log.debug('Shutting down Android driver');\n\n try {\n if (!_.isEmpty(this._screenRecordingProperties)) {\n await this.stopRecordingScreen();\n }\n } catch (ign) {}\n\n await helpers.removeAllSessionWebSocketHandlers(this.server, this.sessionId);\n\n await this.mobileStopScreenStreaming();\n\n await super.deleteSession();\n\n if (this.bootstrap) {\n // certain cleanup we only care to do if the bootstrap was ever run\n await this.stopChromedriverProxies();\n if (this.opts.unicodeKeyboard && this.opts.resetKeyboard && this.defaultIME) {\n this.log.debug(`Resetting IME to ${this.defaultIME}`);\n await this.adb?.setIME(this.defaultIME);\n }\n if (!this.isChromeSession && !this.opts.dontStopAppOnReset) {\n await this.adb?.forceStop(this.opts.appPackage);\n }\n await this.adb?.goToHome();\n if (this.opts.fullReset && !this.opts.skipUninstall && !this.appOnDevice) {\n await this.adb?.uninstallApk(this.opts.appPackage);\n }\n await this.bootstrap.shutdown();\n this.bootstrap = null;\n } else {\n this.log.debug(\"Called deleteSession but bootstrap wasn't active\");\n }\n // some cleanup we want to do regardless, in case we are shutting down\n // mid-startup\n await this.adb?.stopLogcat();\n if (this.useUnlockHelperApp) {\n await this.adb?.forceStop('io.appium.unlock');\n }\n if (this._wasWindowAnimationDisabled) {\n this.log.info('Restoring window animation state');\n await this.adb?.setAnimationState(true);\n\n // This was necessary to change animation scale over Android P. We must reset the policy for the security.\n if (await this.adb?.getApiLevel() >= 28) {\n this.log.info('Restoring hidden api policy to the device default configuration');\n await this.adb?.setDefaultHiddenApiPolicy(!!this.opts.ignoreHiddenApiPolicyError);\n }\n }\n\n if (this.opts.reboot) {\n let avdName = this.opts.avd.replace('@', '');\n this.log.debug(`closing emulator '${avdName}'`);\n await this.adb?.killEmulator(avdName);\n }\n }\n\n async setSharedPreferences () {\n let sharedPrefs = this.opts.sharedPreferences;\n this.log.info('Trying to set shared preferences');\n let name = sharedPrefs.name;\n if (_.isUndefined(name)) {\n this.log.warn(`Skipping setting Shared preferences, name is undefined: ${JSON.stringify(sharedPrefs)}`);\n return false;\n }\n let remotePath = `/data/data/${this.opts.appPackage}/shared_prefs`;\n let remoteFile = `${remotePath}/${name}.xml`;\n let localPath = `/tmp/${name}.xml`;\n let builder = this.getPrefsBuilder();\n builder.build(sharedPrefs.prefs);\n this.log.info(`Creating temporary shared preferences: ${localPath}`);\n builder.toFile(localPath);\n this.log.info(`Creating shared_prefs remote folder: ${remotePath}`);\n await this.adb.shell(['mkdir', '-p', remotePath]);\n this.log.info(`Pushing shared_prefs to ${remoteFile}`);\n await this.adb.push(localPath, remoteFile);\n try {\n this.log.info(`Trying to remove shared preferences temporary file`);\n if (await fs.exists(localPath)) {\n await fs.unlink(localPath);\n }\n } catch (e) {\n this.log.warn(`Error trying to remove temporary file ${localPath}`);\n }\n return true;\n }\n\n getPrefsBuilder () {\n /* Add this method to create a new SharedPrefsBuilder instead of\n * directly creating the object on setSharedPreferences for testing purposes\n */\n return new SharedPrefsBuilder();\n }\n\n validateDesiredCaps (caps) {\n if (!super.validateDesiredCaps(caps)) {\n return false;\n }\n if ((!caps.browserName || !helpers.isChromeBrowser(caps.browserName)) && !caps.app && !caps.appPackage) {\n this.log.errorAndThrow('The desired capabilities must include either an app, appPackage or browserName');\n }\n return helpers.validateDesiredCaps(caps);\n }\n\n proxyActive (sessionId) {\n super.proxyActive(sessionId);\n\n return this.jwpProxyActive;\n }\n\n getProxyAvoidList (sessionId) {\n super.getProxyAvoidList(sessionId);\n\n return this.jwpProxyAvoid;\n }\n\n canProxy (sessionId) {\n super.canProxy(sessionId);\n\n // this will change depending on ChromeDriver status\n return _.isFunction(this.proxyReqRes);\n }\n}\n\nexport { AndroidDriver };\nexport default AndroidDriver;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AAIA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEA,MAAMA,aAAa,GAAG,MAAtB;AACA,MAAMC,WAAW,GAAG,IAApB;AAIA,MAAMC,QAAQ,GAAG,CACf,CAAC,MAAD,EAAS,IAAIC,MAAJ,CAAW,yBAAX,CAAT,CADe,EAEf,CAAC,KAAD,EAAQ,IAAIA,MAAJ,CAAW,yBAAX,CAAR,CAFe,EAGf,CAAC,MAAD,EAAS,IAAIA,MAAJ,CAAW,wBAAX,CAAT,CAHe,EAIf,CAAC,KAAD,EAAQ,IAAIA,MAAJ,CAAW,wBAAX,CAAR,CAJe,EAKf,CAAC,MAAD,EAAS,IAAIA,MAAJ,CAAW,+BAAX,CAAT,CALe,EAMf,CAAC,MAAD,EAAS,IAAIA,MAAJ,CAAW,qCAAX,CAAT,CANe,EAOf,CAAC,MAAD,EAAS,IAAIA,MAAJ,CAAW,6BAAX,CAAT,CAPe,EAQf,CAAC,KAAD,EAAQ,IAAIA,MAAJ,CAAW,6BAAX,CAAR,CARe,EASf,CAAC,MAAD,EAAS,IAAIA,MAAJ,CAAW,yBAAX,CAAT,CATe,EAUf,CAAC,MAAD,EAAS,IAAIA,MAAJ,CAAW,8BAAX,CAAT,CAVe,EAWf,CAAC,KAAD,EAAQ,IAAIA,MAAJ,CAAW,oCAAX,CAAR,CAXe,EAYf,CAAC,MAAD,EAAS,IAAIA,MAAJ,CAAW,oCAAX,CAAT,CAZe,CAAjB;;AAeA,MAAMC,aAAN,SAA4BC,kBAA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AC+E,WAAN,IAAqB,CAAC1F,uBAAA,CAAQyF,eAAR,CAAwB9E,IAAI,CAAC+E,WAA7B,CAAvB,KAAqE,CAAC/E,IAAI,CAACsD,GAA3E,IAAkF,CAACtD,IAAI,CAACuD,UAA5F,EAAwG;MACtG,KAAKJ,GAAL,CAASuB,aAAT,CAAuB,gFAAvB;IACD;;IACD,OAAOrF,uBAAA,CAAQ2I,mBAAR,CAA4BhI,IAA5B,CAAP;EACD;;EAEDuL,WAAW,CAAExL,SAAF,EAAa;IACtB,MAAMwL,WAAN,CAAkBxL,SAAlB;IAEA,OAAO,KAAKtB,cAAZ;EACD;;EAED+M,iBAAiB,CAAEzL,SAAF,EAAa;IAC5B,MAAMyL,iBAAN,CAAwBzL,SAAxB;IAEA,OAAO,KAAKrB,aAAZ;EACD;;EAED+M,QAAQ,CAAE1L,SAAF,EAAa;IACnB,MAAM0L,QAAN,CAAe1L,SAAf;IAGA,OAAOpB,eAAA,CAAE+M,UAAF,CAAa,KAAKC,WAAlB,CAAP;EACD;;AApeoC;;;eAwexB3N,a"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.js","names":["log","logger","getLogger"],"sources":["../../lib/logger.js"],"sourcesContent":["import { logger } from 'appium/support';\nconst log = logger.getLogger('AndroidDriver');\n\nexport default log;\n"],"mappings":";;;;;;;;;AAAA;;AACA,MAAMA,GAAG,GAAGC,eAAA,CAAOC,SAAP,CAAiB,eAAjB,CAAZ;;eAEeF,G"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uiautomator.js","names":["log","logger","getLogger","UiAutomator","events","EventEmitter","constructor","adb","errorAndThrow","tempPath","start","uiAutomatorBinaryPath","className","startDetector","extraParams","processIsAlive","debug","changeState","STATE_STARTING","jarName","parseJarNameFromPath","push","killUiAutomatorOnDevice","args","proc","createSubProcess","on","code","signal","state","STATE_STOPPED","STATE_STOPPING","msg","error","STATE_ONLINE","e","emit","EVENT_ERROR","stop","shutdown","binaryPath","reTest","exec","Error","EVENT_CHANGED","killProcessesByName","warn"],"sources":["../../lib/uiautomator.js"],"sourcesContent":["import events from 'events';\nimport { logger } from 'appium/support';\n\n\nconst log = logger.getLogger('UiAutomator');\n\nclass UiAutomator extends events.EventEmitter {\n constructor (adb) {\n if (!adb) {\n log.errorAndThrow('adb is required to instantiate UiAutomator');\n }\n super();\n this.adb = adb;\n this.tempPath = '/data/local/tmp/';\n }\n\n async start (uiAutomatorBinaryPath, className, startDetector, ...extraParams) {\n let processIsAlive;\n try {\n log.debug('Starting UiAutomator');\n this.changeState(UiAutomator.STATE_STARTING);\n\n log.debug('Parsing uiautomator jar');\n // expecting a path like /ads/ads/foo.jar or \\asd\\asd\\foo.jar\n let jarName = this.parseJarNameFromPath(uiAutomatorBinaryPath);\n await this.adb.push(uiAutomatorBinaryPath, this.tempPath);\n\n // killing any uiautomator existing processes\n await this.killUiAutomatorOnDevice();\n\n log.debug('Starting UIAutomator');\n let args = ['shell', 'uiautomator', 'runtest', jarName, '-c', className, ...extraParams];\n this.proc = this.adb.createSubProcess(args);\n\n // handle out-of-bound exit by simply emitting a stopped state\n this.proc.on('exit', (code, signal) => {\n processIsAlive = false;\n // cleanup\n if (this.state !== UiAutomator.STATE_STOPPED &&\n this.state !== UiAutomator.STATE_STOPPING) {\n let msg = `UiAutomator exited unexpectedly with code ${code}, ` +\n `signal ${signal}`;\n log.error(msg);\n } else if (this.state === UiAutomator.STATE_STOPPING) {\n log.debug('UiAutomator shut down normally');\n }\n this.changeState(UiAutomator.STATE_STOPPED);\n });\n\n await this.proc.start(startDetector);\n processIsAlive = true;\n this.changeState(UiAutomator.STATE_ONLINE);\n return this.proc;\n } catch (e) {\n this.emit(UiAutomator.EVENT_ERROR, e);\n if (processIsAlive) {\n await this.killUiAutomatorOnDevice();\n await this.proc.stop();\n }\n log.errorAndThrow(e);\n }\n }\n\n async shutdown () {\n log.debug('Shutting down UiAutomator');\n if (this.state !== UiAutomator.STATE_STOPPED) {\n this.changeState(UiAutomator.STATE_STOPPING);\n await this.proc.stop();\n }\n await this.killUiAutomatorOnDevice();\n this.changeState(UiAutomator.STATE_STOPPED);\n }\n\n parseJarNameFromPath (binaryPath) {\n let reTest = /.*(\\/|\\\\)(.*\\.jar)/.exec(binaryPath);\n if (!reTest) {\n throw new Error(`Unable to parse jar name from ${binaryPath}`);\n }\n let jarName = reTest[2];\n log.debug(`Found jar name: '${jarName}'`);\n return jarName;\n }\n\n changeState (state) {\n log.debug(`Moving to state '${state}'`);\n this.state = state;\n this.emit(UiAutomator.EVENT_CHANGED, {state});\n }\n\n async killUiAutomatorOnDevice () {\n try {\n await this.adb.killProcessesByName('uiautomator');\n } catch (e) {\n log.warn(`Error while killing uiAutomator: ${e}`);\n }\n }\n\n}\n\nUiAutomator.EVENT_ERROR = 'uiautomator_error';\nUiAutomator.EVENT_CHANGED = 'stateChanged';\nUiAutomator.STATE_STOPPING = 'stopping';\nUiAutomator.STATE_STOPPED = 'stopped';\nUiAutomator.STATE_STARTING = 'starting';\nUiAutomator.STATE_ONLINE = 'online';\n\n\nexport { UiAutomator };\nexport default UiAutomator;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AAGA,MAAMA,GAAG,GAAGC,eAAA,CAAOC,SAAP,CAAiB,aAAjB,CAAZ;;AAEA,MAAMC,WAAN,SAA0BC,eAAA,CAAOC,YAAjC,CAA8C;EAC5CC,WAAW,CAAEC,GAAF,EAAO;IAChB,IAAI,CAACA,GAAL,EAAU;MACRP,GAAG,CAACQ,aAAJ,CAAkB,4CAAlB;IACD;;IACD;IACA,KAAKD,GAAL,GAAWA,GAAX;IACA,KAAKE,QAAL,GAAgB,kBAAhB;EACD;;EAEU,MAALC,KAAK,CAAEC,qBAAF,EAAyBC,SAAzB,EAAoCC,aAApC,EAAmD,GAAGC,WAAtD,EAAmE;IAC5E,IAAIC,cAAJ;;IACA,IAAI;MACFf,GAAG,CAACgB,KAAJ,CAAU,sBAAV;MACA,KAAKC,WAAL,CAAiBd,WAAW,CAACe,cAA7B;MAE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