target.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. /*
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. const path = require('path');
  18. const { inspect } = require('util');
  19. const Adb = require('./Adb');
  20. const build = require('./build');
  21. const emulator = require('./emulator');
  22. const AndroidManifest = require('./AndroidManifest');
  23. const { compareBy } = require('./utils');
  24. const { retryPromise } = require('./retry');
  25. const { events, CordovaError } = require('cordova-common');
  26. const INSTALL_COMMAND_TIMEOUT = 5 * 60 * 1000;
  27. const NUM_INSTALL_RETRIES = 3;
  28. const EXEC_KILL_SIGNAL = 'SIGKILL';
  29. /**
  30. * @typedef { 'device' | 'emulator' } TargetType
  31. * @typedef { { id: string, type: TargetType } } Target
  32. * @typedef { { id?: string, type?: TargetType } } TargetSpec
  33. */
  34. /**
  35. * Returns a list of available targets (connected devices & started emulators)
  36. *
  37. * @return {Promise<Target[]>}
  38. */
  39. exports.list = async () => {
  40. return (await Adb.devices())
  41. .map(id => ({
  42. id,
  43. type: id.startsWith('emulator-') ? 'emulator' : 'device'
  44. }));
  45. };
  46. /**
  47. * @param {TargetSpec?} spec
  48. * @return {Promise<Target>}
  49. */
  50. async function resolveToOnlineTarget (spec = {}) {
  51. const targetList = await exports.list();
  52. if (targetList.length === 0) return null;
  53. // Sort by type: devices first, then emulators.
  54. targetList.sort(compareBy(t => t.type));
  55. // Find first matching target for spec. {} matches any target.
  56. return targetList.find(target =>
  57. Object.keys(spec).every(k => spec[k] === target[k])
  58. ) || null;
  59. }
  60. async function isEmulatorName (name) {
  61. const emus = await emulator.list_images();
  62. return emus.some(avd => avd.name === name);
  63. }
  64. /**
  65. * @param {TargetSpec?} spec
  66. * @return {Promise<Target>}
  67. */
  68. async function resolveToOfflineEmulator (spec = {}) {
  69. if (spec.type === 'device') return null;
  70. if (spec.id && !(await isEmulatorName(spec.id))) return null;
  71. // try to start an emulator with name spec.id
  72. // if spec.id is undefined, picks best match regarding target API
  73. const emulatorId = await emulator.start(spec.id);
  74. return { id: emulatorId, type: 'emulator' };
  75. }
  76. /**
  77. * @param {TargetSpec?} spec
  78. * @return {Promise<Target & {arch: string}>}
  79. */
  80. exports.resolve = async (spec = {}) => {
  81. events.emit('verbose', `Trying to find target matching ${inspect(spec)}`);
  82. const resolvedTarget =
  83. (await resolveToOnlineTarget(spec)) ||
  84. (await resolveToOfflineEmulator(spec));
  85. if (!resolvedTarget) {
  86. throw new CordovaError(`Could not find target matching ${inspect(spec)}`);
  87. }
  88. return {
  89. ...resolvedTarget,
  90. arch: await build.detectArchitecture(resolvedTarget.id)
  91. };
  92. };
  93. exports.install = async function ({ id: target, arch, type }, buildResults) {
  94. const apk_path = build.findBestApkForArchitecture(buildResults, arch);
  95. const manifest = new AndroidManifest(path.join(__dirname, '../../app/src/main/AndroidManifest.xml'));
  96. const pkgName = manifest.getPackageId();
  97. const launchName = pkgName + '/.' + manifest.getActivity().getName();
  98. events.emit('log', 'Using apk: ' + apk_path);
  99. events.emit('log', 'Package name: ' + pkgName);
  100. events.emit('verbose', `Installing app on target ${target}`);
  101. async function doInstall (execOptions = {}) {
  102. try {
  103. await Adb.install(target, apk_path, { replace: true, execOptions });
  104. } catch (error) {
  105. // CB-9557 CB-10157 only uninstall and reinstall app if the one that
  106. // is already installed on device was signed w/different certificate
  107. if (!/INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES/.test(error.toString())) throw error;
  108. events.emit('warn', 'Uninstalling app from device and reinstalling it again because the ' +
  109. 'installed app already signed with different key');
  110. // This promise is always resolved, even if 'adb uninstall' fails to uninstall app
  111. // or the app doesn't installed at all, so no error catching needed.
  112. await Adb.uninstall(target, pkgName);
  113. await Adb.install(target, apk_path, { replace: true });
  114. }
  115. }
  116. if (type === 'emulator') {
  117. // Work around sporadic emulator hangs: http://issues.apache.org/jira/browse/CB-9119
  118. await retryPromise(NUM_INSTALL_RETRIES, () => doInstall({
  119. timeout: INSTALL_COMMAND_TIMEOUT,
  120. killSignal: EXEC_KILL_SIGNAL
  121. }));
  122. } else {
  123. await doInstall();
  124. }
  125. events.emit('log', 'INSTALL SUCCESS');
  126. events.emit('verbose', 'Unlocking screen...');
  127. await Adb.shell(target, 'input keyevent 82');
  128. await Adb.start(target, launchName);
  129. events.emit('log', 'LAUNCH SUCCESS');
  130. };