TagSpaces is an offline, open source, document manager with tagging support
recreating android platform added cordova-media plugin
Ilian Sapundshieve0e33cab7e47
diff --git a/cordova/config.xml b/cordova/config.xmlindex 6e6107319..b92010613 100644--- a/cordova/config.xml+++ b/cordova/config.xml@@ -29,5 +29,6 @@<plugin name="cordova-plugin-device" spec="^2.0.2" /><plugin name="cordova-plugin-whitelist" spec="^1.3.3" /><plugin name="cordova-plugin-camera" spec="~4.0.3" />- <engine name="android" spec="git+https://github.com/apache/cordova-android.git" />+ <plugin name="cordova-plugin-media" spec="^5.0.2" />+ <engine name="android" spec="^7.1.4" /></widget>diff --git a/cordova/package.json b/cordova/package.jsonindex ecbd00836..52e27a1f8 100644--- a/cordova/package.json+++ b/cordova/package.json@@ -10,10 +10,11 @@"author": "Apache Cordova Team","license": "Apache-2.0","dependencies": {- "cordova-android": "git+https://github.com/apache/cordova-android.git",+ "cordova-android": "^7.1.4","cordova-plugin-camera": "^4.0.3","cordova-plugin-device": "^2.0.2","cordova-plugin-file": "^6.0.1",+ "cordova-plugin-media": "^5.0.2","cordova-plugin-whitelist": "^1.3.3"},"cordova": {@@ -21,6 +22,7 @@"cordova-plugin-whitelist": {},"cordova-plugin-file": {},"cordova-plugin-device": {},+ "cordova-plugin-media": {},"cordova-plugin-camera": {}},"platforms": [diff --git a/cordova/platforms/android/.gitignore b/cordova/platforms/android/.gitignoreindex 5eced2b9c..6e5244597 100644--- a/cordova/platforms/android/.gitignore+++ b/cordova/platforms/android/.gitignore@@ -1,6 +1,9 @@# Non-project-specific build files:build.xmllocal.properties+/gradlew+/gradlew.bat+/gradle# Ant buildsant-buildant-gendiff --git a/cordova/platforms/android/CordovaLib/build.gradle b/cordova/platforms/android/CordovaLib/build.gradleindex 834617a93..4f7f171ca 100644--- a/cordova/platforms/android/CordovaLib/build.gradle+++ b/cordova/platforms/android/CordovaLib/build.gradle@@ -24,15 +24,15 @@ ext {buildscript {repositories {- google()+ maven {+ url "https://maven.google.com"+ }jcenter()}dependencies {- // The gradle plugin and the maven plugin have to be updated after each version of Android- // studio comes out- classpath 'com.android.tools.build:gradle:3.2.0'- classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'+ classpath 'com.android.tools.build:gradle:3.0.1'+ classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'}}@@ -42,11 +42,12 @@ apply plugin: 'com.github.dcendents.android-maven'apply plugin: 'com.jfrog.bintray'group = 'org.apache.cordova'-version = '8.0.0-dev'+version = '7.1.4'android {compileSdkVersion cdvCompileSdkVersionbuildToolsVersion cdvBuildToolsVersion+ publishNonDefault truecompileOptions {sourceCompatibility JavaVersion.VERSION_1_8@@ -93,9 +94,9 @@ install {}}scm {- connection 'scm:git:https://github.com/apache/cordova-android.git'- developerConnection 'scm:git:[email protected]:apache/cordova-android.git'- url 'https://github.com/apache/cordova-android'+ connection 'https://git-wip-us.apache.org/repos/asf?p=cordova-android.git'+ developerConnection 'https://git-wip-us.apache.org/repos/asf?p=cordova-android.git'+ url 'https://git-wip-us.apache.org/repos/asf?p=cordova-android'}}@@ -121,16 +122,16 @@ bintray {name = 'cordova-android'userOrg = 'cordova'licenses = ['Apache-2.0']- vcsUrl = 'https://github.com/apache/cordova-android'+ vcsUrl = 'https://git-wip-us.apache.org/repos/asf?p=cordova-android.git'websiteUrl = 'https://cordova.apache.org'- issueTrackerUrl = 'https://github.com/apache/cordova-android/issues'+ issueTrackerUrl = 'https://issues.apache.org/jira/browse/CB'publicDownloadNumbers = truelicenses = ['Apache-2.0']labels = ['android', 'cordova', 'phonegap']version {- name = '8.0.0-dev'+ name = '7.1.4'released = new Date()- vcsTag = '8.0.0-dev'+ vcsTag = '7.1.4'}}}diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebView.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebView.javaindex 306339837..f4cab35f0 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebView.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebView.java@@ -31,7 +31,7 @@ import android.webkit.WebChromeClient.CustomViewCallback;* are not expected to implement it.*/public interface CordovaWebView {- public static final String CORDOVA_VERSION = "8.0.0-dev";+ public static final String CORDOVA_VERSION = "7.1.4";void init(CordovaInterface cordova, List<PluginEntry> pluginEntries, CordovaPreferences preferences);diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebViewImpl.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebViewImpl.javaindex 1db2e9554..fb99c3443 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebViewImpl.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebViewImpl.java@@ -216,10 +216,8 @@ public class CordovaWebViewImpl implements CordovaWebView {// TODO: What about params?// Load new URLloadUrlIntoView(url, true);- return;} else {LOG.w(TAG, "showWebPage: Refusing to load URL into webview since it is not in the <allow-navigation> whitelist. URL=" + url);- return;}}if (!pluginManager.shouldOpenExternalUrl(url)) {diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CoreAndroid.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CoreAndroid.javaindex 3945cdd62..e384f8d74 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CoreAndroid.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CoreAndroid.java@@ -43,7 +43,6 @@ public class CoreAndroid extends CordovaPlugin {private BroadcastReceiver telephonyReceiver;private CallbackContext messageChannel;private PluginResult pendingResume;- private PluginResult pendingPause;private final Object messageChannelLock = new Object();/**@@ -114,10 +113,6 @@ public class CoreAndroid extends CordovaPlugin {else if (action.equals("messageChannel")) {synchronized(messageChannelLock) {messageChannel = callbackContext;- if (pendingPause != null) {- sendEventMessage(pendingPause);- pendingPause = null;- }if (pendingResume != null) {sendEventMessage(pendingResume);pendingResume = null;@@ -144,7 +139,7 @@ public class CoreAndroid extends CordovaPlugin {public void clearCache() {cordova.getActivity().runOnUiThread(new Runnable() {public void run() {- webView.clearCache();+ webView.clearCache(true);}});}@@ -326,19 +321,7 @@ public class CoreAndroid extends CordovaPlugin {} catch (JSONException e) {LOG.e(TAG, "Failed to create event message", e);}- PluginResult result = new PluginResult(PluginResult.Status.OK, obj);-- if (messageChannel == null) {- LOG.i(TAG, "Request to send event before messageChannel initialised: " + action);- if ("pause".equals(action)) {- pendingPause = result;- } else if ("resume".equals(action)) {- // When starting normally onPause then onResume is called- pendingPause = null;- }- } else {- sendEventMessage(result);- }+ sendEventMessage(new PluginResult(PluginResult.Status.OK, obj));}private void sendEventMessage(PluginResult payload) {diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemCookieManager.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemCookieManager.javaindex 3e5df513b..acf795fa6 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemCookieManager.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemCookieManager.java@@ -58,11 +58,7 @@ class SystemCookieManager implements ICordovaCookieManager {}public void clearCookies() {- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {- cookieManager.removeAllCookies(null);- } else {- cookieManager.removeAllCookie();- }+ cookieManager.removeAllCookie();}public void flush() {diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.javaindex 72846f0fc..a27fc6af4 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.java@@ -142,7 +142,6 @@ public class SystemWebChromeClient extends WebChromeClient {* Handle database quota exceeded notification.*/@Override- @SuppressWarnings("deprecation")public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize,long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater){@@ -181,13 +180,11 @@ public class SystemWebChromeClient extends WebChromeClient {// API level 7 is required for this, see if we could lower this using something else@Override- @SuppressWarnings("deprecation")public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {parentEngine.getCordovaWebView().showCustomView(view, callback);}@Override- @SuppressWarnings("deprecation")public void onHideCustomView() {parentEngine.getCordovaWebView().hideCustomView();}diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.javaindex 616cef1ed..0b6a577ea 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java@@ -74,8 +74,7 @@ public class SystemWebViewClient extends WebViewClient {* @param url The url to be loaded.* @return true to override, false for default behavior*/- @Override- @SuppressWarnings("deprecation")+ @Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {return parentEngine.client.onNavigationAttempt(url);}@@ -187,7 +186,6 @@ public class SystemWebViewClient extends WebViewClient {* @param failingUrl The url that failed to load.*/@Override- @SuppressWarnings("deprecation")public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {// Ignore error due to stopLoading().if (!isCurrentlyLoading) {@@ -318,7 +316,6 @@ public class SystemWebViewClient extends WebViewClient {}@Override- @SuppressWarnings("deprecation")public WebResourceResponse shouldInterceptRequest(WebView view, String url) {try {// Check the against the whitelist and lock out access to the WebView directorydiff --git a/cordova/platforms/android/android.json b/cordova/platforms/android/android.jsonindex c0fbf7475..af50ce707 100644--- a/cordova/platforms/android/android.json+++ b/cordova/platforms/android/android.json@@ -24,6 +24,10 @@"xml": "<allow-navigation href=\"cdvfile:*\" />","count": 1},+ {+ "xml": "<feature name=\"Media\"><param name=\"android-package\" value=\"org.apache.cordova.media.AudioHandler\" /></feature>",+ "count": 1+ },{"xml": "<feature name=\"Whitelist\"><param name=\"android-package\" value=\"org.apache.cordova.whitelist.WhitelistPlugin\" /><param name=\"onload\" value=\"true\" /></feature>","count": 1@@ -36,7 +40,19 @@"/*": [{"xml": "<uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" />",- "count": 2+ "count": 3+ },+ {+ "xml": "<uses-permission android:name=\"android.permission.RECORD_AUDIO\" />",+ "count": 1+ },+ {+ "xml": "<uses-permission android:name=\"android.permission.MODIFY_AUDIO_SETTINGS\" />",+ "count": 1+ },+ {+ "xml": "<uses-permission android:name=\"android.permission.READ_PHONE_STATE\" />",+ "count": 1}],"application": [@@ -59,6 +75,9 @@"cordova-plugin-file": {"PACKAGE_NAME": "org.tagspaces.mobile"},+ "cordova-plugin-media": {+ "PACKAGE_NAME": "org.tagspaces.mobile"+ },"cordova-plugin-whitelist": {"PACKAGE_NAME": "org.tagspaces.mobile"}@@ -277,12 +296,29 @@"cordova"],"runs": true+ },+ {+ "id": "cordova-plugin-media.MediaError",+ "file": "plugins/cordova-plugin-media/www/MediaError.js",+ "pluginId": "cordova-plugin-media",+ "clobbers": [+ "window.MediaError"+ ]+ },+ {+ "id": "cordova-plugin-media.Media",+ "file": "plugins/cordova-plugin-media/www/Media.js",+ "pluginId": "cordova-plugin-media",+ "clobbers": [+ "window.Media"+ ]}],"plugin_metadata": {"cordova-plugin-camera": "4.0.3","cordova-plugin-device": "2.0.2","cordova-plugin-file": "6.0.1",+ "cordova-plugin-media": "5.0.2","cordova-plugin-whitelist": "1.3.3"}}\ No newline at end of filediff --git a/cordova/platforms/android/app/build.gradle b/cordova/platforms/android/app/build.gradleindex 802d9bfdc..a7cc3f4e1 100644--- a/cordova/platforms/android/app/build.gradle+++ b/cordova/platforms/android/app/build.gradle@@ -22,32 +22,33 @@ apply plugin: 'com.android.application'buildscript {repositories {mavenCentral()- google()+ maven {+ url "https://maven.google.com"+ }jcenter()}dependencies {- classpath 'com.android.tools.build:gradle:3.2.0'+ classpath 'com.android.tools.build:gradle:3.0.1'}}// Allow plugins to declare Maven dependencies via build-extras.gradle.allprojects {repositories {- mavenCentral()+ mavenCentral();jcenter()}}task wrapper(type: Wrapper) {- gradleVersion = '4.6.0'+ gradleVersion = '4.1.0'}// Configuration properties. Set these via environment variables, build-extras.gradle, or gradle.properties.// Refer to: http://www.gradle.org/docs/current/userguide/tutorial_this_and_that.htmlext {apply from: '../CordovaLib/cordova.gradle'-// The value for android.compileSdkVersion.if (!project.hasProperty('cdvCompileSdkVersion')) {cdvCompileSdkVersion = null;@@ -144,25 +145,24 @@ cdvBuildRelease.dependsOn {return computeBuildTargetName(false)}-task cdvPrintProps {- doLast {- println('cdvCompileSdkVersion=' + cdvCompileSdkVersion)- println('cdvBuildToolsVersion=' + cdvBuildToolsVersion)- println('cdvVersionCode=' + cdvVersionCode)- println('cdvVersionCodeForceAbiDigit=' + cdvVersionCodeForceAbiDigit)- println('cdvMinSdkVersion=' + cdvMinSdkVersion)- println('cdvBuildMultipleApks=' + cdvBuildMultipleApks)- println('cdvReleaseSigningPropertiesFile=' + cdvReleaseSigningPropertiesFile)- println('cdvDebugSigningPropertiesFile=' + cdvDebugSigningPropertiesFile)- println('cdvBuildArch=' + cdvBuildArch)- println('computedVersionCode=' + android.defaultConfig.versionCode)- android.productFlavors.each { flavor ->- println('computed' + flavor.name.capitalize() + 'VersionCode=' + flavor.versionCode)- }+task cdvPrintProps << {+ println('cdvCompileSdkVersion=' + cdvCompileSdkVersion)+ println('cdvBuildToolsVersion=' + cdvBuildToolsVersion)+ println('cdvVersionCode=' + cdvVersionCode)+ println('cdvVersionCodeForceAbiDigit=' + cdvVersionCodeForceAbiDigit)+ println('cdvMinSdkVersion=' + cdvMinSdkVersion)+ println('cdvBuildMultipleApks=' + cdvBuildMultipleApks)+ println('cdvReleaseSigningPropertiesFile=' + cdvReleaseSigningPropertiesFile)+ println('cdvDebugSigningPropertiesFile=' + cdvDebugSigningPropertiesFile)+ println('cdvBuildArch=' + cdvBuildArch)+ println('computedVersionCode=' + android.defaultConfig.versionCode)+ android.productFlavors.each { flavor ->+ println('computed' + flavor.name.capitalize() + 'VersionCode=' + flavor.versionCode)}}android {+defaultConfig {versionCode cdvVersionCode ?: new BigInteger("" + privateHelpers.extractIntFromManifest("versionCode"))applicationId privateHelpers.extractStringFromManifest("package")@@ -249,7 +249,6 @@ android {}addSigningProps(cdvReleaseSigningPropertiesFile, signingConfigs.release)}-if (cdvDebugSigningPropertiesFile) {addSigningProps(cdvDebugSigningPropertiesFile, signingConfigs.debug)}@@ -266,7 +265,7 @@ dependencies {implementation fileTree(dir: 'libs', include: '*.jar')// SUB-PROJECT DEPENDENCIES STARTimplementation(project(path: ":CordovaLib"))- implementation "com.android.support:support-v4:24.1.1+"+ compile "com.android.support:support-v4:24.1.1+"// SUB-PROJECT DEPENDENCIES END}diff --git a/cordova/platforms/android/app/src/main/AndroidManifest.xml b/cordova/platforms/android/app/src/main/AndroidManifest.xmlindex 135b7c9b2..a8c9c5f81 100644--- a/cordova/platforms/android/app/src/main/AndroidManifest.xml+++ b/cordova/platforms/android/app/src/main/AndroidManifest.xml@@ -2,7 +2,7 @@<manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" package="org.tagspaces.mobile" xmlns:android="http://schemas.android.com/apk/res/android"><supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" /><uses-permission android:name="android.permission.INTERNET" />- <application android:hardwareAccelerated="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:supportsRtl="true">+ <application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true"><activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize"><intent-filter android:label="@string/launcher_name"><action android:name="android.intent.action.MAIN" />@@ -13,6 +13,9 @@<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/camera_provider_paths" /></provider></application>- <uses-sdk android:minSdkVersion="23" android:targetSdkVersion="27" />+ <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="27" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />+ <uses-permission android:name="android.permission.RECORD_AUDIO" />+ <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />+ <uses-permission android:name="android.permission.READ_PHONE_STATE" /></manifest>diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/AudioHandler.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/AudioHandler.javanew file mode 100644index 000000000..9e734c440--- /dev/null+++ b/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/AudioHandler.java@@ -0,0 +1,568 @@+/*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+*/+package org.apache.cordova.media;++import org.apache.cordova.CallbackContext;+import org.apache.cordova.CordovaPlugin;+import org.apache.cordova.CordovaResourceApi;+import org.apache.cordova.PermissionHelper;++import android.Manifest;+import android.content.Context;+import android.content.pm.PackageManager;+import android.media.AudioManager;+import android.media.AudioManager.OnAudioFocusChangeListener;+import android.net.Uri;+import android.os.Build;++import java.security.Permission;+import java.util.ArrayList;++import org.apache.cordova.LOG;+import org.apache.cordova.PluginResult;+import org.json.JSONArray;+import org.json.JSONException;+import org.json.JSONObject;++import java.util.HashMap;++/**+ * This class called by CordovaActivity to play and record audio.+ * The file can be local or over a network using http.+ *+ * Audio formats supported (tested):+ * .mp3, .wav+ *+ * Local audio files must reside in one of two places:+ * android_asset: file name must start with /android_asset/sound.mp3+ * sdcard: file name is just sound.mp3+ */+public class AudioHandler extends CordovaPlugin {++ public static String TAG = "AudioHandler";+ HashMap<String, AudioPlayer> players; // Audio player object+ ArrayList<AudioPlayer> pausedForPhone; // Audio players that were paused when phone call came in+ ArrayList<AudioPlayer> pausedForFocus; // Audio players that were paused when focus was lost+ private int origVolumeStream = -1;+ private CallbackContext messageChannel;+++ public static String [] permissions = { Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE};+ public static int RECORD_AUDIO = 0;+ public static int WRITE_EXTERNAL_STORAGE = 1;++ public static final int PERMISSION_DENIED_ERROR = 20;++ private String recordId;+ private String fileUriStr;++ /**+ * Constructor.+ */+ public AudioHandler() {+ this.players = new HashMap<String, AudioPlayer>();+ this.pausedForPhone = new ArrayList<AudioPlayer>();+ this.pausedForFocus = new ArrayList<AudioPlayer>();+ }+++ protected void getWritePermission(int requestCode)+ {+ PermissionHelper.requestPermission(this, requestCode, permissions[WRITE_EXTERNAL_STORAGE]);+ }+++ protected void getMicPermission(int requestCode)+ {+ PermissionHelper.requestPermission(this, requestCode, permissions[RECORD_AUDIO]);+ }+++ /**+ * Executes the request and returns PluginResult.+ * @param action The action to execute.+ * @param args JSONArry of arguments for the plugin.+ * @param callbackContext The callback context used when calling back into JavaScript.+ * @return A PluginResult object with a status and message.+ */+ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {+ CordovaResourceApi resourceApi = webView.getResourceApi();+ PluginResult.Status status = PluginResult.Status.OK;+ String result = "";++ if (action.equals("startRecordingAudio")) {+ recordId = args.getString(0);+ String target = args.getString(1);+ try {+ Uri targetUri = resourceApi.remapUri(Uri.parse(target));+ fileUriStr = targetUri.toString();+ } catch (IllegalArgumentException e) {+ fileUriStr = target;+ }+ promptForRecord();+ }+ else if (action.equals("stopRecordingAudio")) {+ this.stopRecordingAudio(args.getString(0), true);+ }+ else if (action.equals("pauseRecordingAudio")) {+ this.stopRecordingAudio(args.getString(0), false);+ }+ else if (action.equals("resumeRecordingAudio")) {+ this.resumeRecordingAudio(args.getString(0));+ }+ else if (action.equals("startPlayingAudio")) {+ String target = args.getString(1);+ String fileUriStr;+ try {+ Uri targetUri = resourceApi.remapUri(Uri.parse(target));+ fileUriStr = targetUri.toString();+ } catch (IllegalArgumentException e) {+ fileUriStr = target;+ }+ this.startPlayingAudio(args.getString(0), FileHelper.stripFileProtocol(fileUriStr));+ }+ else if (action.equals("seekToAudio")) {+ this.seekToAudio(args.getString(0), args.getInt(1));+ }+ else if (action.equals("pausePlayingAudio")) {+ this.pausePlayingAudio(args.getString(0));+ }+ else if (action.equals("stopPlayingAudio")) {+ this.stopPlayingAudio(args.getString(0));+ } else if (action.equals("setVolume")) {+ try {+ this.setVolume(args.getString(0), Float.parseFloat(args.getString(1)));+ } catch (NumberFormatException nfe) {+ //no-op+ }+ } else if (action.equals("getCurrentPositionAudio")) {+ float f = this.getCurrentPositionAudio(args.getString(0));+ callbackContext.sendPluginResult(new PluginResult(status, f));+ return true;+ }+ else if (action.equals("getDurationAudio")) {+ float f = this.getDurationAudio(args.getString(0), args.getString(1));+ callbackContext.sendPluginResult(new PluginResult(status, f));+ return true;+ }+ else if (action.equals("create")) {+ String id = args.getString(0);+ String src = FileHelper.stripFileProtocol(args.getString(1));+ getOrCreatePlayer(id, src);+ }+ else if (action.equals("release")) {+ boolean b = this.release(args.getString(0));+ callbackContext.sendPluginResult(new PluginResult(status, b));+ return true;+ }+ else if (action.equals("messageChannel")) {+ messageChannel = callbackContext;+ return true;+ } else if (action.equals("getCurrentAmplitudeAudio")) {+ float f = this.getCurrentAmplitudeAudio(args.getString(0));+ callbackContext.sendPluginResult(new PluginResult(status, f));+ return true;+ }+ else { // Unrecognized action.+ return false;+ }++ callbackContext.sendPluginResult(new PluginResult(status, result));++ return true;+ }++ /**+ * Stop all audio players and recorders.+ */+ public void onDestroy() {+ if (!players.isEmpty()) {+ onLastPlayerReleased();+ }+ for (AudioPlayer audio : this.players.values()) {+ audio.destroy();+ }+ this.players.clear();+ }++ /**+ * Stop all audio players and recorders on navigate.+ */+ @Override+ public void onReset() {+ onDestroy();+ }++ /**+ * Called when a message is sent to plugin.+ *+ * @param id The message id+ * @param data The message data+ * @return Object to stop propagation or null+ */+ public Object onMessage(String id, Object data) {++ // If phone message+ if (id.equals("telephone")) {++ // If phone ringing, then pause playing+ if ("ringing".equals(data) || "offhook".equals(data)) {++ // Get all audio players and pause them+ for (AudioPlayer audio : this.players.values()) {+ if (audio.getState() == AudioPlayer.STATE.MEDIA_RUNNING.ordinal()) {+ this.pausedForPhone.add(audio);+ audio.pausePlaying();+ }+ }++ }++ // If phone idle, then resume playing those players we paused+ else if ("idle".equals(data)) {+ for (AudioPlayer audio : this.pausedForPhone) {+ audio.startPlaying(null);+ }+ this.pausedForPhone.clear();+ }+ }+ return null;+ }++ //--------------------------------------------------------------------------+ // LOCAL METHODS+ //--------------------------------------------------------------------------++ private AudioPlayer getOrCreatePlayer(String id, String file) {+ AudioPlayer ret = players.get(id);+ if (ret == null) {+ if (players.isEmpty()) {+ onFirstPlayerCreated();+ }+ ret = new AudioPlayer(this, id, file);+ players.put(id, ret);+ }+ return ret;+ }++ /**+ * Release the audio player instance to save memory.+ * @param id The id of the audio player+ */+ private boolean release(String id) {+ AudioPlayer audio = players.remove(id);+ if (audio == null) {+ return false;+ }+ if (players.isEmpty()) {+ onLastPlayerReleased();+ }+ audio.destroy();+ return true;+ }++ /**+ * Start recording and save the specified file.+ * @param id The id of the audio player+ * @param file The name of the file+ */+ public void startRecordingAudio(String id, String file) {+ AudioPlayer audio = getOrCreatePlayer(id, file);+ audio.startRecording(file);+ }++ /**+ * Stop/Pause recording and save to the file specified when recording started.+ * @param id The id of the audio player+ * @param stop If true stop recording, if false pause recording+ */+ public void stopRecordingAudio(String id, boolean stop) {+ AudioPlayer audio = this.players.get(id);+ if (audio != null) {+ audio.stopRecording(stop);+ }+ }++ /**+ * Resume recording+ * @param id The id of the audio player+ */+ public void resumeRecordingAudio(String id) {+ AudioPlayer audio = players.get(id);+ if (audio != null) {+ audio.resumeRecording();+ }+ }++ /**+ * Start or resume playing audio file.+ * @param id The id of the audio player+ * @param file The name of the audio file.+ */+ public void startPlayingAudio(String id, String file) {+ AudioPlayer audio = getOrCreatePlayer(id, file);+ audio.startPlaying(file);+ getAudioFocus();+ }++ /**+ * Seek to a location.+ * @param id The id of the audio player+ * @param milliseconds int: number of milliseconds to skip 1000 = 1 second+ */+ public void seekToAudio(String id, int milliseconds) {+ AudioPlayer audio = this.players.get(id);+ if (audio != null) {+ audio.seekToPlaying(milliseconds);+ }+ }++ /**+ * Pause playing.+ * @param id The id of the audio player+ */+ public void pausePlayingAudio(String id) {+ AudioPlayer audio = this.players.get(id);+ if (audio != null) {+ audio.pausePlaying();+ }+ }++ /**+ * Stop playing the audio file.+ * @param id The id of the audio player+ */+ public void stopPlayingAudio(String id) {+ AudioPlayer audio = this.players.get(id);+ if (audio != null) {+ audio.stopPlaying();+ }+ }++ /**+ * Get current position of playback.+ * @param id The id of the audio player+ * @return position in msec+ */+ public float getCurrentPositionAudio(String id) {+ AudioPlayer audio = this.players.get(id);+ if (audio != null) {+ return (audio.getCurrentPosition() / 1000.0f);+ }+ return -1;+ }++ /**+ * Get the duration of the audio file.+ * @param id The id of the audio player+ * @param file The name of the audio file.+ * @return The duration in msec.+ */+ public float getDurationAudio(String id, String file) {+ AudioPlayer audio = getOrCreatePlayer(id, file);+ return audio.getDuration(file);+ }++ /**+ * Set the audio device to be used for playback.+ *+ * @param output 1=earpiece, 2=speaker+ */+ @SuppressWarnings("deprecation")+ public void setAudioOutputDevice(int output) {+ String TAG1 = "AudioHandler.setAudioOutputDevice(): Error : ";++ AudioManager audiMgr = (AudioManager) this.cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);+ if (output == 2) {+ audiMgr.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_SPEAKER, AudioManager.ROUTE_ALL);+ }+ else if (output == 1) {+ audiMgr.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);+ }+ else {+ LOG.e(TAG1," Unknown output device");+ }+ }++ public void pauseAllLostFocus() {+ for (AudioPlayer audio : this.players.values()) {+ if (audio.getState() == AudioPlayer.STATE.MEDIA_RUNNING.ordinal()) {+ this.pausedForFocus.add(audio);+ audio.pausePlaying();+ }+ }+ }++ public void resumeAllGainedFocus() {+ for (AudioPlayer audio : this.pausedForFocus) {+ audio.resumePlaying();+ }+ this.pausedForFocus.clear();+ }++ /**+ * Get the the audio focus+ */+ private OnAudioFocusChangeListener focusChangeListener = new OnAudioFocusChangeListener() {+ public void onAudioFocusChange(int focusChange) {+ switch (focusChange) {+ case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :+ case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :+ case (AudioManager.AUDIOFOCUS_LOSS) :+ pauseAllLostFocus();+ break;+ case (AudioManager.AUDIOFOCUS_GAIN):+ resumeAllGainedFocus();+ break;+ default:+ break;+ }+ }+ };++ public void getAudioFocus() {+ String TAG2 = "AudioHandler.getAudioFocus(): Error : ";++ AudioManager am = (AudioManager) this.cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);+ int result = am.requestAudioFocus(focusChangeListener,+ AudioManager.STREAM_MUSIC,+ AudioManager.AUDIOFOCUS_GAIN);++ if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {+ LOG.e(TAG2,result + " instead of " + AudioManager.AUDIOFOCUS_REQUEST_GRANTED);+ }++ }+++ /**+ * Get the audio device to be used for playback.+ *+ * @return 1=earpiece, 2=speaker+ */+ @SuppressWarnings("deprecation")+ public int getAudioOutputDevice() {+ AudioManager audiMgr = (AudioManager) this.cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);+ if (audiMgr.getRouting(AudioManager.MODE_NORMAL) == AudioManager.ROUTE_EARPIECE) {+ return 1;+ }+ else if (audiMgr.getRouting(AudioManager.MODE_NORMAL) == AudioManager.ROUTE_SPEAKER) {+ return 2;+ }+ else {+ return -1;+ }+ }++ /**+ * Set the volume for an audio device+ *+ * @param id The id of the audio player+ * @param volume Volume to adjust to 0.0f - 1.0f+ */+ public void setVolume(String id, float volume) {+ String TAG3 = "AudioHandler.setVolume(): Error : ";++ AudioPlayer audio = this.players.get(id);+ if (audio != null) {+ audio.setVolume(volume);+ } else {+ LOG.e(TAG3,"Unknown Audio Player " + id);+ }+ }++ private void onFirstPlayerCreated() {+ origVolumeStream = cordova.getActivity().getVolumeControlStream();+ cordova.getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);+ }++ private void onLastPlayerReleased() {+ if (origVolumeStream != -1) {+ cordova.getActivity().setVolumeControlStream(origVolumeStream);+ origVolumeStream = -1;+ }+ }++ void sendEventMessage(String action, JSONObject actionData) {+ JSONObject message = new JSONObject();+ try {+ message.put("action", action);+ if (actionData != null) {+ message.put(action, actionData);+ }+ } catch (JSONException e) {+ LOG.e(TAG, "Failed to create event message", e);+ }++ PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, message);+ pluginResult.setKeepCallback(true);+ if (messageChannel != null) {+ messageChannel.sendPluginResult(pluginResult);+ }+ }++ public void onRequestPermissionResult(int requestCode, String[] permissions,+ int[] grantResults) throws JSONException+ {+ for(int r:grantResults)+ {+ if(r == PackageManager.PERMISSION_DENIED)+ {+ this.messageChannel.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, PERMISSION_DENIED_ERROR));+ return;+ }+ }+ promptForRecord();+ }++ /*+ * This little utility method catch-all work great for multi-permission stuff.+ *+ */++ private void promptForRecord()+ {+ if(PermissionHelper.hasPermission(this, permissions[WRITE_EXTERNAL_STORAGE]) &&+ PermissionHelper.hasPermission(this, permissions[RECORD_AUDIO])) {+ this.startRecordingAudio(recordId, FileHelper.stripFileProtocol(fileUriStr));+ }+ else if(PermissionHelper.hasPermission(this, permissions[RECORD_AUDIO]))+ {+ getWritePermission(WRITE_EXTERNAL_STORAGE);+ }+ else+ {+ getMicPermission(RECORD_AUDIO);+ }++ }++ /**+ * Get current amplitude of recording.+ * @param id The id of the audio player+ * @return amplitude+ */+ public float getCurrentAmplitudeAudio(String id) {+ AudioPlayer audio = this.players.get(id);+ if (audio != null) {+ return (audio.getCurrentAmplitude());+ }+ return 0;+ }+}diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/AudioPlayer.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/AudioPlayer.javanew file mode 100644index 000000000..861421e72--- /dev/null+++ b/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/AudioPlayer.java@@ -0,0 +1,722 @@+/*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+*/+package org.apache.cordova.media;++import android.media.AudioManager;+import android.media.MediaPlayer;+import android.media.MediaPlayer.OnCompletionListener;+import android.media.MediaPlayer.OnErrorListener;+import android.media.MediaPlayer.OnPreparedListener;+import android.media.MediaRecorder;+import android.os.Environment;++import org.apache.cordova.LOG;++import org.json.JSONException;+import org.json.JSONObject;++import java.io.File;+import java.io.FileInputStream;+import java.io.FileOutputStream;+import java.io.InputStream;+import java.io.OutputStream;+import java.io.IOException;+import java.util.LinkedList;++/**+ * This class implements the audio playback and recording capabilities used by Cordova.+ * It is called by the AudioHandler Cordova class.+ * Only one file can be played or recorded per class instance.+ *+ * Local audio files must reside in one of two places:+ * android_asset: file name must start with /android_asset/sound.mp3+ * sdcard: file name is just sound.mp3+ */+public class AudioPlayer implements OnCompletionListener, OnPreparedListener, OnErrorListener {++ // AudioPlayer modes+ public enum MODE { NONE, PLAY, RECORD };++ // AudioPlayer states+ public enum STATE { MEDIA_NONE,+ MEDIA_STARTING,+ MEDIA_RUNNING,+ MEDIA_PAUSED,+ MEDIA_STOPPED,+ MEDIA_LOADING+ };++ private static final String LOG_TAG = "AudioPlayer";++ // AudioPlayer message ids+ private static int MEDIA_STATE = 1;+ private static int MEDIA_DURATION = 2;+ private static int MEDIA_POSITION = 3;+ private static int MEDIA_ERROR = 9;++ // Media error codes+ private static int MEDIA_ERR_NONE_ACTIVE = 0;+ private static int MEDIA_ERR_ABORTED = 1;+// private static int MEDIA_ERR_NETWORK = 2;+// private static int MEDIA_ERR_DECODE = 3;+// private static int MEDIA_ERR_NONE_SUPPORTED = 4;++ private AudioHandler handler; // The AudioHandler object+ private String id; // The id of this player (used to identify Media object in JavaScript)+ private MODE mode = MODE.NONE; // Playback or Recording mode+ private STATE state = STATE.MEDIA_NONE; // State of recording or playback++ private String audioFile = null; // File name to play or record to+ private float duration = -1; // Duration of audio++ private MediaRecorder recorder = null; // Audio recording object+ private LinkedList<String> tempFiles = null; // Temporary recording file name+ private String tempFile = null;++ private MediaPlayer player = null; // Audio player object+ private boolean prepareOnly = true; // playback after file prepare flag+ private int seekOnPrepared = 0; // seek to this location once media is prepared++ /**+ * Constructor.+ *+ * @param handler The audio handler object+ * @param id The id of this audio player+ */+ public AudioPlayer(AudioHandler handler, String id, String file) {+ this.handler = handler;+ this.id = id;+ this.audioFile = file;+ this.tempFiles = new LinkedList<String>();+ }++ private String generateTempFile() {+ String tempFileName = null;+ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {+ tempFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmprecording-" + System.currentTimeMillis() + ".3gp";+ } else {+ tempFileName = "/data/data/" + handler.cordova.getActivity().getPackageName() + "/cache/tmprecording-" + System.currentTimeMillis() + ".3gp";+ }+ return tempFileName;+ }++ /**+ * Destroy player and stop audio playing or recording.+ */+ public void destroy() {+ // Stop any play or record+ if (this.player != null) {+ if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {+ this.player.stop();+ this.setState(STATE.MEDIA_STOPPED);+ }+ this.player.release();+ this.player = null;+ }+ if (this.recorder != null) {+ this.stopRecording(true);+ this.recorder.release();+ this.recorder = null;+ }+ }++ /**+ * Start recording the specified file.+ *+ * @param file The name of the file+ */+ public void startRecording(String file) {+ switch (this.mode) {+ case PLAY:+ LOG.d(LOG_TAG, "AudioPlayer Error: Can't record in play mode.");+ sendErrorStatus(MEDIA_ERR_ABORTED);+ break;+ case NONE:+ this.audioFile = file;+ this.recorder = new MediaRecorder();+ this.recorder.setAudioSource(MediaRecorder.AudioSource.MIC);+ this.recorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS); // RAW_AMR);+ this.recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); //AMR_NB);+ this.tempFile = generateTempFile();+ this.recorder.setOutputFile(this.tempFile);+ try {+ this.recorder.prepare();+ this.recorder.start();+ this.setState(STATE.MEDIA_RUNNING);+ return;+ } catch (IllegalStateException e) {+ e.printStackTrace();+ } catch (IOException e) {+ e.printStackTrace();+ }++ sendErrorStatus(MEDIA_ERR_ABORTED);+ break;+ case RECORD:+ LOG.d(LOG_TAG, "AudioPlayer Error: Already recording.");+ sendErrorStatus(MEDIA_ERR_ABORTED);+ }+ }++ /**+ * Save temporary recorded file to specified name+ *+ * @param file+ */+ public void moveFile(String file) {+ /* this is a hack to save the file as the specified name */++ if (!file.startsWith("/")) {+ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {+ file = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + file;+ } else {+ file = "/data/data/" + handler.cordova.getActivity().getPackageName() + "/cache/" + file;+ }+ }++ int size = this.tempFiles.size();+ LOG.d(LOG_TAG, "size = " + size);++ // only one file so just copy it+ if (size == 1) {+ String logMsg = "renaming " + this.tempFile + " to " + file;+ LOG.d(LOG_TAG, logMsg);+ File f = new File(this.tempFile);+ if (!f.renameTo(new File(file))) LOG.e(LOG_TAG, "FAILED " + logMsg);+ }+ // more than one file so the user must have pause recording. We'll need to concat files.+ else {+ FileOutputStream outputStream = null;+ try {+ outputStream = new FileOutputStream(new File(file));+ FileInputStream inputStream = null;+ File inputFile = null;+ for (int i = 0; i < size; i++) {+ try {+ inputFile = new File(this.tempFiles.get(i));+ inputStream = new FileInputStream(inputFile);+ copy(inputStream, outputStream, (i>0));+ } catch(Exception e) {+ LOG.e(LOG_TAG, e.getLocalizedMessage(), e);+ } finally {+ if (inputStream != null) try {+ inputStream.close();+ inputFile.delete();+ inputFile = null;+ } catch (Exception e) {+ LOG.e(LOG_TAG, e.getLocalizedMessage(), e);+ }+ }+ }+ } catch(Exception e) {+ e.printStackTrace();+ } finally {+ if (outputStream != null) try {+ outputStream.close();+ } catch (Exception e) {+ LOG.e(LOG_TAG, e.getLocalizedMessage(), e);+ }+ }+ }+ }++ private static long copy(InputStream from, OutputStream to, boolean skipHeader)+ throws IOException {+ byte[] buf = new byte[8096];+ long total = 0;+ if (skipHeader) {+ from.skip(6);+ }+ while (true) {+ int r = from.read(buf);+ if (r == -1) {+ break;+ }+ to.write(buf, 0, r);+ total += r;+ }+ return total;+ }++ /**+ * Stop/Pause recording and save to the file specified when recording started.+ */+ public void stopRecording(boolean stop) {+ if (this.recorder != null) {+ try{+ if (this.state == STATE.MEDIA_RUNNING) {+ this.recorder.stop();+ }+ this.recorder.reset();+ if (!this.tempFiles.contains(this.tempFile)) {+ this.tempFiles.add(this.tempFile);+ }+ if (stop) {+ LOG.d(LOG_TAG, "stopping recording");+ this.setState(STATE.MEDIA_STOPPED);+ this.moveFile(this.audioFile);+ } else {+ LOG.d(LOG_TAG, "pause recording");+ this.setState(STATE.MEDIA_PAUSED);+ }+ }+ catch (Exception e) {+ e.printStackTrace();+ }+ }+ }++ /**+ * Resume recording and save to the file specified when recording started.+ */+ public void resumeRecording() {+ startRecording(this.audioFile);+ }++ //==========================================================================+ // Playback+ //==========================================================================++ /**+ * Start or resume playing audio file.+ *+ * @param file The name of the audio file.+ */+ public void startPlaying(String file) {+ if (this.readyPlayer(file) && this.player != null) {+ this.player.start();+ this.setState(STATE.MEDIA_RUNNING);+ this.seekOnPrepared = 0; //insures this is always reset+ } else {+ this.prepareOnly = false;+ }+ }++ /**+ * Seek or jump to a new time in the track.+ */+ public void seekToPlaying(int milliseconds) {+ if (this.readyPlayer(this.audioFile)) {+ if (milliseconds > 0) {+ this.player.seekTo(milliseconds);+ }+ LOG.d(LOG_TAG, "Send a onStatus update for the new seek");+ sendStatusChange(MEDIA_POSITION, null, (milliseconds / 1000.0f));+ }+ else {+ this.seekOnPrepared = milliseconds;+ }+ }++ /**+ * Pause playing.+ */+ public void pausePlaying() {++ // If playing, then pause+ if (this.state == STATE.MEDIA_RUNNING && this.player != null) {+ this.player.pause();+ this.setState(STATE.MEDIA_PAUSED);+ }+ else {+ LOG.d(LOG_TAG, "AudioPlayer Error: pausePlaying() called during invalid state: " + this.state.ordinal());+ sendErrorStatus(MEDIA_ERR_NONE_ACTIVE);+ }+ }++ /**+ * Stop playing the audio file.+ */+ public void stopPlaying() {+ if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {+ this.player.pause();+ this.player.seekTo(0);+ LOG.d(LOG_TAG, "stopPlaying is calling stopped");+ this.setState(STATE.MEDIA_STOPPED);+ }+ else {+ LOG.d(LOG_TAG, "AudioPlayer Error: stopPlaying() called during invalid state: " + this.state.ordinal());+ sendErrorStatus(MEDIA_ERR_NONE_ACTIVE);+ }+ }++ /**+ * Resume playing.+ */+ public void resumePlaying() {+ this.startPlaying(this.audioFile);+ }++ /**+ * Callback to be invoked when playback of a media source has completed.+ *+ * @param player The MediaPlayer that reached the end of the file+ */+ public void onCompletion(MediaPlayer player) {+ LOG.d(LOG_TAG, "on completion is calling stopped");+ this.setState(STATE.MEDIA_STOPPED);+ }++ /**+ * Get current position of playback.+ *+ * @return position in msec or -1 if not playing+ */+ public long getCurrentPosition() {+ if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {+ int curPos = this.player.getCurrentPosition();+ sendStatusChange(MEDIA_POSITION, null, (curPos / 1000.0f));+ return curPos;+ }+ else {+ return -1;+ }+ }++ /**+ * Determine if playback file is streaming or local.+ * It is streaming if file name starts with "http://"+ *+ * @param file The file name+ * @return T=streaming, F=local+ */+ public boolean isStreaming(String file) {+ if (file.contains("http://") || file.contains("https://") || file.contains("rtsp://")) {+ return true;+ }+ else {+ return false;+ }+ }++ /**+ * Get the duration of the audio file.+ *+ * @param file The name of the audio file.+ * @return The duration in msec.+ * -1=can't be determined+ * -2=not allowed+ */+ public float getDuration(String file) {++ // Can't get duration of recording+ if (this.recorder != null) {+ return (-2); // not allowed+ }++ // If audio file already loaded and started, then return duration+ if (this.player != null) {+ return this.duration;+ }++ // If no player yet, then create one+ else {+ this.prepareOnly = true;+ this.startPlaying(file);++ // This will only return value for local, since streaming+ // file hasn't been read yet.+ return this.duration;+ }+ }++ /**+ * Callback to be invoked when the media source is ready for playback.+ *+ * @param player The MediaPlayer that is ready for playback+ */+ public void onPrepared(MediaPlayer player) {+ // Listen for playback completion+ this.player.setOnCompletionListener(this);+ // seek to any location received while not prepared+ this.seekToPlaying(this.seekOnPrepared);+ // If start playing after prepared+ if (!this.prepareOnly) {+ this.player.start();+ this.setState(STATE.MEDIA_RUNNING);+ this.seekOnPrepared = 0; //reset only when played+ } else {+ this.setState(STATE.MEDIA_STARTING);+ }+ // Save off duration+ this.duration = getDurationInSeconds();+ // reset prepare only flag+ this.prepareOnly = true;++ // Send status notification to JavaScript+ sendStatusChange(MEDIA_DURATION, null, this.duration);+ }++ /**+ * By default Android returns the length of audio in mills but we want seconds+ *+ * @return length of clip in seconds+ */+ private float getDurationInSeconds() {+ return (this.player.getDuration() / 1000.0f);+ }++ /**+ * Callback to be invoked when there has been an error during an asynchronous operation+ * (other errors will throw exceptions at method call time).+ *+ * @param player the MediaPlayer the error pertains to+ * @param arg1 the type of error that has occurred: (MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_SERVER_DIED)+ * @param arg2 an extra code, specific to the error.+ */+ public boolean onError(MediaPlayer player, int arg1, int arg2) {+ LOG.d(LOG_TAG, "AudioPlayer.onError(" + arg1 + ", " + arg2 + ")");++ // we don't want to send success callback+ // so we don't call setState() here+ this.state = STATE.MEDIA_STOPPED;+ this.destroy();+ // Send error notification to JavaScript+ sendErrorStatus(arg1);++ return false;+ }++ /**+ * Set the state and send it to JavaScript.+ *+ * @param state+ */+ private void setState(STATE state) {+ if (this.state != state) {+ sendStatusChange(MEDIA_STATE, null, (float)state.ordinal());+ }+ this.state = state;+ }++ /**+ * Set the mode and send it to JavaScript.+ *+ * @param mode+ */+ private void setMode(MODE mode) {+ if (this.mode != mode) {+ //mode is not part of the expected behavior, so no notification+ //this.handler.webView.sendJavascript("cordova.require('cordova-plugin-media.Media').onStatus('" + this.id + "', " + MEDIA_STATE + ", " + mode + ");");+ }+ this.mode = mode;+ }++ /**+ * Get the audio state.+ *+ * @return int+ */+ public int getState() {+ return this.state.ordinal();+ }++ /**+ * Set the volume for audio player+ *+ * @param volume+ */+ public void setVolume(float volume) {+ if (this.player != null) {+ this.player.setVolume(volume, volume);+ } else {+ LOG.d(LOG_TAG, "AudioPlayer Error: Cannot set volume until the audio file is initialized.");+ sendErrorStatus(MEDIA_ERR_NONE_ACTIVE);+ }+ }++ /**+ * attempts to put the player in play mode+ * @return true if in playmode, false otherwise+ */+ private boolean playMode() {+ switch(this.mode) {+ case NONE:+ this.setMode(MODE.PLAY);+ break;+ case PLAY:+ break;+ case RECORD:+ LOG.d(LOG_TAG, "AudioPlayer Error: Can't play in record mode.");+ sendErrorStatus(MEDIA_ERR_ABORTED);+ return false; //player is not ready+ }+ return true;+ }++ /**+ * attempts to initialize the media player for playback+ * @param file the file to play+ * @return false if player not ready, reports if in wrong mode or state+ */+ private boolean readyPlayer(String file) {+ if (playMode()) {+ switch (this.state) {+ case MEDIA_NONE:+ if (this.player == null) {+ this.player = new MediaPlayer();+ this.player.setOnErrorListener(this);+ }+ try {+ this.loadAudioFile(file);+ } catch (Exception e) {+ sendErrorStatus(MEDIA_ERR_ABORTED);+ }+ return false;+ case MEDIA_LOADING:+ //cordova js is not aware of MEDIA_LOADING, so we send MEDIA_STARTING instead+ LOG.d(LOG_TAG, "AudioPlayer Loading: startPlaying() called during media preparation: " + STATE.MEDIA_STARTING.ordinal());+ this.prepareOnly = false;+ return false;+ case MEDIA_STARTING:+ case MEDIA_RUNNING:+ case MEDIA_PAUSED:+ return true;+ case MEDIA_STOPPED:+ //if we are readying the same file+ if (file!=null && this.audioFile.compareTo(file) == 0) {+ //maybe it was recording?+ if (player == null) {+ this.player = new MediaPlayer();+ this.player.setOnErrorListener(this);+ this.prepareOnly = false;++ try {+ this.loadAudioFile(file);+ } catch (Exception e) {+ sendErrorStatus(MEDIA_ERR_ABORTED);+ }+ return false;//we´re not ready yet+ }+ else {+ //reset the audio file+ player.seekTo(0);+ player.pause();+ return true;+ }+ } else {+ //reset the player+ this.player.reset();+ try {+ this.loadAudioFile(file);+ } catch (Exception e) {+ sendErrorStatus(MEDIA_ERR_ABORTED);+ }+ //if we had to prepare the file, we won't be in the correct state for playback+ return false;+ }+ default:+ LOG.d(LOG_TAG, "AudioPlayer Error: startPlaying() called during invalid state: " + this.state);+ sendErrorStatus(MEDIA_ERR_ABORTED);+ }+ }+ return false;+ }++ /**+ * load audio file+ * @throws IOException+ * @throws IllegalStateException+ * @throws SecurityException+ * @throws IllegalArgumentException+ */+ private void loadAudioFile(String file) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {+ if (this.isStreaming(file)) {+ this.player.setDataSource(file);+ this.player.setAudioStreamType(AudioManager.STREAM_MUSIC);+ //if it's a streaming file, play mode is implied+ this.setMode(MODE.PLAY);+ this.setState(STATE.MEDIA_STARTING);+ this.player.setOnPreparedListener(this);+ this.player.prepareAsync();+ }+ else {+ if (file.startsWith("/android_asset/")) {+ String f = file.substring(15);+ android.content.res.AssetFileDescriptor fd = this.handler.cordova.getActivity().getAssets().openFd(f);+ this.player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());+ }+ else {+ File fp = new File(file);+ if (fp.exists()) {+ FileInputStream fileInputStream = new FileInputStream(file);+ this.player.setDataSource(fileInputStream.getFD());+ fileInputStream.close();+ }+ else {+ this.player.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/" + file);+ }+ }+ this.setState(STATE.MEDIA_STARTING);+ this.player.setOnPreparedListener(this);+ this.player.prepare();++ // Get duration+ this.duration = getDurationInSeconds();+ }+ }++ private void sendErrorStatus(int errorCode) {+ sendStatusChange(MEDIA_ERROR, errorCode, null);+ }++ private void sendStatusChange(int messageType, Integer additionalCode, Float value) {++ if (additionalCode != null && value != null) {+ throw new IllegalArgumentException("Only one of additionalCode or value can be specified, not both");+ }++ JSONObject statusDetails = new JSONObject();+ try {+ statusDetails.put("id", this.id);+ statusDetails.put("msgType", messageType);+ if (additionalCode != null) {+ JSONObject code = new JSONObject();+ code.put("code", additionalCode.intValue());+ statusDetails.put("value", code);+ }+ else if (value != null) {+ statusDetails.put("value", value.floatValue());+ }+ } catch (JSONException e) {+ LOG.e(LOG_TAG, "Failed to create status details", e);+ }++ this.handler.sendEventMessage("status", statusDetails);+ }++ /**+ * Get current amplitude of recording.+ *+ * @return amplitude or 0 if not recording+ */+ public float getCurrentAmplitude() {+ if (this.recorder != null) {+ try{+ if (this.state == STATE.MEDIA_RUNNING) {+ return (float) this.recorder.getMaxAmplitude() / 32762;+ }+ }+ catch (Exception e) {+ e.printStackTrace();+ }+ }+ return 0;+ }+}diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/FileHelper.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/FileHelper.javanew file mode 100644index 000000000..e20752c62--- /dev/null+++ b/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/FileHelper.java@@ -0,0 +1,38 @@+/*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+ */+package org.apache.cordova.media;++import android.net.Uri;++public class FileHelper {++ /**+ * Removes the "file://" prefix from the given URI string, if applicable.+ * If the given URI string doesn't have a "file://" prefix, it is returned unchanged.+ *+ * @param uriString the URI string to operate on+ * @return a path without the "file://" prefix+ */+ public static String stripFileProtocol(String uriString) {+ if (uriString.startsWith("file://")) {+ return Uri.parse(uriString).getPath();+ }+ return uriString;+ }+}diff --git a/cordova/platforms/android/app/src/main/res/drawable-hdpi/ic_border_color_black_48dp.png b/cordova/platforms/android/app/src/main/res/drawable-hdpi/ic_border_color_black_48dp.pngdeleted file mode 100644index 537f8bbfd..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-hdpi/ic_border_color_black_48dp.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-hdpi/ic_camera_alt_black_48dp.png b/cordova/platforms/android/app/src/main/res/drawable-hdpi/ic_camera_alt_black_48dp.pngdeleted file mode 100644index 6125fa2b7..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-hdpi/ic_camera_alt_black_48dp.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-hdpi/ic_launcher.png b/cordova/platforms/android/app/src/main/res/drawable-hdpi/ic_launcher.pngdeleted file mode 100644index bdc0f0b5b..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-hdpi/ic_launcher.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-hdpi/ic_receipt_black_48dp.png b/cordova/platforms/android/app/src/main/res/drawable-hdpi/ic_receipt_black_48dp.pngdeleted file mode 100644index 7e5e93b6b..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-hdpi/ic_receipt_black_48dp.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-hdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-hdpi/screen.pngnew file mode 100644index 000000000..2d564f49cBinary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-land-hdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-ldpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-ldpi/screen.pngnew file mode 100644index 000000000..c7eae7edeBinary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-land-ldpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-mdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-mdpi/screen.pngnew file mode 100644index 000000000..3bf1ec2e9Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-land-mdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-xhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-xhdpi/screen.pngnew file mode 100644index 000000000..987a92462Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-land-xhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-xxhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-xxhdpi/screen.pngnew file mode 100644index 000000000..ef9fc7400Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-land-xxhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-xxxhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-xxxhdpi/screen.pngnew file mode 100644index 000000000..8f9a458e1Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-land-xxxhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-ldpi/ic_launcher.png b/cordova/platforms/android/app/src/main/res/drawable-ldpi/ic_launcher.pngdeleted file mode 100644index aef9d514a..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-ldpi/ic_launcher.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-mdpi/ic_border_color_black_48dp.png b/cordova/platforms/android/app/src/main/res/drawable-mdpi/ic_border_color_black_48dp.pngdeleted file mode 100644index b86c1adbe..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-mdpi/ic_border_color_black_48dp.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-mdpi/ic_camera_alt_black_48dp.png b/cordova/platforms/android/app/src/main/res/drawable-mdpi/ic_camera_alt_black_48dp.pngdeleted file mode 100644index d83d658d0..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-mdpi/ic_camera_alt_black_48dp.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-mdpi/ic_launcher.png b/cordova/platforms/android/app/src/main/res/drawable-mdpi/ic_launcher.pngdeleted file mode 100644index d82586967..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-mdpi/ic_launcher.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-mdpi/ic_receipt_black_48dp.png b/cordova/platforms/android/app/src/main/res/drawable-mdpi/ic_receipt_black_48dp.pngdeleted file mode 100644index de0f06a6b..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-mdpi/ic_receipt_black_48dp.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-hdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-hdpi/screen.pngnew file mode 100644index 000000000..5875561d3Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-port-hdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-ldpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-ldpi/screen.pngnew file mode 100644index 000000000..725420620Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-port-ldpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-mdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-mdpi/screen.pngnew file mode 100644index 000000000..9034b68fdBinary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-port-mdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-xhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-xhdpi/screen.pngnew file mode 100644index 000000000..95dc8d849Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-port-xhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-xxhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-xxhdpi/screen.pngnew file mode 100644index 000000000..9b6bfe4a8Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-port-xxhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-xxxhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-xxxhdpi/screen.pngnew file mode 100644index 000000000..ec655cde1Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-port-xxxhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-xhdpi/ic_border_color_black_48dp.png b/cordova/platforms/android/app/src/main/res/drawable-xhdpi/ic_border_color_black_48dp.pngdeleted file mode 100644index 051cd3d61..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-xhdpi/ic_border_color_black_48dp.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-xhdpi/ic_camera_alt_black_48dp.png b/cordova/platforms/android/app/src/main/res/drawable-xhdpi/ic_camera_alt_black_48dp.pngdeleted file mode 100644index 6df33edd6..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-xhdpi/ic_camera_alt_black_48dp.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-xhdpi/ic_launcher.png b/cordova/platforms/android/app/src/main/res/drawable-xhdpi/ic_launcher.pngdeleted file mode 100644index d8beacdcd..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-xhdpi/ic_launcher.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-xhdpi/ic_receipt_black_48dp.png b/cordova/platforms/android/app/src/main/res/drawable-xhdpi/ic_receipt_black_48dp.pngdeleted file mode 100644index c7bc3f42a..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-xhdpi/ic_receipt_black_48dp.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-xxhdpi/ic_border_color_black_48dp.png b/cordova/platforms/android/app/src/main/res/drawable-xxhdpi/ic_border_color_black_48dp.pngdeleted file mode 100644index 42da34f16..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-xxhdpi/ic_border_color_black_48dp.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-xxhdpi/ic_camera_alt_black_48dp.png b/cordova/platforms/android/app/src/main/res/drawable-xxhdpi/ic_camera_alt_black_48dp.pngdeleted file mode 100644index d9d2e3c24..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-xxhdpi/ic_camera_alt_black_48dp.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-xxhdpi/ic_launcher.png b/cordova/platforms/android/app/src/main/res/drawable-xxhdpi/ic_launcher.pngdeleted file mode 100644index 3071a36b9..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-xxhdpi/ic_launcher.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-xxhdpi/ic_receipt_black_48dp.png b/cordova/platforms/android/app/src/main/res/drawable-xxhdpi/ic_receipt_black_48dp.pngdeleted file mode 100644index 794452dc0..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-xxhdpi/ic_receipt_black_48dp.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_border_color_black_48dp.png b/cordova/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_border_color_black_48dp.pngdeleted file mode 100644index 301671c22..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_border_color_black_48dp.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_camera_alt_black_48dp.png b/cordova/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_camera_alt_black_48dp.pngdeleted file mode 100644index 021d1d582..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_camera_alt_black_48dp.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_launcher.png b/cordova/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_launcher.pngdeleted file mode 100644index 6bc2234a6..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_launcher.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_receipt_black_48dp.png b/cordova/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_receipt_black_48dp.pngdeleted file mode 100644index 56917b2ef..000000000Binary files a/cordova/platforms/android/app/src/main/res/drawable-xxxhdpi/ic_receipt_black_48dp.png and /dev/null differdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-hdpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-hdpi/icon.pngnew file mode 100644index 000000000..538426124Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/mipmap-hdpi/icon.png differdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-ldpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-ldpi/icon.pngnew file mode 100644index 000000000..c5fcaeb64Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/mipmap-ldpi/icon.png differdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-mdpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-mdpi/icon.pngnew file mode 100644index 000000000..a18167be1Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/mipmap-mdpi/icon.png differdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-xhdpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-xhdpi/icon.pngnew file mode 100644index 000000000..9e3eec364Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/mipmap-xhdpi/icon.png differdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-xxhdpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-xxhdpi/icon.pngnew file mode 100644index 000000000..a56928965Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/mipmap-xxhdpi/icon.png differdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-xxxhdpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-xxxhdpi/icon.pngnew file mode 100644index 000000000..3c322f2eaBinary files /dev/null and b/cordova/platforms/android/app/src/main/res/mipmap-xxxhdpi/icon.png differdiff --git a/cordova/platforms/android/app/src/main/res/xml/config.xml b/cordova/platforms/android/app/src/main/res/xml/config.xmlindex 61a3b1bcf..4fe3a337a 100644--- a/cordova/platforms/android/app/src/main/res/xml/config.xml+++ b/cordova/platforms/android/app/src/main/res/xml/config.xml@@ -11,6 +11,9 @@<param name="onload" value="true" /></feature><allow-navigation href="cdvfile:*" />+ <feature name="Media">+ <param name="android-package" value="org.apache.cordova.media.AudioHandler" />+ </feature><feature name="Whitelist"><param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin" /><param name="onload" value="true" />diff --git a/cordova/platforms/android/build.gradle b/cordova/platforms/android/build.gradleindex fb40bb660..569004f45 100644--- a/cordova/platforms/android/build.gradle+++ b/cordova/platforms/android/build.gradle@@ -20,30 +20,32 @@buildscript {repositories {- google()+ maven {+ url "https://maven.google.com"+ }jcenter()}-dependencies {+// NOTE: Do not place your application dependencies here; they belong// in the individual module build.gradle files-- classpath 'com.android.tools.build:gradle:3.2.0'+ classpath 'com.android.tools.build:gradle:3.0.1'}}allprojects {repositories {- google()+ maven {+ url "https://maven.google.com"+ }jcenter()}-//This replaces project.properties w.r.t. build settingsproject.ext {- defaultBuildToolsVersion="28.0.3" //String+ defaultBuildToolsVersion="27.0.1" //StringdefaultMinSdkVersion=19 //Integer - Minimum requirement is Android 4.4- defaultTargetSdkVersion=28 //Integer - We ALWAYS target the latest by default- defaultCompileSdkVersion=28 //Integer - We ALWAYS compile with the latest by default+ defaultTargetSdkVersion=27 //Integer - We ALWAYS target the latest by default+ defaultCompileSdkVersion=27 //Integer - We ALWAYS compile with the latest by default}}diff --git a/cordova/platforms/android/cordova/Api.js b/cordova/platforms/android/cordova/Api.jsindex be6b76b99..ae4d17bdd 100644--- a/cordova/platforms/android/cordova/Api.js+++ b/cordova/platforms/android/cordova/Api.js@@ -21,6 +21,7 @@ var path = require('path');var Q = require('q');var AndroidProject = require('./lib/AndroidProject');+var AndroidStudio = require('./lib/AndroidStudio');var PluginManager = require('cordova-common').PluginManager;var CordovaLogger = require('cordova-common').CordovaLogger;@@ -55,27 +56,41 @@ function setupEvents (externalEventEmitter) {function Api (platform, platformRootDir, events) {this.platform = PLATFORM;this.root = path.resolve(__dirname, '..');+ this.builder = 'gradle';setupEvents(events);- const appMain = path.join(this.root, 'app', 'src', 'main');- const appRes = path.join(appMain, 'res');+ var self = this;this.locations = {- root: this.root,- www: path.join(appMain, 'assets', 'www'),- res: appRes,- platformWww: path.join(this.root, 'platform_www'),- configXml: path.join(appRes, 'xml', 'config.xml'),- defaultConfigXml: path.join(this.root, 'cordova', 'defaults.xml'),- strings: path.join(appRes, 'values', 'strings.xml'),- manifest: path.join(appMain, 'AndroidManifest.xml'),- build: path.join(this.root, 'build'),- javaSrc: path.join(appMain, 'java'),+ root: self.root,+ www: path.join(self.root, 'assets/www'),+ res: path.join(self.root, 'res'),+ platformWww: path.join(self.root, 'platform_www'),+ configXml: path.join(self.root, 'res/xml/config.xml'),+ defaultConfigXml: path.join(self.root, 'cordova/defaults.xml'),+ strings: path.join(self.root, 'res/values/strings.xml'),+ manifest: path.join(self.root, 'AndroidManifest.xml'),+ build: path.join(self.root, 'build'),+ javaSrc: path.join(self.root, 'src'),// NOTE: Due to platformApi spec we need to return relative paths herecordovaJs: 'bin/templates/project/assets/www/cordova.js',cordovaJsSrc: 'cordova-js-src'};++ // XXX Override some locations for Android Studio projects+ if (AndroidStudio.isAndroidStudioProject(self.root) === true) {+ selfEvents.emit('log', 'Android Studio project detected');+ this.builder = 'studio';+ this.android_studio = true;+ this.locations.configXml = path.join(self.root, 'app/src/main/res/xml/config.xml');+ this.locations.strings = path.join(self.root, 'app/src/main/res/values/strings.xml');+ this.locations.manifest = path.join(self.root, 'app/src/main/AndroidManifest.xml');+ // We could have Java Source, we could have other languages+ this.locations.javaSrc = path.join(self.root, 'app/src/main/java/');+ this.locations.www = path.join(self.root, 'app/src/main/assets/www');+ this.locations.res = path.join(self.root, 'app/src/main/res');+ }}/**@@ -208,13 +223,33 @@ Api.prototype.addPlugin = function (plugin, installOptions) {installOptions.variables.PACKAGE_NAME = project.getPackageName();}+ if (this.android_studio === true) {+ installOptions.android_studio = true;+ }+return Q().then(function () {+ // CB-11964: Do a clean when installing the plugin code to get around+ // the Gradle bug introduced by the Android Gradle Plugin Version 2.2+ // TODO: Delete when the next version of Android Gradle plugin comes out+ // Since clean doesn't just clean the build, it also wipes out www, we need+ // to pass additional options.++ // Do some basic argument parsing+ var opts = {};++ // Skip cleaning prepared files when not invoking via cordova CLI.+ opts.noPrepare = true;++ if (!AndroidStudio.isAndroidStudioProject(self.root) && !project.isClean()) {+ return self.clean(opts);+ }+ }).then(function () {return PluginManager.get(self.platform, self.locations, project).addPlugin(plugin, installOptions);}).then(function () {if (plugin.getFrameworks(this.platform).length === 0) return;selfEvents.emit('verbose', 'Updating build files since android plugin contained <framework>');// This should pick the correct builder, not just get gradle- require('./lib/builders/builders').getBuilder().prepBuildFiles();+ require('./lib/builders/builders').getBuilder(this.builder).prepBuildFiles();}.bind(this))// CB-11022 Return truthy value to prevent running prepare after.thenResolve(true);@@ -236,8 +271,9 @@ Api.prototype.addPlugin = function (plugin, installOptions) {Api.prototype.removePlugin = function (plugin, uninstallOptions) {var project = AndroidProject.getProjectFile(this.root);- if (uninstallOptions && uninstallOptions.usePlatformWww === true) {+ if (uninstallOptions && uninstallOptions.usePlatformWww === true && this.android_studio === true) {uninstallOptions.usePlatformWww = false;+ uninstallOptions.android_studio = true;}return PluginManager.get(this.platform, this.locations, project)@@ -246,7 +282,7 @@ Api.prototype.removePlugin = function (plugin, uninstallOptions) {if (plugin.getFrameworks(this.platform).length === 0) return;selfEvents.emit('verbose', 'Updating build files since android plugin contained <framework>');- require('./lib/builders/builders').getBuilder().prepBuildFiles();+ require('./lib/builders/builders').getBuilder(this.builder).prepBuildFiles();}.bind(this))// CB-11022 Return truthy value to prevent running prepare after.thenResolve(true);@@ -299,7 +335,9 @@ Api.prototype.removePlugin = function (plugin, uninstallOptions) {*/Api.prototype.build = function (buildOptions) {var self = this;-+ if (this.android_studio) {+ buildOptions.studio = true;+ }return require('./lib/check_reqs').run().then(function () {return require('./lib/build').run.call(self, buildOptions);}).then(function (buildResults) {@@ -343,9 +381,12 @@ Api.prototype.run = function (runOptions) {*/Api.prototype.clean = function (cleanOptions) {var self = this;- // This will lint, checking for null won't- if (typeof cleanOptions === 'undefined') {- cleanOptions = {};+ if (this.android_studio) {+ // This will lint, checking for null won't+ if (typeof cleanOptions === 'undefined') {+ cleanOptions = {};+ }+ cleanOptions.studio = true;}return require('./lib/check_reqs').run().then(function () {diff --git a/cordova/platforms/android/cordova/android_sdk_version b/cordova/platforms/android/cordova/android_sdk_versionindex c4082f1f9..34ed28fea 100755--- a/cordova/platforms/android/cordova/android_sdk_version+++ b/cordova/platforms/android/cordova/android_sdk_version@@ -21,7 +21,9 @@var android_sdk = require('./lib/android_sdk');-android_sdk.print_newest_available_sdk_target().done(null, function (err) {+android_sdk.print_newest_available_sdk_target().done(null, function(err) {console.error(err);process.exit(2);});++diff --git a/cordova/platforms/android/cordova/build b/cordova/platforms/android/cordova/buildindex 69f7b3ae0..222e84a06 100755--- a/cordova/platforms/android/cordova/build+++ b/cordova/platforms/android/cordova/build@@ -19,25 +19,24 @@under the License.*/-var args = process.argv;+var args = process.argv;var Api = require('./Api');var nopt = require('nopt');var path = require('path');// Support basic help commands-if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(args[2]) >= 0) {+if(['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >= 0)require('./lib/build').help();-}// Do some basic argument parsingvar buildOpts = nopt({- 'verbose': Boolean,- 'silent': Boolean,- 'debug': Boolean,- 'release': Boolean,+ 'verbose' : Boolean,+ 'silent' : Boolean,+ 'debug' : Boolean,+ 'release' : Boolean,'nobuild': Boolean,- 'buildConfig': path-}, { 'd': '--verbose' });+ 'buildConfig' : path+}, { 'd' : '--verbose' });// Make buildOptions compatible with PlatformApi build method specbuildOpts.argv = buildOpts.argv.original;@@ -45,7 +44,7 @@ buildOpts.argv = buildOpts.argv.original;require('./loggingHelper').adjustLoggerLevel(buildOpts);new Api().build(buildOpts)-.catch(function (err) {+.catch(function(err) {console.error(err.stack);process.exit(2);});diff --git a/cordova/platforms/android/cordova/check_reqs b/cordova/platforms/android/cordova/check_reqsindex e0c1c444f..372a3830a 100755--- a/cordova/platforms/android/cordova/check_reqs+++ b/cordova/platforms/android/cordova/check_reqs@@ -22,10 +22,9 @@var check_reqs = require('./lib/check_reqs');check_reqs.run().done(- function success () {+ function success() {console.log('Looks like your environment fully supports cordova-android development!');- },- function fail (err) {+ }, function fail(err) {console.log(err);process.exit(2);}diff --git a/cordova/platforms/android/cordova/clean b/cordova/platforms/android/cordova/cleanindex d3e6da1e3..22065cc54 100755--- a/cordova/platforms/android/cordova/clean+++ b/cordova/platforms/android/cordova/clean@@ -20,11 +20,11 @@*/var Api = require('./Api');-var path = require('path');+var path = require('path');var nopt = require('nopt');// Support basic help commands-if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >= 0) {+if(['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >= 0) {console.log('Usage: ' + path.relative(process.cwd(), process.argv[1]));console.log('Cleans the project directory.');process.exit(0);@@ -32,9 +32,9 @@ if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >=// Do some basic argument parsingvar opts = nopt({- 'verbose': Boolean,- 'silent': Boolean-}, { 'd': '--verbose' });+ 'verbose' : Boolean,+ 'silent' : Boolean+}, { 'd' : '--verbose' });// Make buildOptions compatible with PlatformApi clean method specopts.argv = opts.argv.original;@@ -45,7 +45,7 @@ opts.noPrepare = true;require('./loggingHelper').adjustLoggerLevel(opts);new Api().clean(opts)-.catch(function (err) {+.catch(function(err) {console.error(err.stack);process.exit(2);});diff --git a/cordova/platforms/android/cordova/lib/AndroidManifest.js b/cordova/platforms/android/cordova/lib/AndroidManifest.jsindex 98f820266..5b7077ae5 100644--- a/cordova/platforms/android/cordova/lib/AndroidManifest.js+++ b/cordova/platforms/android/cordova/lib/AndroidManifest.js@@ -51,11 +51,15 @@ AndroidManifest.prototype.setVersionCode = function (versionCode) {};AndroidManifest.prototype.getPackageId = function () {+ /* jshint -W069 */return this.doc.getroot().attrib['package'];+ /* jshint +W069 */};AndroidManifest.prototype.setPackageId = function (pkgId) {+ /* jshint -W069 */this.doc.getroot().attrib['package'] = pkgId;+ /* jshint +W069 */return this;};diff --git a/cordova/platforms/android/cordova/lib/AndroidProject.js b/cordova/platforms/android/cordova/lib/AndroidProject.jsindex 3c2586a32..bf55cad1c 100644--- a/cordova/platforms/android/cordova/lib/AndroidProject.js+++ b/cordova/platforms/android/cordova/lib/AndroidProject.js@@ -21,6 +21,7 @@ var fs = require('fs');var path = require('path');var properties_parser = require('properties-parser');var AndroidManifest = require('./AndroidManifest');+var AndroidStudio = require('./AndroidStudio');var pluginHandlers = require('./pluginHandlers');var projectFileCache = {};@@ -61,7 +62,10 @@ function AndroidProject (projectDir) {this._dirty = false;this.projectDir = projectDir;this.platformWww = path.join(this.projectDir, 'platform_www');- this.www = path.join(this.projectDir, 'app/src/main/assets/www');+ this.www = path.join(this.projectDir, 'assets/www');+ if (AndroidStudio.isAndroidStudioProject(projectDir) === true) {+ this.www = path.join(this.projectDir, 'app/src/main/assets/www');+ }}AndroidProject.getProjectFile = function (projectDir) {@@ -88,7 +92,10 @@ AndroidProject.purgeCache = function (projectDir) {* @return {String} The name of the package*/AndroidProject.prototype.getPackageName = function () {- var manifestPath = path.join(this.projectDir, 'app/src/main/AndroidManifest.xml');+ var manifestPath = path.join(this.projectDir, 'AndroidManifest.xml');+ if (AndroidStudio.isAndroidStudioProject(this.projectDir) === true) {+ manifestPath = path.join(this.projectDir, 'app/src/main/AndroidManifest.xml');+ }return new AndroidManifest(manifestPath).getPackageId();};diff --git a/cordova/platforms/android/cordova/lib/AndroidStudio.js b/cordova/platforms/android/cordova/lib/AndroidStudio.jsnew file mode 100644index 000000000..68d4d8f6c--- /dev/null+++ b/cordova/platforms/android/cordova/lib/AndroidStudio.js@@ -0,0 +1,11 @@+/*+ * This is a simple routine that checks if project is an Android Studio Project+ *+ * @param {String} root Root folder of the project+ */++/* jshint esnext: false */++module.exports.isAndroidStudioProject = function isAndroidStudioProject (root) {+ return true;+};diff --git a/cordova/platforms/android/cordova/lib/android_sdk.js b/cordova/platforms/android/cordova/lib/android_sdk.jsindex 1c0ab204c..148f9f3db 100755--- a/cordova/platforms/android/cordova/lib/android_sdk.js+++ b/cordova/platforms/android/cordova/lib/android_sdk.js@@ -17,6 +17,7 @@under the License.*/+var Q = require('q');var superspawn = require('cordova-common').superspawn;var suffix_number_regex = /(\d+)$/;@@ -94,7 +95,7 @@ module.exports.list_targets = function () {} else throw err;}).then(function (targets) {if (targets.length === 0) {- return Promise.reject(new Error('No android targets (SDKs) installed!'));+ return Q.reject(new Error('No android targets (SDKs) installed!'));}return targets;});diff --git a/cordova/platforms/android/cordova/lib/build.js b/cordova/platforms/android/cordova/lib/build.jsindex 2f0ba690e..e33cfae08 100644--- a/cordova/platforms/android/cordova/lib/build.js+++ b/cordova/platforms/android/cordova/lib/build.js@@ -31,10 +31,11 @@ var events = require('cordova-common').events;var spawn = require('cordova-common').superspawn.spawn;var CordovaError = require('cordova-common').CordovaError;-module.exports.parseBuildOptions = parseOpts;function parseOpts (options, resolvedTarget, projectRoot) {options = options || {};options.argv = nopt({+ gradle: Boolean,+ studio: Boolean,prepenv: Boolean,versionCode: String,minSdkVersion: String,@@ -49,13 +50,26 @@ function parseOpts (options, resolvedTarget, projectRoot) {// Android Studio Build method is the defaultvar ret = {buildType: options.release ? 'release' : 'debug',+ buildMethod: process.env.ANDROID_BUILD || 'studio',prepEnv: options.argv.prepenv,arch: resolvedTarget && resolvedTarget.arch,extraArgs: []};+ if (options.argv.gradle || options.argv.studio) {+ ret.buildMethod = options.argv.studio ? 'studio' : 'gradle';+ }++ // This comes from cordova/run+ if (options.studio) ret.buildMethod = 'studio';+ if (options.gradle) ret.buildMethod = 'gradle';++ if (options.nobuild) ret.buildMethod = 'none';+if (options.argv.versionCode) { ret.extraArgs.push('-PcdvVersionCode=' + options.argv.versionCode); }+if (options.argv.minSdkVersion) { ret.extraArgs.push('-PcdvMinSdkVersion=' + options.argv.minSdkVersion); }+if (options.argv.gradleArg) {ret.extraArgs = ret.extraArgs.concat(options.argv.gradleArg);}@@ -115,8 +129,7 @@ function parseOpts (options, resolvedTarget, projectRoot) {*/module.exports.runClean = function (options) {var opts = parseOpts(options, null, this.root);- var builder = builders.getBuilder();-+ var builder = builders.getBuilder(opts.buildMethod);return builder.prepEnv(opts).then(function () {return builder.clean(opts);});@@ -136,8 +149,8 @@ module.exports.runClean = function (options) {*/module.exports.run = function (options, optResolvedTarget) {var opts = parseOpts(options, optResolvedTarget, this.root);- var builder = builders.getBuilder();-+ console.log(opts.buildMethod);+ var builder = builders.getBuilder(opts.buildMethod);return builder.prepEnv(opts).then(function () {if (opts.prepEnv) {events.emit('verbose', 'Build file successfully prepared.');@@ -148,7 +161,8 @@ module.exports.run = function (options, optResolvedTarget) {events.emit('log', 'Built the following apk(s): \n\t' + apkPaths.join('\n\t'));return {apkPaths: apkPaths,- buildType: opts.buildType+ buildType: opts.buildType,+ buildMethod: opts.buildMethod};});});@@ -262,10 +276,12 @@ module.exports.help = function () {console.log('Flags:');console.log(' \'--debug\': will build project in debug mode (default)');console.log(' \'--release\': will build project for release');+ console.log(' \'--ant\': will build project with ant');+ console.log(' \'--gradle\': will build project with gradle (default)');console.log(' \'--nobuild\': will skip build process (useful when using run command)');console.log(' \'--prepenv\': don\'t build, but copy in build scripts where necessary');- console.log(' \'--versionCode=#\': Override versionCode for this build. Useful for uploading multiple APKs.');- console.log(' \'--minSdkVersion=#\': Override minSdkVersion for this build. Useful for uploading multiple APKs.');+ console.log(' \'--versionCode=#\': Override versionCode for this build. Useful for uploading multiple APKs. Requires --gradle.');+ console.log(' \'--minSdkVersion=#\': Override minSdkVersion for this build. Useful for uploading multiple APKs. Requires --gradle.');console.log(' \'--gradleArg=<gradle command line arg>\': Extra args to pass to the gradle command. Use one flag per arg. Ex. --gradleArg=-PcdvBuildMultipleApks=true');console.log('');console.log('Signed APK flags (overwrites debug/release-signing.proprties) :');diff --git a/cordova/platforms/android/cordova/lib/builders/GenericBuilder.js b/cordova/platforms/android/cordova/lib/builders/GenericBuilder.jsnew file mode 100644index 000000000..892aa38f4--- /dev/null+++ b/cordova/platforms/android/cordova/lib/builders/GenericBuilder.js@@ -0,0 +1,124 @@+/*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+*/+/* eslint no-self-assign: 0 */+/* eslint no-unused-vars: 0 */++var Q = require('q');+var fs = require('fs');+var path = require('path');+var shell = require('shelljs');+var events = require('cordova-common').events;++function GenericBuilder (projectDir) {+ this.root = projectDir || path.resolve(__dirname, '../../..');+ this.binDirs = {+ studio: path.join(this.root, 'app', 'build', 'outputs', 'apk'),+ gradle: path.join(this.root, 'build', 'outputs', 'apk')+ };+}++GenericBuilder.prototype.prepEnv = function () {+ return Q();+};++GenericBuilder.prototype.build = function () {+ events.emit('log', 'Skipping build...');+ return Q(null);+};++GenericBuilder.prototype.clean = function () {+ return Q();+};++GenericBuilder.prototype.findOutputApks = function (build_type, arch) {+ var self = this;+ return Object.keys(this.binDirs).reduce(function (result, builderName) {+ var binDir = self.binDirs[builderName];+ return result.concat(findOutputApksHelper(binDir, build_type, builderName === 'ant' ? null : arch));+ }, []).sort(apkSorter);+};++module.exports = GenericBuilder;++function apkSorter (fileA, fileB) {+ // De-prioritize arch specific builds+ var archSpecificRE = /-x86|-arm/;+ if (archSpecificRE.exec(fileA)) {+ return 1;+ } else if (archSpecificRE.exec(fileB)) {+ return -1;+ }++ // De-prioritize unsigned builds+ var unsignedRE = /-unsigned/;+ if (unsignedRE.exec(fileA)) {+ return 1;+ } else if (unsignedRE.exec(fileB)) {+ return -1;+ }++ var timeDiff = fs.statSync(fileB).mtime - fs.statSync(fileA).mtime;+ return timeDiff === 0 ? fileA.length - fileB.length : timeDiff;+}++function findOutputApksHelper (dir, build_type, arch) {+ var shellSilent = shell.config.silent;+ shell.config.silent = true;++ // list directory recursively+ var ret = shell.ls('-R', dir).map(function (file) {+ // ls does not include base directory+ return path.join(dir, file);+ }).filter(function (file) {+ // find all APKs+ return file.match(/\.apk?$/i);+ }).filter(function (candidate) {+ var apkName = path.basename(candidate);+ // Need to choose between release and debug .apk.+ if (build_type === 'debug') {+ return /-debug/.exec(apkName) && !/-unaligned|-unsigned/.exec(apkName);+ }+ if (build_type === 'release') {+ return /-release/.exec(apkName) && !/-unaligned/.exec(apkName);+ }+ return true;+ }).sort(apkSorter);++ shellSilent = shellSilent;++ if (ret.length === 0) {+ return ret;+ }+ // Assume arch-specific build if newest apk has -x86 or -arm.+ var archSpecific = !!/-x86|-arm/.exec(path.basename(ret[0]));+ // And show only arch-specific ones (or non-arch-specific)+ ret = ret.filter(function (p) {+ /* jshint -W018 */+ return !!/-x86|-arm/.exec(path.basename(p)) === archSpecific;+ /* jshint +W018 */+ });++ if (archSpecific && ret.length > 1 && arch) {+ ret = ret.filter(function (p) {+ return path.basename(p).indexOf('-' + arch) !== -1;+ });+ }++ return ret;+}diff --git a/cordova/platforms/android/cordova/lib/builders/GradleBuilder.js b/cordova/platforms/android/cordova/lib/builders/GradleBuilder.jsnew file mode 100644index 000000000..b955db18b--- /dev/null+++ b/cordova/platforms/android/cordova/lib/builders/GradleBuilder.js@@ -0,0 +1,331 @@+/*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+*/++var Q = require('q');+var fs = require('fs');+var util = require('util');+var path = require('path');+var shell = require('shelljs');+var superspawn = require('cordova-common').superspawn;+var CordovaError = require('cordova-common').CordovaError;+var events = require('cordova-common').events;+var check_reqs = require('../check_reqs');++var GenericBuilder = require('./GenericBuilder');++var MARKER = 'YOUR CHANGES WILL BE ERASED!';+var SIGNING_PROPERTIES = '-signing.properties';+var TEMPLATE =+ '# This file is automatically generated.\n' ++ '# Do not modify this file -- ' + MARKER + '\n';++function GradleBuilder (projectRoot) {+ GenericBuilder.call(this, projectRoot);++ this.binDirs = { gradle: this.binDirs.gradle };+}++util.inherits(GradleBuilder, GenericBuilder);++GradleBuilder.prototype.getArgs = function (cmd, opts) {+ if (cmd === 'release') {+ cmd = 'cdvBuildRelease';+ } else if (cmd === 'debug') {+ cmd = 'cdvBuildDebug';+ }+ var args = [cmd, '-b', path.join(this.root, 'build.gradle')];+ if (opts.arch) {+ args.push('-PcdvBuildArch=' + opts.arch);+ }++ // 10 seconds -> 6 seconds+ args.push('-Dorg.gradle.daemon=true');+ // to allow dex in process+ args.push('-Dorg.gradle.jvmargs=-Xmx2048m');+ // allow NDK to be used - required by Gradle 1.5 plugin+ args.push('-Pandroid.useDeprecatedNdk=true');+ args.push.apply(args, opts.extraArgs);+ // Shaves another 100ms, but produces a "try at own risk" warning. Not worth it (yet):+ // args.push('-Dorg.gradle.parallel=true');+ return args;+};++/*+ * This returns a promise+ */++GradleBuilder.prototype.runGradleWrapper = function (gradle_cmd, gradle_file) {+ var gradlePath = path.join(this.root, 'gradlew');+ gradle_file = path.join(this.root, (gradle_file || 'wrapper.gradle'));+ if (fs.existsSync(gradlePath)) {+ // Literally do nothing, for some reason this works, while !fs.existsSync didn't on Windows+ } else {+ return superspawn.spawn(gradle_cmd, ['-p', this.root, 'wrapper', '-b', gradle_file], { stdio: 'pipe' })+ .progress(function (stdio) {+ suppressJavaOptionsInfo(stdio);+ });+ }+};++/*+ * We need to kill this in a fire.+ */++GradleBuilder.prototype.readProjectProperties = function () {+ function findAllUniq (data, r) {+ var s = {};+ var m;+ while ((m = r.exec(data))) {+ s[m[1]] = 1;+ }+ return Object.keys(s);+ }++ var data = fs.readFileSync(path.join(this.root, 'project.properties'), 'utf8');+ return {+ libs: findAllUniq(data, /^\s*android\.library\.reference\.\d+=(.*)(?:\s|$)/mg),+ gradleIncludes: findAllUniq(data, /^\s*cordova\.gradle\.include\.\d+=(.*)(?:\s|$)/mg),+ systemLibs: findAllUniq(data, /^\s*cordova\.system\.library\.\d+=(.*)(?:\s|$)/mg)+ };+};++GradleBuilder.prototype.extractRealProjectNameFromManifest = function () {+ var manifestPath = path.join(this.root, 'AndroidManifest.xml');+ var manifestData = fs.readFileSync(manifestPath, 'utf8');+ var m = /<manifest[\s\S]*?package\s*=\s*"(.*?)"/i.exec(manifestData);+ if (!m) {+ throw new CordovaError('Could not find package name in ' + manifestPath);+ }++ var packageName = m[1];+ var lastDotIndex = packageName.lastIndexOf('.');+ return packageName.substring(lastDotIndex + 1);+};++// Makes the project buildable, minus the gradle wrapper.+GradleBuilder.prototype.prepBuildFiles = function () {+ // Update the version of build.gradle in each dependent library.+ var pluginBuildGradle = path.join(this.root, 'cordova', 'lib', 'plugin-build.gradle');+ var propertiesObj = this.readProjectProperties();+ var subProjects = propertiesObj.libs;++ // Check and copy the gradle file into the subproject.+ // Called by the loop below this function def.+ var checkAndCopy = function (subProject, root) {+ var subProjectGradle = path.join(root, subProject, 'build.gradle');+ // This is the future-proof way of checking if a file exists+ // This must be synchronous to satisfy a Travis test+ try {+ fs.accessSync(subProjectGradle, fs.F_OK);+ } catch (e) {+ shell.cp('-f', pluginBuildGradle, subProjectGradle);+ }+ };++ // Some dependencies on Android don't use gradle, or don't have default+ // gradle files. This copies a dummy gradle file into them+ for (var i = 0; i < subProjects.length; ++i) {+ if (subProjects[i] !== 'CordovaLib' && subProjects[i] !== 'app') {+ checkAndCopy(subProjects[i], this.root);+ }+ }++ var name = this.extractRealProjectNameFromManifest();+ // Remove the proj.id/name- prefix from projects: https://issues.apache.org/jira/browse/CB-9149+ var settingsGradlePaths = subProjects.map(function (p) {+ var realDir = p.replace(/[/\\]/g, ':');+ var libName = realDir.replace(name + '-', '');+ var str = 'include ":' + libName + '"\n';+ if (realDir.indexOf(name + '-') !== -1) { str += 'project(":' + libName + '").projectDir = new File("' + p + '")\n'; }+ return str;+ });++ // Write the settings.gradle file.+ fs.writeFileSync(path.join(this.root, 'settings.gradle'),+ '// GENERATED FILE - DO NOT EDIT\n' ++ 'include ":"\n' + settingsGradlePaths.join(''));+ // Update dependencies within build.gradle.+ var buildGradle = fs.readFileSync(path.join(this.root, 'build.gradle'), 'utf8');+ var depsList = '';+ var root = this.root;++ // Cordova Plugins can be written as library modules that would use Cordova as a+ // dependency. Because we need to make sure that Cordova is compiled only once for+ // dexing, we make sure to exclude CordovaLib from these modules+ var insertExclude = function (p) {+ var gradlePath = path.join(root, p, 'build.gradle');+ var projectGradleFile = fs.readFileSync(gradlePath, 'utf-8');+ if (projectGradleFile.indexOf('CordovaLib') !== -1) {+ depsList += '{\n exclude module:("CordovaLib")\n }\n';+ } else {+ depsList += '\n';+ }+ };++ subProjects.forEach(function (p) {+ events.emit('log', 'Subproject Path: ' + p);+ var libName = p.replace(/[/\\]/g, ':').replace(name + '-', '');+ depsList += ' implementation(project(path: "' + libName + '"))';+ insertExclude(p);+ });++ // For why we do this mapping: https://issues.apache.org/jira/browse/CB-8390+ var SYSTEM_LIBRARY_MAPPINGS = [+ [/^\/?extras\/android\/support\/(.*)$/, 'com.android.support:support-$1:+'],+ [/^\/?google\/google_play_services\/libproject\/google-play-services_lib\/?$/, 'com.google.android.gms:play-services:+']+ ];+ propertiesObj.systemLibs.forEach(function (p) {+ var mavenRef;+ // It's already in gradle form if it has two ':'s+ if (/:.*:/.exec(p)) {+ mavenRef = p;+ } else {+ for (var i = 0; i < SYSTEM_LIBRARY_MAPPINGS.length; ++i) {+ var pair = SYSTEM_LIBRARY_MAPPINGS[i];+ if (pair[0].exec(p)) {+ mavenRef = p.replace(pair[0], pair[1]);+ break;+ }+ }+ if (!mavenRef) {+ throw new CordovaError('Unsupported system library (does not work with gradle): ' + p);+ }+ }+ depsList += ' compile "' + mavenRef + '"\n';+ });++ // This code is dangerous and actually writes gradle declarations directly into the build.gradle+ // Try not to mess with this if possible+ buildGradle = buildGradle.replace(/(SUB-PROJECT DEPENDENCIES START)[\s\S]*(\/\/ SUB-PROJECT DEPENDENCIES END)/, '$1\n' + depsList + ' $2');+ var includeList = '';+ propertiesObj.gradleIncludes.forEach(function (includePath) {+ includeList += 'apply from: "' + includePath + '"\n';+ });+ buildGradle = buildGradle.replace(/(PLUGIN GRADLE EXTENSIONS START)[\s\S]*(\/\/ PLUGIN GRADLE EXTENSIONS END)/, '$1\n' + includeList + '$2');+ fs.writeFileSync(path.join(this.root, 'build.gradle'), buildGradle);+};++GradleBuilder.prototype.prepEnv = function (opts) {+ var self = this;+ return check_reqs.check_gradle().then(function (gradlePath) {+ return self.runGradleWrapper(gradlePath);+ }).then(function () {+ return self.prepBuildFiles();+ }).then(function () {+ // We now copy the gradle out of the framework+ // This is a dirty patch to get the build working+ /*+ var wrapperDir = path.join(self.root, 'CordovaLib');+ if (process.platform == 'win32') {+ shell.rm('-f', path.join(self.root, 'gradlew.bat'));+ shell.cp(path.join(wrapperDir, 'gradlew.bat'), self.root);+ } else {+ shell.rm('-f', path.join(self.root, 'gradlew'));+ shell.cp(path.join(wrapperDir, 'gradlew'), self.root);+ }+ shell.rm('-rf', path.join(self.root, 'gradle', 'wrapper'));+ shell.mkdir('-p', path.join(self.root, 'gradle'));+ shell.cp('-r', path.join(wrapperDir, 'gradle', 'wrapper'), path.join(self.root, 'gradle'));+*/+ // If the gradle distribution URL is set, make sure it points to version we want.+ // If it's not set, do nothing, assuming that we're using a future version of gradle that we don't want to mess with.+ // For some reason, using ^ and $ don't work. This does the job, though.+ var distributionUrlRegex = /distributionUrl.*zip/;+ /* jshint -W069 */+ var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'https\\://services.gradle.org/distributions/gradle-4.1-all.zip';+ /* jshint +W069 */+ var gradleWrapperPropertiesPath = path.join(self.root, 'gradle', 'wrapper', 'gradle-wrapper.properties');+ shell.chmod('u+w', gradleWrapperPropertiesPath);+ shell.sed('-i', distributionUrlRegex, 'distributionUrl=' + distributionUrl, gradleWrapperPropertiesPath);++ var propertiesFile = opts.buildType + SIGNING_PROPERTIES;+ var propertiesFilePath = path.join(self.root, propertiesFile);+ if (opts.packageInfo) {+ fs.writeFileSync(propertiesFilePath, TEMPLATE + opts.packageInfo.toProperties());+ } else if (isAutoGenerated(propertiesFilePath)) {+ shell.rm('-f', propertiesFilePath);+ }+ });+};++/*+ * Builds the project with gradle.+ * Returns a promise.+ */+GradleBuilder.prototype.build = function (opts) {+ var wrapper = path.join(this.root, 'gradlew');+ var args = this.getArgs(opts.buildType === 'debug' ? 'debug' : 'release', opts);++ return superspawn.spawn(wrapper, args, { stdio: 'pipe' })+ .progress(function (stdio) {+ suppressJavaOptionsInfo(stdio);+ }).catch(function (error) {+ if (error.toString().indexOf('failed to find target with hash string') >= 0) {+ return check_reqs.check_android_target(error).then(function () {+ // If due to some odd reason - check_android_target succeeds+ // we should still fail here.+ return Q.reject(error);+ });+ }+ return Q.reject(error);+ });+};++GradleBuilder.prototype.clean = function (opts) {+ var builder = this;+ var wrapper = path.join(this.root, 'gradlew');+ var args = builder.getArgs('clean', opts);+ return Q().then(function () {+ return superspawn.spawn(wrapper, args, { stdio: 'inherit' });+ }).then(function () {+ shell.rm('-rf', path.join(builder.root, 'out'));++ ['debug', 'release'].forEach(function (config) {+ var propertiesFilePath = path.join(builder.root, config + SIGNING_PROPERTIES);+ if (isAutoGenerated(propertiesFilePath)) {+ shell.rm('-f', propertiesFilePath);+ }+ });+ });+};++module.exports = GradleBuilder;++function suppressJavaOptionsInfo (stdio) {+ if (stdio.stderr) {+ /*+ * Workaround for the issue with Java printing some unwanted information to+ * stderr instead of stdout.+ * This function suppresses 'Picked up _JAVA_OPTIONS' message from being+ * printed to stderr. See https://issues.apache.org/jira/browse/CB-9971 for+ * explanation.+ */+ var suppressThisLine = /^Picked up _JAVA_OPTIONS: /i.test(stdio.stderr.toString());+ if (suppressThisLine) {+ return;+ }+ process.stderr.write(stdio.stderr);+ } else {+ process.stdout.write(stdio.stdout);+ }+}++function isAutoGenerated (file) {+ return fs.existsSync(file) && fs.readFileSync(file, 'utf8').indexOf(MARKER) > 0;+}diff --git a/cordova/platforms/android/cordova/lib/builders/ProjectBuilder.js b/cordova/platforms/android/cordova/lib/builders/ProjectBuilder.jsdeleted file mode 100644index c5ad00d34..000000000--- a/cordova/platforms/android/cordova/lib/builders/ProjectBuilder.js+++ /dev/null@@ -1,370 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.-*/-/* eslint no-self-assign: 0 */-/* eslint no-unused-vars: 0 */--var Q = require('q');-var fs = require('fs');-var path = require('path');-var shell = require('shelljs');-var spawn = require('cordova-common').superspawn.spawn;-var events = require('cordova-common').events;-var CordovaError = require('cordova-common').CordovaError;-var check_reqs = require('../check_reqs');--const MARKER = 'YOUR CHANGES WILL BE ERASED!';-const SIGNING_PROPERTIES = '-signing.properties';-const TEMPLATE =- '# This file is automatically generated.\n' +- '# Do not modify this file -- ' + MARKER + '\n';--class ProjectBuilder {- constructor (rootDirectory) {- this.root = rootDirectory || path.resolve(__dirname, '../../..');- this.binDir = path.join(this.root, 'app', 'build', 'outputs', 'apk');- }-- getArgs (cmd, opts) {- if (cmd === 'release') {- cmd = 'cdvBuildRelease';- } else if (cmd === 'debug') {- cmd = 'cdvBuildDebug';- }-- let args = [cmd, '-b', path.join(this.root, 'build.gradle')];-- if (opts.arch) {- args.push('-PcdvBuildArch=' + opts.arch);- }-- args.push.apply(args, opts.extraArgs);-- return args;- }-- /*- * This returns a promise- */- runGradleWrapper (gradle_cmd) {- var gradlePath = path.join(this.root, 'gradlew');- var wrapperGradle = path.join(this.root, 'wrapper.gradle');- if (fs.existsSync(gradlePath)) {- // Literally do nothing, for some reason this works, while !fs.existsSync didn't on Windows- } else {- return spawn(gradle_cmd, ['-p', this.root, 'wrapper', '-b', wrapperGradle], { stdio: 'inherit' });- }- }-- readProjectProperties () {- function findAllUniq (data, r) {- var s = {};- var m;- while ((m = r.exec(data))) {- s[m[1]] = 1;- }- return Object.keys(s);- }-- var data = fs.readFileSync(path.join(this.root, 'project.properties'), 'utf8');- return {- libs: findAllUniq(data, /^\s*android\.library\.reference\.\d+=(.*)(?:\s|$)/mg),- gradleIncludes: findAllUniq(data, /^\s*cordova\.gradle\.include\.\d+=(.*)(?:\s|$)/mg),- systemLibs: findAllUniq(data, /^\s*cordova\.system\.library\.\d+=(.*)(?:\s|$)/mg)- };- }-- extractRealProjectNameFromManifest () {- var manifestPath = path.join(this.root, 'app', 'src', 'main', 'AndroidManifest.xml');- var manifestData = fs.readFileSync(manifestPath, 'utf8');- var m = /<manifest[\s\S]*?package\s*=\s*"(.*?)"/i.exec(manifestData);- if (!m) {- throw new CordovaError('Could not find package name in ' + manifestPath);- }-- var packageName = m[1];- var lastDotIndex = packageName.lastIndexOf('.');- return packageName.substring(lastDotIndex + 1);- }-- // Makes the project buildable, minus the gradle wrapper.- prepBuildFiles () {- // Update the version of build.gradle in each dependent library.- var pluginBuildGradle = path.join(this.root, 'cordova', 'lib', 'plugin-build.gradle');- var propertiesObj = this.readProjectProperties();- var subProjects = propertiesObj.libs;-- // Check and copy the gradle file into the subproject- // Called by the loop before this function def-- var checkAndCopy = function (subProject, root) {- var subProjectGradle = path.join(root, subProject, 'build.gradle');- // This is the future-proof way of checking if a file exists- // This must be synchronous to satisfy a Travis test- try {- fs.accessSync(subProjectGradle, fs.F_OK);- } catch (e) {- shell.cp('-f', pluginBuildGradle, subProjectGradle);- }- };-- for (var i = 0; i < subProjects.length; ++i) {- if (subProjects[i] !== 'CordovaLib') {- checkAndCopy(subProjects[i], this.root);- }- }- var name = this.extractRealProjectNameFromManifest();- // Remove the proj.id/name- prefix from projects: https://issues.apache.org/jira/browse/CB-9149- var settingsGradlePaths = subProjects.map(function (p) {- var realDir = p.replace(/[/\\]/g, ':');- var libName = realDir.replace(name + '-', '');- var str = 'include ":' + libName + '"\n';- if (realDir.indexOf(name + '-') !== -1) {- str += 'project(":' + libName + '").projectDir = new File("' + p + '")\n';- }- return str;- });-- fs.writeFileSync(path.join(this.root, 'settings.gradle'),- '// GENERATED FILE - DO NOT EDIT\n' +- 'include ":"\n' + settingsGradlePaths.join(''));-- // Update dependencies within build.gradle.- var buildGradle = fs.readFileSync(path.join(this.root, 'app', 'build.gradle'), 'utf8');- var depsList = '';- var root = this.root;- var insertExclude = function (p) {- var gradlePath = path.join(root, p, 'build.gradle');- var projectGradleFile = fs.readFileSync(gradlePath, 'utf-8');- if (projectGradleFile.indexOf('CordovaLib') !== -1) {- depsList += '{\n exclude module:("CordovaLib")\n }\n';- } else {- depsList += '\n';- }- };- subProjects.forEach(function (p) {- events.emit('log', 'Subproject Path: ' + p);- var libName = p.replace(/[/\\]/g, ':').replace(name + '-', '');- if (libName !== 'app') {- depsList += ' implementation(project(path: ":' + libName + '"))';- insertExclude(p);- }- });- // For why we do this mapping: https://issues.apache.org/jira/browse/CB-8390- var SYSTEM_LIBRARY_MAPPINGS = [- [/^\/?extras\/android\/support\/(.*)$/, 'com.android.support:support-$1:+'],- [/^\/?google\/google_play_services\/libproject\/google-play-services_lib\/?$/, 'com.google.android.gms:play-services:+']- ];-- propertiesObj.systemLibs.forEach(function (p) {- var mavenRef;- // It's already in gradle form if it has two ':'s- if (/:.*:/.exec(p)) {- mavenRef = p;- } else {- for (var i = 0; i < SYSTEM_LIBRARY_MAPPINGS.length; ++i) {- var pair = SYSTEM_LIBRARY_MAPPINGS[i];- if (pair[0].exec(p)) {- mavenRef = p.replace(pair[0], pair[1]);- break;- }- }- if (!mavenRef) {- throw new CordovaError('Unsupported system library (does not work with gradle): ' + p);- }- }- depsList += ' implementation "' + mavenRef + '"\n';- });-- buildGradle = buildGradle.replace(/(SUB-PROJECT DEPENDENCIES START)[\s\S]*(\/\/ SUB-PROJECT DEPENDENCIES END)/, '$1\n' + depsList + ' $2');- var includeList = '';-- propertiesObj.gradleIncludes.forEach(function (includePath) {- includeList += 'apply from: "../' + includePath + '"\n';- });- buildGradle = buildGradle.replace(/(PLUGIN GRADLE EXTENSIONS START)[\s\S]*(\/\/ PLUGIN GRADLE EXTENSIONS END)/, '$1\n' + includeList + '$2');- // This needs to be stored in the app gradle, not the root grade- fs.writeFileSync(path.join(this.root, 'app', 'build.gradle'), buildGradle);- }-- prepEnv (opts) {- var self = this;- return check_reqs.check_gradle()- .then(function (gradlePath) {- return self.runGradleWrapper(gradlePath);- }).then(function () {- return self.prepBuildFiles();- }).then(function () {- // If the gradle distribution URL is set, make sure it points to version we want.- // If it's not set, do nothing, assuming that we're using a future version of gradle that we don't want to mess with.- // For some reason, using ^ and $ don't work. This does the job, though.- var distributionUrlRegex = /distributionUrl.*zip/;- var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'https\\://services.gradle.org/distributions/gradle-4.6-all.zip';- var gradleWrapperPropertiesPath = path.join(self.root, 'gradle', 'wrapper', 'gradle-wrapper.properties');- shell.chmod('u+w', gradleWrapperPropertiesPath);- shell.sed('-i', distributionUrlRegex, 'distributionUrl=' + distributionUrl, gradleWrapperPropertiesPath);-- var propertiesFile = opts.buildType + SIGNING_PROPERTIES;- var propertiesFilePath = path.join(self.root, propertiesFile);- if (opts.packageInfo) {- fs.writeFileSync(propertiesFilePath, TEMPLATE + opts.packageInfo.toProperties());- } else if (isAutoGenerated(propertiesFilePath)) {- shell.rm('-f', propertiesFilePath);- }- });- }-- /*- * Builds the project with gradle.- * Returns a promise.- */- build (opts) {- var wrapper = path.join(this.root, 'gradlew');- var args = this.getArgs(opts.buildType === 'debug' ? 'debug' : 'release', opts);-- return spawn(wrapper, args, { stdio: 'pipe' })- .progress(function (stdio) {- if (stdio.stderr) {- /*- * Workaround for the issue with Java printing some unwanted information to- * stderr instead of stdout.- * This function suppresses 'Picked up _JAVA_OPTIONS' message from being- * printed to stderr. See https://issues.apache.org/jira/browse/CB-9971 for- * explanation.- */- var suppressThisLine = /^Picked up _JAVA_OPTIONS: /i.test(stdio.stderr.toString());- if (suppressThisLine) {- return;- }- process.stderr.write(stdio.stderr);- } else {- process.stdout.write(stdio.stdout);- }- }).catch(function (error) {- if (error.toString().indexOf('failed to find target with hash string') >= 0) {- return check_reqs.check_android_target(error).then(function () {- // If due to some odd reason - check_android_target succeeds- // we should still fail here.- return Q.reject(error);- });- }- return Q.reject(error);- });- }-- clean (opts) {- var builder = this;- var wrapper = path.join(this.root, 'gradlew');- var args = builder.getArgs('clean', opts);- return Q().then(function () {- return spawn(wrapper, args, { stdio: 'inherit' });- })- .then(function () {- shell.rm('-rf', path.join(builder.root, 'out'));-- ['debug', 'release'].forEach(function (config) {- var propertiesFilePath = path.join(builder.root, config + SIGNING_PROPERTIES);- if (isAutoGenerated(propertiesFilePath)) {- shell.rm('-f', propertiesFilePath);- }- });- });- }-- findOutputApks (build_type, arch) {- return findOutputApksHelper(this.binDir, build_type, arch).sort(apkSorter);- }-- fetchBuildResults (build_type, arch) {- return {- apkPaths: this.findOutputApks(build_type, arch),- buildType: build_type- };- }-}--module.exports = ProjectBuilder;--function apkSorter (fileA, fileB) {- // De-prioritize arch specific builds- var archSpecificRE = /-x86|-arm/;- if (archSpecificRE.exec(fileA)) {- return 1;- } else if (archSpecificRE.exec(fileB)) {- return -1;- }-- // De-prioritize unsigned builds- var unsignedRE = /-unsigned/;- if (unsignedRE.exec(fileA)) {- return 1;- } else if (unsignedRE.exec(fileB)) {- return -1;- }-- var timeDiff = fs.statSync(fileB).mtime - fs.statSync(fileA).mtime;- return timeDiff === 0 ? fileA.length - fileB.length : timeDiff;-}--function findOutputApksHelper (dir, build_type, arch) {- var shellSilent = shell.config.silent;- shell.config.silent = true;-- // list directory recursively- var ret = shell.ls('-R', dir).map(function (file) {- // ls does not include base directory- return path.join(dir, file);- }).filter(function (file) {- // find all APKs- return file.match(/\.apk?$/i);- }).filter(function (candidate) {- var apkName = path.basename(candidate);- // Need to choose between release and debug .apk.- if (build_type === 'debug') {- return /-debug/.exec(apkName) && !/-unaligned|-unsigned/.exec(apkName);- }- if (build_type === 'release') {- return /-release/.exec(apkName) && !/-unaligned/.exec(apkName);- }- return true;- }).sort(apkSorter);-- shellSilent = shellSilent;-- if (ret.length === 0) {- return ret;- }- // Assume arch-specific build if newest apk has -x86 or -arm.- var archSpecific = !!/-x86|-arm/.exec(path.basename(ret[0]));- // And show only arch-specific ones (or non-arch-specific)- ret = ret.filter(function (p) {- return !!/-x86|-arm/.exec(path.basename(p)) === archSpecific;- });-- if (archSpecific && ret.length > 1 && arch) {- ret = ret.filter(function (p) {- return path.basename(p).indexOf('-' + arch) !== -1;- });- }-- return ret;-}--function isAutoGenerated (file) {- return fs.existsSync(file) && fs.readFileSync(file, 'utf8').indexOf(MARKER) > 0;-}diff --git a/cordova/platforms/android/cordova/lib/builders/StudioBuilder.js b/cordova/platforms/android/cordova/lib/builders/StudioBuilder.jsnew file mode 100644index 000000000..1689e16c5--- /dev/null+++ b/cordova/platforms/android/cordova/lib/builders/StudioBuilder.js@@ -0,0 +1,303 @@+/*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+*/++var Q = require('q');+var fs = require('fs');+var util = require('util');+var path = require('path');+var shell = require('shelljs');+var spawn = require('cordova-common').superspawn.spawn;+var events = require('cordova-common').events;+var CordovaError = require('cordova-common').CordovaError;+var check_reqs = require('../check_reqs');++var GenericBuilder = require('./GenericBuilder');++var MARKER = 'YOUR CHANGES WILL BE ERASED!';+var SIGNING_PROPERTIES = '-signing.properties';+var TEMPLATE =+ '# This file is automatically generated.\n' ++ '# Do not modify this file -- ' + MARKER + '\n';++function StudioBuilder (projectRoot) {+ GenericBuilder.call(this, projectRoot);++ this.binDirs = {gradle: this.binDirs.studio};+}++util.inherits(StudioBuilder, GenericBuilder);++StudioBuilder.prototype.getArgs = function (cmd, opts) {+ if (cmd === 'release') {+ cmd = 'cdvBuildRelease';+ } else if (cmd === 'debug') {+ cmd = 'cdvBuildDebug';+ }+ var args = [cmd, '-b', path.join(this.root, 'build.gradle')];+ if (opts.arch) {+ args.push('-PcdvBuildArch=' + opts.arch);+ }++ // 10 seconds -> 6 seconds+ args.push('-Dorg.gradle.daemon=true');+ // to allow dex in process+ args.push('-Dorg.gradle.jvmargs=-Xmx2048m');+ // allow NDK to be used - required by Gradle 1.5 plugin+ // args.push('-Pandroid.useDeprecatedNdk=true');+ args.push.apply(args, opts.extraArgs);+ // Shaves another 100ms, but produces a "try at own risk" warning. Not worth it (yet):+ // args.push('-Dorg.gradle.parallel=true');+ return args;+};++/*+ * This returns a promise+ */++StudioBuilder.prototype.runGradleWrapper = function (gradle_cmd) {+ var gradlePath = path.join(this.root, 'gradlew');+ var wrapperGradle = path.join(this.root, 'wrapper.gradle');+ if (fs.existsSync(gradlePath)) {+ // Literally do nothing, for some reason this works, while !fs.existsSync didn't on Windows+ } else {+ return spawn(gradle_cmd, ['-p', this.root, 'wrapper', '-b', wrapperGradle], {stdio: 'inherit'});+ }+};++StudioBuilder.prototype.readProjectProperties = function () {++ function findAllUniq (data, r) {+ var s = {};+ var m;+ while ((m = r.exec(data))) {+ s[m[1]] = 1;+ }+ return Object.keys(s);+ }++ var data = fs.readFileSync(path.join(this.root, 'project.properties'), 'utf8');+ return {+ libs: findAllUniq(data, /^\s*android\.library\.reference\.\d+=(.*)(?:\s|$)/mg),+ gradleIncludes: findAllUniq(data, /^\s*cordova\.gradle\.include\.\d+=(.*)(?:\s|$)/mg),+ systemLibs: findAllUniq(data, /^\s*cordova\.system\.library\.\d+=(.*)(?:\s|$)/mg)+ };+};++StudioBuilder.prototype.extractRealProjectNameFromManifest = function () {+ var manifestPath = path.join(this.root, 'app', 'src', 'main', 'AndroidManifest.xml');+ var manifestData = fs.readFileSync(manifestPath, 'utf8');+ var m = /<manifest[\s\S]*?package\s*=\s*"(.*?)"/i.exec(manifestData);+ if (!m) {+ throw new CordovaError('Could not find package name in ' + manifestPath);+ }++ var packageName = m[1];+ var lastDotIndex = packageName.lastIndexOf('.');+ return packageName.substring(lastDotIndex + 1);+};++// Makes the project buildable, minus the gradle wrapper.+StudioBuilder.prototype.prepBuildFiles = function () {+ // Update the version of build.gradle in each dependent library.+ var pluginBuildGradle = path.join(this.root, 'cordova', 'lib', 'plugin-build.gradle');+ var propertiesObj = this.readProjectProperties();+ var subProjects = propertiesObj.libs;++ // Check and copy the gradle file into the subproject+ // Called by the loop before this function def++ var checkAndCopy = function (subProject, root) {+ var subProjectGradle = path.join(root, subProject, 'build.gradle');+ // This is the future-proof way of checking if a file exists+ // This must be synchronous to satisfy a Travis test+ try {+ fs.accessSync(subProjectGradle, fs.F_OK);+ } catch (e) {+ shell.cp('-f', pluginBuildGradle, subProjectGradle);+ }+ };++ for (var i = 0; i < subProjects.length; ++i) {+ if (subProjects[i] !== 'CordovaLib') {+ checkAndCopy(subProjects[i], this.root);+ }+ }+ var name = this.extractRealProjectNameFromManifest();+ // Remove the proj.id/name- prefix from projects: https://issues.apache.org/jira/browse/CB-9149+ var settingsGradlePaths = subProjects.map(function (p) {+ var realDir = p.replace(/[/\\]/g, ':');+ var libName = realDir.replace(name + '-', '');+ var str = 'include ":' + libName + '"\n';+ if (realDir.indexOf(name + '-') !== -1) {+ str += 'project(":' + libName + '").projectDir = new File("' + p + '")\n';+ }+ return str;+ });++ fs.writeFileSync(path.join(this.root, 'settings.gradle'),+ '// GENERATED FILE - DO NOT EDIT\n' ++ 'include ":"\n' + settingsGradlePaths.join(''));++ // Update dependencies within build.gradle.+ var buildGradle = fs.readFileSync(path.join(this.root, 'app', 'build.gradle'), 'utf8');+ var depsList = '';+ var root = this.root;+ var insertExclude = function (p) {+ var gradlePath = path.join(root, p, 'build.gradle');+ var projectGradleFile = fs.readFileSync(gradlePath, 'utf-8');+ if (projectGradleFile.indexOf('CordovaLib') !== -1) {+ depsList += '{\n exclude module:("CordovaLib")\n }\n';+ } else {+ depsList += '\n';+ }+ };+ subProjects.forEach(function (p) {+ events.emit('log', 'Subproject Path: ' + p);+ var libName = p.replace(/[/\\]/g, ':').replace(name + '-', '');+ if (libName !== 'app') {+ depsList += ' implementation(project(path: ":' + libName + '"))';+ insertExclude(p);+ }+ });+ // For why we do this mapping: https://issues.apache.org/jira/browse/CB-8390+ var SYSTEM_LIBRARY_MAPPINGS = [+ [/^\/?extras\/android\/support\/(.*)$/, 'com.android.support:support-$1:+'],+ [/^\/?google\/google_play_services\/libproject\/google-play-services_lib\/?$/, 'com.google.android.gms:play-services:+']+ ];++ propertiesObj.systemLibs.forEach(function (p) {+ var mavenRef;+ // It's already in gradle form if it has two ':'s+ if (/:.*:/.exec(p)) {+ mavenRef = p;+ } else {+ for (var i = 0; i < SYSTEM_LIBRARY_MAPPINGS.length; ++i) {+ var pair = SYSTEM_LIBRARY_MAPPINGS[i];+ if (pair[0].exec(p)) {+ mavenRef = p.replace(pair[0], pair[1]);+ break;+ }+ }+ if (!mavenRef) {+ throw new CordovaError('Unsupported system library (does not work with gradle): ' + p);+ }+ }+ depsList += ' compile "' + mavenRef + '"\n';+ });++ buildGradle = buildGradle.replace(/(SUB-PROJECT DEPENDENCIES START)[\s\S]*(\/\/ SUB-PROJECT DEPENDENCIES END)/, '$1\n' + depsList + ' $2');+ var includeList = '';++ propertiesObj.gradleIncludes.forEach(function (includePath) {+ includeList += 'apply from: "../' + includePath + '"\n';+ });+ buildGradle = buildGradle.replace(/(PLUGIN GRADLE EXTENSIONS START)[\s\S]*(\/\/ PLUGIN GRADLE EXTENSIONS END)/, '$1\n' + includeList + '$2');+ // This needs to be stored in the app gradle, not the root grade+ fs.writeFileSync(path.join(this.root, 'app', 'build.gradle'), buildGradle);+};++StudioBuilder.prototype.prepEnv = function (opts) {+ var self = this;+ return check_reqs.check_gradle()+ .then(function (gradlePath) {+ return self.runGradleWrapper(gradlePath);+ }).then(function () {+ return self.prepBuildFiles();+ }).then(function () {+ // If the gradle distribution URL is set, make sure it points to version we want.+ // If it's not set, do nothing, assuming that we're using a future version of gradle that we don't want to mess with.+ // For some reason, using ^ and $ don't work. This does the job, though.+ var distributionUrlRegex = /distributionUrl.*zip/;+ var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'https\\://services.gradle.org/distributions/gradle-4.1-all.zip';+ var gradleWrapperPropertiesPath = path.join(self.root, 'gradle', 'wrapper', 'gradle-wrapper.properties');+ shell.chmod('u+w', gradleWrapperPropertiesPath);+ shell.sed('-i', distributionUrlRegex, 'distributionUrl=' + distributionUrl, gradleWrapperPropertiesPath);++ var propertiesFile = opts.buildType + SIGNING_PROPERTIES;+ var propertiesFilePath = path.join(self.root, propertiesFile);+ if (opts.packageInfo) {+ fs.writeFileSync(propertiesFilePath, TEMPLATE + opts.packageInfo.toProperties());+ } else if (isAutoGenerated(propertiesFilePath)) {+ shell.rm('-f', propertiesFilePath);+ }+ });+};++/*+ * Builds the project with gradle.+ * Returns a promise.+ */+StudioBuilder.prototype.build = function (opts) {+ var wrapper = path.join(this.root, 'gradlew');+ var args = this.getArgs(opts.buildType === 'debug' ? 'debug' : 'release', opts);++ return spawn(wrapper, args, {stdio: 'pipe'})+ .progress(function (stdio) {+ if (stdio.stderr) {+ /*+ * Workaround for the issue with Java printing some unwanted information to+ * stderr instead of stdout.+ * This function suppresses 'Picked up _JAVA_OPTIONS' message from being+ * printed to stderr. See https://issues.apache.org/jira/browse/CB-9971 for+ * explanation.+ */+ var suppressThisLine = /^Picked up _JAVA_OPTIONS: /i.test(stdio.stderr.toString());+ if (suppressThisLine) {+ return;+ }+ process.stderr.write(stdio.stderr);+ } else {+ process.stdout.write(stdio.stdout);+ }+ }).catch(function (error) {+ if (error.toString().indexOf('failed to find target with hash string') >= 0) {+ return check_reqs.check_android_target(error).then(function () {+ // If due to some odd reason - check_android_target succeeds+ // we should still fail here.+ return Q.reject(error);+ });+ }+ return Q.reject(error);+ });+};++StudioBuilder.prototype.clean = function (opts) {+ var builder = this;+ var wrapper = path.join(this.root, 'gradlew');+ var args = builder.getArgs('clean', opts);+ return Q().then(function () {+ return spawn(wrapper, args, {stdio: 'inherit'});+ })+ .then(function () {+ shell.rm('-rf', path.join(builder.root, 'out'));++ ['debug', 'release'].forEach(function (config) {+ var propertiesFilePath = path.join(builder.root, config + SIGNING_PROPERTIES);+ if (isAutoGenerated(propertiesFilePath)) {+ shell.rm('-f', propertiesFilePath);+ }+ });+ });+};++module.exports = StudioBuilder;++function isAutoGenerated (file) {+ return fs.existsSync(file) && fs.readFileSync(file, 'utf8').indexOf(MARKER) > 0;+}diff --git a/cordova/platforms/android/cordova/lib/builders/builders.js b/cordova/platforms/android/cordova/lib/builders/builders.jsindex 42fc19d72..aedf9be52 100644--- a/cordova/platforms/android/cordova/lib/builders/builders.js+++ b/cordova/platforms/android/cordova/lib/builders/builders.js@@ -1,34 +1,46 @@/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at- http://www.apache.org/licenses/LICENSE-2.0+ http://www.apache.org/licenses/LICENSE-2.0- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.+ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.*/-const CordovaError = require('cordova-common').CordovaError;+var CordovaError = require('cordova-common').CordovaError;++var knownBuilders = {+ gradle: 'GradleBuilder',+ studio: 'StudioBuilder',+ none: 'GenericBuilder'+};/**- * Helper method that instantiates and returns a builder for specified build type.+ * Helper method that instantiates and returns a builder for specified build+ * type.*- * @return {Builder} A builder instance for specified build type.+ * @param {String} builderType Builder name to construct and return. Must+ * be one of 'ant', 'gradle' or 'none'+ *+ * @return {Builder} A builder instance for specified build type.*/-module.exports.getBuilder = function () {+module.exports.getBuilder = function (builderType, projectRoot) {+ if (!knownBuilders[builderType]) { throw new CordovaError('Builder ' + builderType + ' is not supported.'); }+try {- const Builder = require('./ProjectBuilder');- return new Builder();+ var Builder = require('./' + knownBuilders[builderType]);+ return new Builder(projectRoot);} catch (err) {- throw new CordovaError('Failed to instantiate ProjectBuilder builder: ' + err);+ throw new CordovaError('Failed to instantiate ' + knownBuilders[builderType] + ' builder: ' + err);}};diff --git a/cordova/platforms/android/cordova/lib/check_reqs.js b/cordova/platforms/android/cordova/lib/check_reqs.jsindex 95ef89fce..d9c5f99d5 100644--- a/cordova/platforms/android/cordova/lib/check_reqs.js+++ b/cordova/platforms/android/cordova/lib/check_reqs.js@@ -19,6 +19,8 @@under the License.*/+/* jshint sub:true */+var shelljs = require('shelljs');var child_process = require('child_process');var Q = require('q');diff --git a/cordova/platforms/android/cordova/lib/config/GradlePropertiesParser.js b/cordova/platforms/android/cordova/lib/config/GradlePropertiesParser.jsdeleted file mode 100644index ac7f38634..000000000--- a/cordova/platforms/android/cordova/lib/config/GradlePropertiesParser.js+++ /dev/null@@ -1,97 +0,0 @@-/**- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.-*/--let fs = require('fs');-let path = require('path');-let propertiesParser = require('properties-parser');-let events = require('cordova-common').events;--class GradlePropertiesParser {- /**- * Loads and Edits Gradle Properties File.- *- * @param {String} platformDir is the path of the Android platform directory- */- constructor (platformDir) {- this._defaults = {- // 10 seconds -> 6 seconds- 'org.gradle.daemon': 'true',-- // to allow dex in process- 'org.gradle.jvmargs': '-Xmx2048m',-- // allow NDK to be used - required by Gradle 1.5 plugin- 'android.useDeprecatedNdk': 'true'-- // Shaves another 100ms, but produces a "try at own risk" warning. Not worth it (yet):- // 'org.gradle.parallel': 'true'- };-- this.gradleFilePath = path.join(platformDir, 'gradle.properties');- }-- configure () {- events.emit('verbose', '[Gradle Properties] Preparing Configuration');-- this._initializeEditor();- this._configureDefaults();- this._save();- }-- /**- * Initialize the properties editor for parsing, setting, etc.- */- _initializeEditor () {- // Touch empty gradle.properties file if missing.- if (!fs.existsSync(this.gradleFilePath)) {- events.emit('verbose', '[Gradle Properties] File missing, creating file with Cordova defaults.');- fs.writeFileSync(this.gradleFilePath, '', 'utf-8');- }-- // Create an editor for parsing, getting, and setting configurations.- this.gradleFile = propertiesParser.createEditor(this.gradleFilePath);- }-- /**- * Validate that defaults are set and set the missing defaults.- */- _configureDefaults () {- // Loop though Cordova default properties and set only if missing.- Object.keys(this._defaults).forEach(key => {- let value = this.gradleFile.get(key);-- if (!value) {- events.emit('verbose', `[Gradle Properties] Appended missing default: ${key}=${this._defaults[key]}`);- this.gradleFile.set(key, this._defaults[key]);- } else if (value !== this._defaults[key]) {- events.emit('info', `[Gradle Properties] Detected Gradle property "${key}" with the value of "${value}", Cordova's recommended value is "${this._defaults[key]}"`);- }- });- }-- /**- * Saves any changes that has been made to the properties file.- */- _save () {- events.emit('verbose', '[Gradle Properties] Updating and Saving File');- this.gradleFile.save();- }-}--module.exports = GradlePropertiesParser;diff --git a/cordova/platforms/android/cordova/lib/device.js b/cordova/platforms/android/cordova/lib/device.jsindex b186f817e..84b509479 100644--- a/cordova/platforms/android/cordova/lib/device.js+++ b/cordova/platforms/android/cordova/lib/device.js@@ -19,6 +19,7 @@under the License.*/+var Q = require('q');var build = require('./build');var path = require('path');var Adb = require('./Adb');@@ -52,13 +53,13 @@ module.exports.list = function (lookHarder) {module.exports.resolveTarget = function (target) {return this.list(true).then(function (device_list) {if (!device_list || !device_list.length) {- return Promise.reject(new CordovaError('Failed to deploy to device, no devices found.'));+ return Q.reject(new CordovaError('Failed to deploy to device, no devices found.'));}// default devicetarget = target || device_list[0];if (device_list.indexOf(target) < 0) {- return Promise.reject(new CordovaError('ERROR: Unable to find target \'' + target + '\'.'));+ return Q.reject('ERROR: Unable to find target \'' + target + '\'.');}return build.detectArchitecture(target).then(function (arch) {@@ -73,7 +74,7 @@ module.exports.resolveTarget = function (target) {* Returns a promise.*/module.exports.install = function (target, buildResults) {- return Promise.resolve().then(function () {+ return Q().then(function () {if (target && typeof target === 'object') {return target;}diff --git a/cordova/platforms/android/cordova/lib/emulator.js b/cordova/platforms/android/cordova/lib/emulator.jsindex e87b7d470..63ed302fe 100644--- a/cordova/platforms/android/cordova/lib/emulator.js+++ b/cordova/platforms/android/cordova/lib/emulator.js@@ -19,6 +19,8 @@under the License.*/+/* jshint sub:true */+var android_versions = require('android-versions');var retry = require('./retry');var build = require('./build');@@ -32,6 +34,7 @@ var shelljs = require('shelljs');var android_sdk = require('./android_sdk');var check_reqs = require('./check_reqs');+var Q = require('q');var os = require('os');var fs = require('fs');var child_process = require('child_process');@@ -167,13 +170,15 @@ module.exports.list_images_using_android = function () {}*/module.exports.list_images = function () {- return Promise.resolve().then(function () {+ return Q.fcall(function () {if (forgivingWhichSync('avdmanager')) {return module.exports.list_images_using_avdmanager();} else if (forgivingWhichSync('android')) {return module.exports.list_images_using_android();} else {- return Promise.reject(new CordovaError('Could not find either `android` or `avdmanager` on your $PATH! Are you sure the Android SDK is installed and available?'));+ return Q().then(function () {+ throw new CordovaError('Could not find either `android` or `avdmanager` on your $PATH! Are you sure the Android SDK is installed and available?');+ });}}).then(function (avds) {// In case we're missing the Android OS version string from the target description, add it.@@ -272,8 +277,8 @@ module.exports.get_available_port = function () {module.exports.start = function (emulator_ID, boot_timeout) {var self = this;- return Promise.resolve().then(function () {- if (emulator_ID) return Promise.resolve(emulator_ID);+ return Q().then(function () {+ if (emulator_ID) return Q(emulator_ID);return self.best_image().then(function (best) {if (best && best.name) {@@ -282,7 +287,7 @@ module.exports.start = function (emulator_ID, boot_timeout) {}var androidCmd = check_reqs.getAbsoluteAndroidCmd();- return Promise.reject(new CordovaError('No emulator images (avds) found.\n' ++ return Q.reject(new CordovaError('No emulator images (avds) found.\n' +'1. Download desired System Image by running: ' + androidCmd + ' sdk\n' +'2. Create an AVD by running: ' + androidCmd + ' avd\n' +'HINT: For a faster emulator, use an Intel System Image and install the HAXM device driver\n'));@@ -303,7 +308,7 @@ module.exports.start = function (emulator_ID, boot_timeout) {return self.wait_for_emulator(port);});}).then(function (emulatorId) {- if (!emulatorId) { return Promise.reject(new CordovaError('Failed to start emulator')); }+ if (!emulatorId) { return Q.reject(new CordovaError('Failed to start emulator')); }// wait for emulator to boot upprocess.stdout.write('Waiting for emulator to boot (this may take a while)...');@@ -329,7 +334,7 @@ module.exports.start = function (emulator_ID, boot_timeout) {*/module.exports.wait_for_emulator = function (port) {var self = this;- return Promise.resolve().then(function () {+ return Q().then(function () {var emulator_id = 'emulator-' + port;return Adb.shell(emulator_id, 'getprop dev.bootcomplete').then(function (output) {if (output.indexOf('1') >= 0) {@@ -366,13 +371,10 @@ module.exports.wait_for_boot = function (emulator_id, time_remaining) {} else {process.stdout.write('.');- return new Promise(resolve => {- const delay = time_remaining < CHECK_BOOTED_INTERVAL ? time_remaining : CHECK_BOOTED_INTERVAL;-- setTimeout(() => {- const updated_time = time_remaining >= 0 ? Math.max(time_remaining - CHECK_BOOTED_INTERVAL, 0) : time_remaining;- resolve(self.wait_for_boot(emulator_id, updated_time));- }, delay);+ // Check at regular intervals+ return Q.delay(time_remaining < CHECK_BOOTED_INTERVAL ? time_remaining : CHECK_BOOTED_INTERVAL).then(function () {+ var updated_time = time_remaining >= 0 ? Math.max(time_remaining - CHECK_BOOTED_INTERVAL, 0) : time_remaining;+ return self.wait_for_boot(emulator_id, updated_time);});}});@@ -398,7 +400,7 @@ module.exports.create_image = function (name, target) {// TODO: This seems like another error case, even though it always happens.console.error('ERROR : Unable to create an avd emulator, no targets found.');console.error('Ensure you have targets available by running the "android" command');- return Promise.reject(new CordovaError());+ return Q.reject();}, function (error) {console.error('ERROR : Failed to create emulator image : ');console.error(error);@@ -409,13 +411,13 @@ module.exports.create_image = function (name, target) {module.exports.resolveTarget = function (target) {return this.list_started().then(function (emulator_list) {if (emulator_list.length < 1) {- return Promise.reject(new CordovaError('No running Android emulators found, please start an emulator before deploying your project.'));+ return Q.reject('No running Android emulators found, please start an emulator before deploying your project.');}// default emulatortarget = target || emulator_list[0];if (emulator_list.indexOf(target) < 0) {- return Promise.reject(new CordovaError('Unable to find target \'' + target + '\'. Failed to deploy to emulator.'));+ return Q.reject('Unable to find target \'' + target + '\'. Failed to deploy to emulator.');}return build.detectArchitecture(target).then(function (arch) {@@ -434,12 +436,15 @@ module.exports.install = function (givenTarget, buildResults) {var target;// We need to find the proper path to the Android Manifest- const manifestPath = path.join(__dirname, '..', '..', 'app', 'src', 'main', 'AndroidManifest.xml');- const manifest = new AndroidManifest(manifestPath);- const pkgName = manifest.getPackageId();+ var manifestPath = path.join(__dirname, '..', '..', 'app', 'src', 'main', 'AndroidManifest.xml');+ if (buildResults.buildMethod === 'gradle') {+ manifestPath = path.join(__dirname, '../../AndroidManifest.xml');+ }+ var manifest = new AndroidManifest(manifestPath);+ var pkgName = manifest.getPackageId();// resolve the target emulator- return Promise.resolve().then(function () {+ return Q().then(function () {if (givenTarget && typeof givenTarget === 'object') {return givenTarget;} else {@@ -454,7 +459,7 @@ module.exports.install = function (givenTarget, buildResults) {}).then(function () {// This promise is always resolved, even if 'adb uninstall' fails to uninstall app// or the app doesn't installed at all, so no error catching needed.- return Promise.resolve().then(function () {+ return Q.when().then(function () {var apk_path = build.findBestApkForArchitecture(buildResults, target.arch);var execOptions = {@@ -474,7 +479,7 @@ module.exports.install = function (givenTarget, buildResults) {events.emit('verbose', 'Installing apk ' + apk + ' on ' + target + '...');var command = 'adb -s ' + target + ' install -r "' + apk + '"';- return new Promise(function (resolve, reject) {+ return Q.promise(function (resolve, reject) {child_process.exec(command, opts, function (err, stdout, stderr) {if (err) reject(new CordovaError('Error executing "' + command + '": ' + stderr));// adb does not return an error code even if installation fails. Instead it puts a specificdiff --git a/cordova/platforms/android/cordova/lib/install-device b/cordova/platforms/android/cordova/lib/install-deviceindex 03873883e..fc4b7841f 100755--- a/cordova/platforms/android/cordova/lib/install-device+++ b/cordova/platforms/android/cordova/lib/install-device@@ -19,23 +19,23 @@under the License.*/-var device = require('./device');-var args = process.argv;+var device = require('./device'),+ args = process.argv;-if (args.length > 2) {+if(args.length > 2) {var install_target;- if (args[2].substring(0, 9) === '--target=') {+ if (args[2].substring(0, 9) == '--target=') {install_target = args[2].substring(9, args[2].length);- device.install(install_target).catch(function (err) {+ device.install(install_target).done(null, function(err) {console.error('ERROR: ' + err);process.exit(2);});- } else {+ } else {console.error('ERROR : argument \'' + args[2] + '\' not recognized.');process.exit(2);- }+ }} else {- device.install().catch(function (err) {+ device.install().done(null, function(err) {console.error('ERROR: ' + err);process.exit(2);});diff --git a/cordova/platforms/android/cordova/lib/install-emulator b/cordova/platforms/android/cordova/lib/install-emulatorindex 2d46dbe93..aa2a34f6f 100755--- a/cordova/platforms/android/cordova/lib/install-emulator+++ b/cordova/platforms/android/cordova/lib/install-emulator@@ -19,20 +19,20 @@under the License.*/-var emulator = require('./emulator');-var args = process.argv;+var emulator = require('./emulator'),+ args = process.argv;var install_target;-if (args.length > 2) {- if (args[2].substring(0, 9) === '--target=') {+if(args.length > 2) {+ if (args[2].substring(0, 9) == '--target=') {install_target = args[2].substring(9, args[2].length);- } else {+ } else {console.error('ERROR : argument \'' + args[2] + '\' not recognized.');process.exit(2);- }+ }}-emulator.install(install_target).catch(function (err) {+emulator.install(install_target).done(null, function(err) {console.error('ERROR: ' + err);process.exit(2);});diff --git a/cordova/platforms/android/cordova/lib/list-devices b/cordova/platforms/android/cordova/lib/list-devicesindex 339c6658d..8e22c7f2f 100755--- a/cordova/platforms/android/cordova/lib/list-devices+++ b/cordova/platforms/android/cordova/lib/list-devices@@ -22,12 +22,12 @@var devices = require('./device');// Usage support for when args are given-require('./check_reqs').check_android().then(function () {- devices.list().then(function (device_list) {- device_list && device_list.forEach(function (dev) {+require('./check_reqs').check_android().then(function() {+ devices.list().done(function(device_list) {+ device_list && device_list.forEach(function(dev) {console.log(dev);});- }, function (err) {+ }, function(err) {console.error('ERROR: ' + err);process.exit(2);});diff --git a/cordova/platforms/android/cordova/lib/list-emulator-images b/cordova/platforms/android/cordova/lib/list-emulator-imagesindex 03cfb190c..25e5c81a4 100755--- a/cordova/platforms/android/cordova/lib/list-emulator-images+++ b/cordova/platforms/android/cordova/lib/list-emulator-images@@ -22,12 +22,12 @@var emulators = require('./emulator');// Usage support for when args are given-require('./check_reqs').check_android().then(function () {- emulators.list_images().then(function (emulator_list) {- emulator_list && emulator_list.forEach(function (emu) {+require('./check_reqs').check_android().then(function() {+ emulators.list_images().done(function(emulator_list) {+ emulator_list && emulator_list.forEach(function(emu) {console.log(emu.name);});- }, function (err) {+ }, function(err) {console.error('ERROR: ' + err);process.exit(2);});diff --git a/cordova/platforms/android/cordova/lib/list-started-emulators b/cordova/platforms/android/cordova/lib/list-started-emulatorsindex 2a83e03a1..43ebda25b 100755--- a/cordova/platforms/android/cordova/lib/list-started-emulators+++ b/cordova/platforms/android/cordova/lib/list-started-emulators@@ -22,12 +22,12 @@var emulators = require('./emulator');// Usage support for when args are given-require('./check_reqs').check_android().then(function () {- emulators.list_started().then(function (emulator_list) {- emulator_list && emulator_list.forEach(function (emu) {+require('./check_reqs').check_android().then(function() {+ emulators.list_started().done(function(emulator_list) {+ emulator_list && emulator_list.forEach(function(emu) {console.log(emu);});- }, function (err) {+ }, function(err) {console.error('ERROR: ' + err);process.exit(2);});diff --git a/cordova/platforms/android/cordova/lib/plugin-build.gradle b/cordova/platforms/android/cordova/lib/plugin-build.gradleindex 032b870e1..fdef1f73f 100644--- a/cordova/platforms/android/cordova/lib/plugin-build.gradle+++ b/cordova/platforms/android/cordova/lib/plugin-build.gradle@@ -20,7 +20,9 @@buildscript {repositories {- google()+ maven {+ url "https://maven.google.com"+ }jcenter()}@@ -36,7 +38,7 @@ buildscript {apply plugin: 'com.android.library'dependencies {- implementation fileTree(dir: 'libs', include: '*.jar')+ compile fileTree(dir: 'libs', include: '*.jar')debugCompile project(path: ":CordovaLib", configuration: "debug")releaseCompile project(path: ":CordovaLib", configuration: "release")}@@ -44,6 +46,7 @@ dependencies {android {compileSdkVersion cdvCompileSdkVersionbuildToolsVersion cdvBuildToolsVersion+ publishNonDefault truecompileOptions {sourceCompatibility JavaVersion.VERSION_1_6diff --git a/cordova/platforms/android/cordova/lib/pluginHandlers.js b/cordova/platforms/android/cordova/lib/pluginHandlers.jsindex 6d1a7336e..f5be4b49d 100644--- a/cordova/platforms/android/cordova/lib/pluginHandlers.js+++ b/cordova/platforms/android/cordova/lib/pluginHandlers.js@@ -14,6 +14,8 @@**/+/* jshint unused: vars */+var fs = require('fs');var path = require('path');var shell = require('shelljs');@@ -26,7 +28,14 @@ var handlers = {if (!obj.src) throw new CordovaError(generateAttributeError('src', 'source-file', plugin.id));if (!obj.targetDir) throw new CordovaError(generateAttributeError('target-dir', 'source-file', plugin.id));- var dest = getInstallDestination(obj);+ var dest = path.join(obj.targetDir, path.basename(obj.src));++ // TODO: This code needs to be replaced, since the core plugins need to be re-mapped to a different location in+ // a later plugins release. This is for legacy plugins to work with Cordova.++ if (options && options.android_studio === true) {+ dest = getInstallDestination(obj);+ }if (options && options.force) {copyFile(plugin.dir, obj.src, project.projectDir, dest, !!(options && options.link));@@ -35,7 +44,11 @@ var handlers = {}},uninstall: function (obj, plugin, project, options) {- var dest = getInstallDestination(obj);+ var dest = path.join(obj.targetDir, path.basename(obj.src));++ if (options && options.android_studio === true) {+ dest = getInstallDestination(obj);+ }// TODO: Add Koltin extension to uninstall, since they are handled like Java filesif (obj.src.endsWith('java')) {@@ -48,21 +61,33 @@ var handlers = {},'lib-file': {install: function (obj, plugin, project, options) {- var dest = path.join('app/libs', path.basename(obj.src));+ var dest = path.join('libs', path.basename(obj.src));+ if (options && options.android_studio === true) {+ dest = path.join('app/libs', path.basename(obj.src));+ }copyFile(plugin.dir, obj.src, project.projectDir, dest, !!(options && options.link));},uninstall: function (obj, plugin, project, options) {- var dest = path.join('app/libs', path.basename(obj.src));+ var dest = path.join('libs', path.basename(obj.src));+ if (options && options.android_studio === true) {+ dest = path.join('app/libs', path.basename(obj.src));+ }removeFile(project.projectDir, dest);}},'resource-file': {install: function (obj, plugin, project, options) {- var dest = path.join('app', 'src', 'main', obj.target);+ var dest = path.normalize(obj.target);+ if (options && options.android_studio === true) {+ dest = path.join('app/src/main', dest);+ }copyFile(plugin.dir, obj.src, project.projectDir, dest, !!(options && options.link));},uninstall: function (obj, plugin, project, options) {- var dest = path.join('app', 'src', 'main', obj.target);+ var dest = path.normalize(obj.target);+ if (options && options.android_studio === true) {+ dest = path.join('app/src/main', dest);+ }removeFile(project.projectDir, dest);}},@@ -294,41 +319,27 @@ function generateAttributeError (attribute, element, id) {function getInstallDestination (obj) {var APP_MAIN_PREFIX = 'app/src/main';- var PATH_SEPARATOR = '/';- var PATH_SEP_MATCH = '\\' + PATH_SEPARATOR;- var PATH_SEP_OR_EOL_MATCH = '(\\' + PATH_SEPARATOR + '|$)';-- var appReg = new RegExp('^app' + PATH_SEP_OR_EOL_MATCH);- var libsReg = new RegExp('^libs' + PATH_SEP_OR_EOL_MATCH);- var srcReg = new RegExp('^src' + PATH_SEP_OR_EOL_MATCH);- var srcMainReg = new RegExp('^src' + PATH_SEP_MATCH + 'main' + PATH_SEP_OR_EOL_MATCH);-- if (appReg.test(obj.targetDir)) {+ if (obj.targetDir.startsWith('app')) {// If any source file is using the new app directory structure,// don't penalize itreturn path.join(obj.targetDir, path.basename(obj.src));- } else {- // Plugin using deprecated target directory structure (GH-580)- if (obj.src.endsWith('.java')) {- return path.join(APP_MAIN_PREFIX, 'java', obj.targetDir.replace(srcReg, ''),- path.basename(obj.src));- } else if (obj.src.endsWith('.aidl')) {- return path.join(APP_MAIN_PREFIX, 'aidl', obj.targetDir.replace(srcReg, ''),- path.basename(obj.src));- } else if (libsReg.test(obj.targetDir)) {- if (obj.src.endsWith('.so')) {- return path.join(APP_MAIN_PREFIX, 'jniLibs', obj.targetDir.replace(libsReg, ''),- path.basename(obj.src));- } else {- return path.join('app', obj.targetDir, path.basename(obj.src));- }- } else if (srcMainReg.test(obj.targetDir)) {+ } else if (obj.src.endsWith('.java')) {+ return path.join(APP_MAIN_PREFIX, 'java', obj.targetDir.substring(4), path.basename(obj.src));+ } else if (obj.src.endsWith('.aidl')) {+ return path.join(APP_MAIN_PREFIX, 'aidl', obj.targetDir.substring(4), path.basename(obj.src));+ } else if (obj.targetDir.includes('libs')) {+ if (obj.src.endsWith('.so')) {+ return path.join(APP_MAIN_PREFIX, 'jniLibs', obj.targetDir.substring(5), path.basename(obj.src));+ } else {return path.join('app', obj.targetDir, path.basename(obj.src));}-+ } else if (obj.targetDir.includes('src/main')) {+ return path.join('app', obj.targetDir, path.basename(obj.src));+ } else {// For all other source files not using the new app directory structure,// add 'app/src/main' to the targetDirreturn path.join(APP_MAIN_PREFIX, obj.targetDir, path.basename(obj.src));}+}diff --git a/cordova/platforms/android/cordova/lib/prepare.js b/cordova/platforms/android/cordova/lib/prepare.jsindex 54aa97d1e..ac63f8a68 100644--- a/cordova/platforms/android/cordova/lib/prepare.js+++ b/cordova/platforms/android/cordova/lib/prepare.js@@ -33,8 +33,6 @@ var PlatformJson = require('cordova-common').PlatformJson;var PlatformMunger = require('cordova-common').ConfigChanges.PlatformMunger;var PluginInfoProvider = require('cordova-common').PluginInfoProvider;-const GradlePropertiesParser = require('./config/GradlePropertiesParser');-module.exports.prepare = function (cordovaProject, options) {var self = this;@@ -43,9 +41,6 @@ module.exports.prepare = function (cordovaProject, options) {this._config = updateConfigFilesFrom(cordovaProject.projectConfig, munger, this.locations);- let gradlePropertiesParser = new GradlePropertiesParser(this.locations.root);- gradlePropertiesParser.configure();-// Update own www dir with project's www assets and plugins' assets and js-filesreturn Q.when(updateWww(cordovaProject, this.locations)).then(function () {// update project according to config.xml changes.@@ -270,14 +265,6 @@ function getImageResourcePath (resourcesDir, type, density, name, sourceName) {return resourcePath;}-function getAdaptiveImageResourcePath (resourcesDir, type, density, name, sourceName) {- if (/\.9\.png$/.test(sourceName)) {- name = name.replace(/\.png$/, '.9.png');- }- var resourcePath = path.join(resourcesDir, (density ? type + '-' + density + '-v26' : type), name);- return resourcePath;-}-function updateSplashes (cordovaProject, platformResourcesDir) {var resources = cordovaProject.projectConfig.getSplashScreens('android');@@ -327,197 +314,20 @@ function cleanSplashes (projectRoot, projectConfig, platformResourcesDir) {}function updateIcons (cordovaProject, platformResourcesDir) {- let icons = cordovaProject.projectConfig.getIcons('android');+ var icons = cordovaProject.projectConfig.getIcons('android');- // Skip if there are no app defined icons in config.xml+ // if there are icon elements in config.xmlif (icons.length === 0) {events.emit('verbose', 'This app does not have launcher icons defined');return;}- // 1. loop icons determin if there is an error in the setup.- // 2. during initial loop, also setup for legacy support.- let errorMissingAttributes = [];- let errorLegacyIconNeeded = [];- let hasAdaptive = false;- icons.forEach((icon, key) => {- if (- (icon.background && !icon.foreground)- || (!icon.background && icon.foreground)- || (!icon.background && !icon.foreground && !icon.src)- ) {- errorMissingAttributes.push(icon.density ? icon.density : 'size=' + (icon.height || icon.width));- }-- if (icon.foreground) {- hasAdaptive = true;-- if (- !icon.src- && (- icon.foreground.startsWith('@color')- || path.extname(path.basename(icon.foreground)) === '.xml'- )- ) {- errorLegacyIconNeeded.push(icon.density ? icon.density : 'size=' + (icon.height || icon.width));- } else if (!icon.src) {- icons[key].src = icon.foreground;- }- }- });-- let errorMessage = [];- if (errorMissingAttributes.length > 0) {- errorMessage.push('One of the following attributes are set but missing the other for the density type: ' + errorMissingAttributes.join(', ') + '. Please ensure that all require attributes are defined.');- }-- if (errorLegacyIconNeeded.length > 0) {- errorMessage.push('For the following icons with the density of: ' + errorLegacyIconNeeded.join(', ') + ', adaptive foreground with a defined color or vector can not be used as a standard fallback icon for older Android devices. To support older Android environments, please provide a value for the src attribute.');- }-- if (errorMessage.length > 0) {- throw new CordovaError(errorMessage.join(' '));- }-- let resourceMap = Object.assign(- {},- mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'ic_launcher.png'),- mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'ic_launcher_foreground.png'),- mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'ic_launcher_background.png'),- mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'ic_launcher_foreground.xml'),- mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'ic_launcher_background.xml'),- mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'ic_launcher.xml')- );-- let preparedIcons = prepareIcons(icons);-- if (hasAdaptive) {- resourceMap = updateIconResourceForAdaptive(preparedIcons, resourceMap, platformResourcesDir);- }-- resourceMap = updateIconResourceForLegacy(preparedIcons, resourceMap, platformResourcesDir);-- events.emit('verbose', 'Updating icons at ' + platformResourcesDir);- FileUpdater.updatePaths(resourceMap, { rootDir: cordovaProject.root }, logFileOp);-}--function updateIconResourceForAdaptive (preparedIcons, resourceMap, platformResourcesDir) {- let android_icons = preparedIcons.android_icons;- let default_icon = preparedIcons.default_icon;-- // The source paths for icons and splashes are relative to- // project's config.xml location, so we use it as base path.- let background;- let foreground;- let targetPathBackground;- let targetPathForeground;-- for (let density in android_icons) {- let backgroundVal = '@mipmap/ic_launcher_background';- let foregroundVal = '@mipmap/ic_launcher_foreground';-- background = android_icons[density].background;- foreground = android_icons[density].foreground;-- if (background.startsWith('@color')) {- // Colors Use Case- backgroundVal = background; // Example: @color/background_foobar_1- } else if (path.extname(path.basename(background)) === '.xml') {- // Vector Use Case- targetPathBackground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', density, 'ic_launcher_background.xml', path.basename(android_icons[density].background));- resourceMap[targetPathBackground] = android_icons[density].background;- } else if (path.extname(path.basename(background)) === '.png') {- // Images Use Case- targetPathBackground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', density, 'ic_launcher_background.png', path.basename(android_icons[density].background));- resourceMap[targetPathBackground] = android_icons[density].background;- }-- if (foreground.startsWith('@color')) {- // Colors Use Case- foregroundVal = foreground;- } else if (path.extname(path.basename(foreground)) === '.xml') {- // Vector Use Case- targetPathForeground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', density, 'ic_launcher_foreground.xml', path.basename(android_icons[density].foreground));- resourceMap[targetPathForeground] = android_icons[density].foreground;- } else if (path.extname(path.basename(foreground)) === '.png') {- // Images Use Case- targetPathForeground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', density, 'ic_launcher_foreground.png', path.basename(android_icons[density].foreground));- resourceMap[targetPathForeground] = android_icons[density].foreground;- }-- // create an XML for DPI and set color- const icLauncherTemplate = `<?xml version="1.0" encoding="utf-8"?>-<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">- <background android:drawable="` + backgroundVal + `" />- <foreground android:drawable="` + foregroundVal + `" />-</adaptive-icon>`;-- let launcherXmlPath = path.join(platformResourcesDir, 'mipmap-' + density + '-v26', 'ic_launcher.xml');-- // Remove the XML from the resourceMap so the file does not get removed.- delete resourceMap[launcherXmlPath];-- fs.writeFileSync(path.resolve(launcherXmlPath), icLauncherTemplate);- }-- // There's no "default" drawable, so assume default == mdpi.- if (default_icon && !android_icons.mdpi) {- let defaultTargetPathBackground;- let defaultTargetPathForeground;-- if (background.startsWith('@color')) {- // Colors Use Case- targetPathBackground = default_icon.background;- } else if (path.extname(path.basename(background)) === '.xml') {- // Vector Use Case- defaultTargetPathBackground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', 'mdpi', 'ic_launcher_background.xml', path.basename(default_icon.background));- resourceMap[defaultTargetPathBackground] = default_icon.background;- } else if (path.extname(path.basename(background)) === '.png') {- // Images Use Case- defaultTargetPathBackground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', 'mdpi', 'ic_launcher_background.png', path.basename(default_icon.background));- resourceMap[defaultTargetPathBackground] = default_icon.background;- }-- if (foreground.startsWith('@color')) {- // Colors Use Case- targetPathForeground = default_icon.foreground;- } else if (path.extname(path.basename(foreground)) === '.xml') {- // Vector Use Case- defaultTargetPathForeground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', 'mdpi', 'ic_launcher_foreground.xml', path.basename(default_icon.foreground));- resourceMap[defaultTargetPathForeground] = default_icon.foreground;- } else if (path.extname(path.basename(foreground)) === '.png') {- // Images Use Case- defaultTargetPathForeground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', 'mdpi', 'ic_launcher_foreground.png', path.basename(default_icon.foreground));- resourceMap[defaultTargetPathForeground] = default_icon.foreground;- }- }+ var resourceMap = mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'icon.png');- return resourceMap;-}--function updateIconResourceForLegacy (preparedIcons, resourceMap, platformResourcesDir) {- let android_icons = preparedIcons.android_icons;- let default_icon = preparedIcons.default_icon;-- // The source paths for icons and splashes are relative to- // project's config.xml location, so we use it as base path.- for (var density in android_icons) {- var targetPath = getImageResourcePath(platformResourcesDir, 'mipmap', density, 'ic_launcher.png', path.basename(android_icons[density].src));- resourceMap[targetPath] = android_icons[density].src;- }-- // There's no "default" drawable, so assume default == mdpi.- if (default_icon && !android_icons.mdpi) {- var defaultTargetPath = getImageResourcePath(platformResourcesDir, 'mipmap', 'mdpi', 'ic_launcher.png', path.basename(default_icon.src));- resourceMap[defaultTargetPath] = default_icon.src;- }-- return resourceMap;-}--function prepareIcons (icons) {+ var android_icons = {};+ var default_icon;// http://developer.android.com/design/style/iconography.html- const SIZE_TO_DENSITY_MAP = {+ var sizeToDensityMap = {36: 'ldpi',48: 'mdpi',72: 'hdpi',@@ -525,15 +335,11 @@ function prepareIcons (icons) {144: 'xxhdpi',192: 'xxxhdpi'};-- let android_icons = {};- let default_icon;-// find the best matching icon for a given density or size// @output android_iconsvar parseIcon = function (icon, icon_size) {// do I have a platform icon for that density already- var density = icon.density || SIZE_TO_DENSITY_MAP[icon_size];+ var density = icon.density || sizeToDensityMap[icon_size];if (!density) {// invalid icon defition ( or unsupported size)return;@@ -549,34 +355,12 @@ function prepareIcons (icons) {for (var i = 0; i < icons.length; i++) {var icon = icons[i];var size = icon.width;-if (!size) {size = icon.height;}-if (!size && !icon.density) {if (default_icon) {- let found = {};- let favor = {};-- // populating found icon.- if (icon.background && icon.foreground) {- found.background = icon.background;- found.foreground = icon.foreground;- }- if (icon.src) {- found.src = icon.src;- }-- if (default_icon.background && default_icon.foreground) {- favor.background = default_icon.background;- favor.foreground = default_icon.foreground;- }- if (default_icon.src) {- favor.src = default_icon.src;- }-- events.emit('verbose', 'Found extra default icon: ' + JSON.stringify(found) + ' and ignoring in favor of ' + JSON.stringify(favor) + '.');+ events.emit('verbose', 'Found extra default icon: ' + icon.src + ' (ignoring in favor of ' + default_icon.src + ')');} else {default_icon = icon;}@@ -585,35 +369,36 @@ function prepareIcons (icons) {}}- return {- android_icons: android_icons,- default_icon: default_icon- };+ // The source paths for icons and splashes are relative to+ // project's config.xml location, so we use it as base path.+ for (var density in android_icons) {+ var targetPath = getImageResourcePath(+ platformResourcesDir, 'mipmap', density, 'icon.png', path.basename(android_icons[density].src));+ resourceMap[targetPath] = android_icons[density].src;+ }++ // There's no "default" drawable, so assume default == mdpi.+ if (default_icon && !android_icons.mdpi) {+ var defaultTargetPath = getImageResourcePath(+ platformResourcesDir, 'mipmap', 'mdpi', 'icon.png', path.basename(default_icon.src));+ resourceMap[defaultTargetPath] = default_icon.src;+ }++ events.emit('verbose', 'Updating icons at ' + platformResourcesDir);+ FileUpdater.updatePaths(+ resourceMap, { rootDir: cordovaProject.root }, logFileOp);}function cleanIcons (projectRoot, projectConfig, platformResourcesDir) {var icons = projectConfig.getIcons('android');+ if (icons.length > 0) {+ var resourceMap = mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'icon.png');+ events.emit('verbose', 'Cleaning icons at ' + platformResourcesDir);- // Skip if there are no app defined icons in config.xml- if (icons.length === 0) {- events.emit('verbose', 'This app does not have launcher icons defined');- return;+ // No source paths are specified in the map, so updatePaths() will delete the target files.+ FileUpdater.updatePaths(+ resourceMap, { rootDir: projectRoot, all: true }, logFileOp);}-- let resourceMap = Object.assign(- {},- mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher.png'),- mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher_foreground.png'),- mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher_background.png'),- mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher_foreground.xml'),- mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher_background.xml'),- mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher.xml')- );-- events.emit('verbose', 'Cleaning icons at ' + platformResourcesDir);-- // No source paths are specified in the map, so updatePaths() will delete the target files.- FileUpdater.updatePaths(resourceMap, { rootDir: projectRoot, all: true }, logFileOp);}/**diff --git a/cordova/platforms/android/cordova/lib/retry.js b/cordova/platforms/android/cordova/lib/retry.jsindex b2b9a4496..c464b9d5f 100644--- a/cordova/platforms/android/cordova/lib/retry.js+++ b/cordova/platforms/android/cordova/lib/retry.js@@ -19,6 +19,8 @@under the License.*/+/* jshint node: true */+'use strict';var events = require('cordova-common').events;@@ -27,20 +29,21 @@ var events = require('cordova-common').events;* Retry a promise-returning function a number of times, propagating its* results on success or throwing its error on a failed final attempt.*- * @arg {Number} attemptsLeft - The number of times to retry the passed call.+ * @arg {Number} attemts_left - The number of times to retry the passed call.* @arg {Function} promiseFunction - A function that returns a promise.* @arg {...} - Arguments to pass to promiseFunction.** @returns {Promise}*/-module.exports.retryPromise = function (attemptsLeft, promiseFunction) {+module.exports.retryPromise = function (attemts_left, promiseFunction) {// NOTE:- // get all trailing arguments, by skipping the first two (attemptsLeft and+ // get all trailing arguments, by skipping the first two (attemts_left and// promiseFunction) because they shouldn't get passed to promiseFunctionvar promiseFunctionArguments = Array.prototype.slice.call(arguments, 2);return promiseFunction.apply(undefined, promiseFunctionArguments).then(+// on success pass results throughfunction onFulfilled (value) {return value;@@ -48,16 +51,17 @@ module.exports.retryPromise = function (attemptsLeft, promiseFunction) {// on rejection either retry, or throw the errorfunction onRejected (error) {- attemptsLeft -= 1;- if (attemptsLeft < 1) {+ attemts_left -= 1;++ if (attemts_left < 1) {throw error;}- events.emit('verbose', 'A retried call failed. Retrying ' + attemptsLeft + ' more time(s).');+ events.emit('verbose', 'A retried call failed. Retrying ' + attemts_left + ' more time(s).');- // retry call self again with the same arguments, except attemptsLeft is now lower- var fullArguments = [attemptsLeft, promiseFunction].concat(promiseFunctionArguments);+ // retry call self again with the same arguments, except attemts_left is now lower+ var fullArguments = [attemts_left, promiseFunction].concat(promiseFunctionArguments);return module.exports.retryPromise.apply(undefined, fullArguments);});diff --git a/cordova/platforms/android/cordova/lib/run.js b/cordova/platforms/android/cordova/lib/run.jsindex 221467bb1..4d7927ced 100644--- a/cordova/platforms/android/cordova/lib/run.js+++ b/cordova/platforms/android/cordova/lib/run.js@@ -19,7 +19,10 @@under the License.*/+/* jshint loopfunc:true */+var path = require('path');+var build = require('./build');var emulator = require('./emulator');var device = require('./device');var Q = require('q');@@ -49,7 +52,6 @@ function getInstallTarget (runOptions) {* @return {Promise}*/module.exports.run = function (runOptions) {- runOptions = runOptions || {};var self = this;var install_target = getInstallTarget(runOptions);@@ -101,17 +103,16 @@ module.exports.run = function (runOptions) {});});}).then(function (resolvedTarget) {- return new Promise((resolve) => {- const builder = require('./builders/builders').getBuilder();- const buildOptions = require('./build').parseBuildOptions(runOptions, null, self.root);- resolve(builder.fetchBuildResults(buildOptions.buildType, buildOptions.arch));- }).then(function (buildResults) {+ // Better just call self.build, but we're doing some processing of+ // build results (according to platformApi spec) so they are in different+ // format than emulator.install expects.+ // TODO: Update emulator/device.install to handle this change+ return build.run.call(self, runOptions, resolvedTarget).then(function (buildResults) {if (resolvedTarget && resolvedTarget.isEmulator) {return emulator.wait_for_boot(resolvedTarget.target).then(function () {return emulator.install(resolvedTarget, buildResults);});}-return device.install(resolvedTarget, buildResults);});});diff --git a/cordova/platforms/android/cordova/lib/start-emulator b/cordova/platforms/android/cordova/lib/start-emulatorindex 20c92b70b..f96bdc3ef 100755--- a/cordova/platforms/android/cordova/lib/start-emulator+++ b/cordova/platforms/android/cordova/lib/start-emulator@@ -19,20 +19,21 @@under the License.*/-var emulator = require('./emulator');-var args = process.argv;+var emulator = require('./emulator'),+ args = process.argv;var install_target;-if (args.length > 2) {- if (args[2].substring(0, 9) === '--target=') {+if(args.length > 2) {+ if (args[2].substring(0, 9) == '--target=') {install_target = args[2].substring(9, args[2].length);- } else {+ } else {console.error('ERROR : argument \'' + args[2] + '\' not recognized.');process.exit(2);- }+ }}-emulator.start(install_target).catch(function (err) {+emulator.start(install_target).done(null, function(err) {console.error('ERROR: ' + err);process.exit(2);});+diff --git a/cordova/platforms/android/cordova/log b/cordova/platforms/android/cordova/logindex 6829f28d2..47f060505 100755--- a/cordova/platforms/android/cordova/log+++ b/cordova/platforms/android/cordova/log@@ -19,17 +19,17 @@under the License.*/-var log = require('./lib/log');-var reqs = require('./lib/check_reqs');-var args = process.argv;+var log = require('./lib/log'),+ reqs = require('./lib/check_reqs'),+ args = process.argv;// Usage support for when args are given-if (args.length > 2) {+if(args.length > 2) {log.help();} else {- reqs.run().done(function () {+ reqs.run().done(function() {return log.run();- }, function (err) {+ }, function(err) {console.error('ERROR: ' + err);process.exit(2);});diff --git a/cordova/platforms/android/cordova/run b/cordova/platforms/android/cordova/runindex 7408a94f7..9544c1dcf 100755--- a/cordova/platforms/android/cordova/run+++ b/cordova/platforms/android/cordova/run@@ -24,23 +24,22 @@ var nopt = require('nopt');var path = require('path');// Support basic help commands-if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >= 0) {+if(['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >= 0)require('./lib/run').help();-}// Do some basic argument parsingvar runOpts = nopt({- 'verbose': Boolean,- 'silent': Boolean,- 'debug': Boolean,- 'release': Boolean,+ 'verbose' : Boolean,+ 'silent' : Boolean,+ 'debug' : Boolean,+ 'release' : Boolean,'nobuild': Boolean,- 'buildConfig': path,- 'archs': String,- 'device': Boolean,+ 'buildConfig' : path,+ 'archs' : String,+ 'device' : Boolean,'emulator': Boolean,- 'target': String-}, { 'd': '--verbose' });+ 'target' : String+}, { 'd' : '--verbose' });// Make runOptions compatible with PlatformApi run method specrunOpts.argv = runOpts.argv.remain;@@ -48,7 +47,7 @@ runOpts.argv = runOpts.argv.remain;require('./loggingHelper').adjustLoggerLevel(runOpts);new Api().run(runOpts)-.catch(function (err) {+.catch(function(err) {console.error(err, err.stack);process.exit(2);});diff --git a/cordova/platforms/android/cordova/version b/cordova/platforms/android/cordova/versionindex 01229aa6d..42d31ce6d 100755--- a/cordova/platforms/android/cordova/version+++ b/cordova/platforms/android/cordova/version@@ -20,7 +20,7 @@*/// Coho updates this line:-var VERSION = "8.0.0-dev";+var VERSION = "7.1.4";module.exports.version = VERSION;diff --git a/cordova/platforms/android/gradle.properties b/cordova/platforms/android/gradle.propertiesdeleted file mode 100644index 11bc459ef..000000000--- a/cordova/platforms/android/gradle.properties+++ /dev/null@@ -1,3 +0,0 @@-org.gradle.daemon=true-org.gradle.jvmargs=-Xmx2048m-android.useDeprecatedNdk=true\ No newline at end of filediff --git a/cordova/platforms/android/gradle/wrapper/gradle-wrapper.jar b/cordova/platforms/android/gradle/wrapper/gradle-wrapper.jarindex 5ba3e81f7..94336fcae 100644Binary files a/cordova/platforms/android/gradle/wrapper/gradle-wrapper.jar and b/cordova/platforms/android/gradle/wrapper/gradle-wrapper.jar differdiff --git a/cordova/platforms/android/gradle/wrapper/gradle-wrapper.properties b/cordova/platforms/android/gradle/wrapper/gradle-wrapper.propertiesindex ce69659e2..45d84399a 100644--- a/cordova/platforms/android/gradle/wrapper/gradle-wrapper.properties+++ b/cordova/platforms/android/gradle/wrapper/gradle-wrapper.properties@@ -1,6 +1,5 @@-#Tue Nov 20 10:23:12 CET 2018distributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/dists+distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zipzipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/dists-distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zipdiff --git a/cordova/platforms/android/gradlew b/cordova/platforms/android/gradlewindex 4453ccea3..cccdd3d51 100755--- a/cordova/platforms/android/gradlew+++ b/cordova/platforms/android/gradlew@@ -33,11 +33,11 @@ DEFAULT_JVM_OPTS=""# Use the maximum available, or set MAX_FD != -1 to use that value.MAX_FD="maximum"-warn ( ) {+warn () {echo "$*"}-die ( ) {+die () {echoecho "$*"echo@@ -155,7 +155,7 @@ if $cygwin ; thenfi# Escape application args-save ( ) {+save () {for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; doneecho " "}diff --git a/cordova/platforms/android/platform_www/cordova.js b/cordova/platforms/android/platform_www/cordova.jsindex 4cdb1e3e5..da35c0214 100644--- a/cordova/platforms/android/platform_www/cordova.js+++ b/cordova/platforms/android/platform_www/cordova.js@@ -1,5 +1,5 @@// Platform: android-// e040d9e9343d5f27dd4f67616660b33b92a82ff7+// 9e8e1b716252c4a08abcd31a13013b868d6f4141/*Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE file@@ -19,7 +19,7 @@under the License.*/;(function() {-var PLATFORM_VERSION_BUILD_LABEL = '8.0.0-dev';+var PLATFORM_VERSION_BUILD_LABEL = '7.1.4';// file: src/scripts/require.js/* jshint -W079 */@@ -975,6 +975,17 @@ function androidExec(success, fail, service, action, args) {}androidExec.init = function() {+ //CB-11828+ //This failsafe checks the version of Android and if it's Jellybean, it switches it to+ //using the Online Event bridge for communicating from Native to JS+ //+ //It's ugly, but it's necessary.+ var check = navigator.userAgent.toLowerCase().match(/android\s[0-9].[0-9]/);+ var version_code = check && check[0].match(/4.[0-3].*/);+ if (version_code != null && nativeToJsBridgeMode == nativeToJsModes.EVAL_BRIDGE) {+ nativeToJsBridgeMode = nativeToJsModes.ONLINE_EVENT;+ }+bridgeSecret = +prompt('', 'gap_init:' + nativeToJsBridgeMode);channel.onNativeReady.fire();};@@ -2175,4 +2186,4 @@ window.cordova = require('cordova');require('cordova/init');-})();\ No newline at end of file+})();diff --git a/cordova/platforms/android/platform_www/cordova_plugins.js b/cordova/platforms/android/platform_www/cordova_plugins.jsindex 12711ac06..0086aec18 100644--- a/cordova/platforms/android/platform_www/cordova_plugins.js+++ b/cordova/platforms/android/platform_www/cordova_plugins.js@@ -1,223 +1,243 @@cordova.define('cordova/plugin_list', function(require, exports, module) {- module.exports = [- {- "id": "cordova-plugin-camera.Camera",- "file": "plugins/cordova-plugin-camera/www/CameraConstants.js",- "pluginId": "cordova-plugin-camera",- "clobbers": [- "Camera"- ]- },- {- "id": "cordova-plugin-camera.CameraPopoverOptions",- "file": "plugins/cordova-plugin-camera/www/CameraPopoverOptions.js",- "pluginId": "cordova-plugin-camera",- "clobbers": [- "CameraPopoverOptions"- ]- },- {- "id": "cordova-plugin-camera.camera",- "file": "plugins/cordova-plugin-camera/www/Camera.js",- "pluginId": "cordova-plugin-camera",- "clobbers": [- "navigator.camera"- ]- },- {- "id": "cordova-plugin-camera.CameraPopoverHandle",- "file": "plugins/cordova-plugin-camera/www/CameraPopoverHandle.js",- "pluginId": "cordova-plugin-camera",- "clobbers": [- "CameraPopoverHandle"- ]- },- {- "id": "cordova-plugin-device.device",- "file": "plugins/cordova-plugin-device/www/device.js",- "pluginId": "cordova-plugin-device",- "clobbers": [- "device"- ]- },- {- "id": "cordova-plugin-file.DirectoryEntry",- "file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.DirectoryEntry"- ]- },- {- "id": "cordova-plugin-file.DirectoryReader",- "file": "plugins/cordova-plugin-file/www/DirectoryReader.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.DirectoryReader"- ]- },- {- "id": "cordova-plugin-file.Entry",- "file": "plugins/cordova-plugin-file/www/Entry.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.Entry"- ]- },- {- "id": "cordova-plugin-file.File",- "file": "plugins/cordova-plugin-file/www/File.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.File"- ]- },- {- "id": "cordova-plugin-file.FileEntry",- "file": "plugins/cordova-plugin-file/www/FileEntry.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.FileEntry"- ]- },- {- "id": "cordova-plugin-file.FileError",- "file": "plugins/cordova-plugin-file/www/FileError.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.FileError"- ]- },- {- "id": "cordova-plugin-file.FileReader",- "file": "plugins/cordova-plugin-file/www/FileReader.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.FileReader"- ]- },- {- "id": "cordova-plugin-file.FileSystem",- "file": "plugins/cordova-plugin-file/www/FileSystem.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.FileSystem"- ]- },- {- "id": "cordova-plugin-file.FileUploadOptions",- "file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.FileUploadOptions"- ]- },- {- "id": "cordova-plugin-file.FileUploadResult",- "file": "plugins/cordova-plugin-file/www/FileUploadResult.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.FileUploadResult"- ]- },- {- "id": "cordova-plugin-file.FileWriter",- "file": "plugins/cordova-plugin-file/www/FileWriter.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.FileWriter"- ]- },- {- "id": "cordova-plugin-file.Flags",- "file": "plugins/cordova-plugin-file/www/Flags.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.Flags"- ]- },- {- "id": "cordova-plugin-file.LocalFileSystem",- "file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.LocalFileSystem"- ],- "merges": [- "window"- ]- },- {- "id": "cordova-plugin-file.Metadata",- "file": "plugins/cordova-plugin-file/www/Metadata.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.Metadata"- ]- },- {- "id": "cordova-plugin-file.ProgressEvent",- "file": "plugins/cordova-plugin-file/www/ProgressEvent.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.ProgressEvent"- ]- },- {- "id": "cordova-plugin-file.fileSystems",- "file": "plugins/cordova-plugin-file/www/fileSystems.js",- "pluginId": "cordova-plugin-file"- },- {- "id": "cordova-plugin-file.requestFileSystem",- "file": "plugins/cordova-plugin-file/www/requestFileSystem.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.requestFileSystem"- ]- },- {- "id": "cordova-plugin-file.resolveLocalFileSystemURI",- "file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",- "pluginId": "cordova-plugin-file",- "merges": [- "window"- ]- },- {- "id": "cordova-plugin-file.isChrome",- "file": "plugins/cordova-plugin-file/www/browser/isChrome.js",- "pluginId": "cordova-plugin-file",- "runs": true- },- {- "id": "cordova-plugin-file.androidFileSystem",- "file": "plugins/cordova-plugin-file/www/android/FileSystem.js",- "pluginId": "cordova-plugin-file",- "merges": [- "FileSystem"- ]- },- {- "id": "cordova-plugin-file.fileSystems-roots",- "file": "plugins/cordova-plugin-file/www/fileSystems-roots.js",- "pluginId": "cordova-plugin-file",- "runs": true- },- {- "id": "cordova-plugin-file.fileSystemPaths",- "file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",- "pluginId": "cordova-plugin-file",- "merges": [- "cordova"- ],- "runs": true- }- ];- module.exports.metadata = {- "cordova-plugin-camera": "4.0.3",- "cordova-plugin-device": "2.0.2",- "cordova-plugin-file": "6.0.1",- "cordova-plugin-whitelist": "1.3.3"- };+module.exports = [+ {+ "id": "cordova-plugin-camera.Camera",+ "file": "plugins/cordova-plugin-camera/www/CameraConstants.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "Camera"+ ]+ },+ {+ "id": "cordova-plugin-camera.CameraPopoverOptions",+ "file": "plugins/cordova-plugin-camera/www/CameraPopoverOptions.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "CameraPopoverOptions"+ ]+ },+ {+ "id": "cordova-plugin-camera.camera",+ "file": "plugins/cordova-plugin-camera/www/Camera.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "navigator.camera"+ ]+ },+ {+ "id": "cordova-plugin-camera.CameraPopoverHandle",+ "file": "plugins/cordova-plugin-camera/www/CameraPopoverHandle.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "CameraPopoverHandle"+ ]+ },+ {+ "id": "cordova-plugin-device.device",+ "file": "plugins/cordova-plugin-device/www/device.js",+ "pluginId": "cordova-plugin-device",+ "clobbers": [+ "device"+ ]+ },+ {+ "id": "cordova-plugin-file.DirectoryEntry",+ "file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.DirectoryEntry"+ ]+ },+ {+ "id": "cordova-plugin-file.DirectoryReader",+ "file": "plugins/cordova-plugin-file/www/DirectoryReader.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.DirectoryReader"+ ]+ },+ {+ "id": "cordova-plugin-file.Entry",+ "file": "plugins/cordova-plugin-file/www/Entry.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.Entry"+ ]+ },+ {+ "id": "cordova-plugin-file.File",+ "file": "plugins/cordova-plugin-file/www/File.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.File"+ ]+ },+ {+ "id": "cordova-plugin-file.FileEntry",+ "file": "plugins/cordova-plugin-file/www/FileEntry.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileEntry"+ ]+ },+ {+ "id": "cordova-plugin-file.FileError",+ "file": "plugins/cordova-plugin-file/www/FileError.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileError"+ ]+ },+ {+ "id": "cordova-plugin-file.FileReader",+ "file": "plugins/cordova-plugin-file/www/FileReader.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileReader"+ ]+ },+ {+ "id": "cordova-plugin-file.FileSystem",+ "file": "plugins/cordova-plugin-file/www/FileSystem.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileSystem"+ ]+ },+ {+ "id": "cordova-plugin-file.FileUploadOptions",+ "file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileUploadOptions"+ ]+ },+ {+ "id": "cordova-plugin-file.FileUploadResult",+ "file": "plugins/cordova-plugin-file/www/FileUploadResult.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileUploadResult"+ ]+ },+ {+ "id": "cordova-plugin-file.FileWriter",+ "file": "plugins/cordova-plugin-file/www/FileWriter.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileWriter"+ ]+ },+ {+ "id": "cordova-plugin-file.Flags",+ "file": "plugins/cordova-plugin-file/www/Flags.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.Flags"+ ]+ },+ {+ "id": "cordova-plugin-file.LocalFileSystem",+ "file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.LocalFileSystem"+ ],+ "merges": [+ "window"+ ]+ },+ {+ "id": "cordova-plugin-file.Metadata",+ "file": "plugins/cordova-plugin-file/www/Metadata.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.Metadata"+ ]+ },+ {+ "id": "cordova-plugin-file.ProgressEvent",+ "file": "plugins/cordova-plugin-file/www/ProgressEvent.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.ProgressEvent"+ ]+ },+ {+ "id": "cordova-plugin-file.fileSystems",+ "file": "plugins/cordova-plugin-file/www/fileSystems.js",+ "pluginId": "cordova-plugin-file"+ },+ {+ "id": "cordova-plugin-file.requestFileSystem",+ "file": "plugins/cordova-plugin-file/www/requestFileSystem.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.requestFileSystem"+ ]+ },+ {+ "id": "cordova-plugin-file.resolveLocalFileSystemURI",+ "file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",+ "pluginId": "cordova-plugin-file",+ "merges": [+ "window"+ ]+ },+ {+ "id": "cordova-plugin-file.isChrome",+ "file": "plugins/cordova-plugin-file/www/browser/isChrome.js",+ "pluginId": "cordova-plugin-file",+ "runs": true+ },+ {+ "id": "cordova-plugin-file.androidFileSystem",+ "file": "plugins/cordova-plugin-file/www/android/FileSystem.js",+ "pluginId": "cordova-plugin-file",+ "merges": [+ "FileSystem"+ ]+ },+ {+ "id": "cordova-plugin-file.fileSystems-roots",+ "file": "plugins/cordova-plugin-file/www/fileSystems-roots.js",+ "pluginId": "cordova-plugin-file",+ "runs": true+ },+ {+ "id": "cordova-plugin-file.fileSystemPaths",+ "file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",+ "pluginId": "cordova-plugin-file",+ "merges": [+ "cordova"+ ],+ "runs": true+ },+ {+ "id": "cordova-plugin-media.MediaError",+ "file": "plugins/cordova-plugin-media/www/MediaError.js",+ "pluginId": "cordova-plugin-media",+ "clobbers": [+ "window.MediaError"+ ]+ },+ {+ "id": "cordova-plugin-media.Media",+ "file": "plugins/cordova-plugin-media/www/Media.js",+ "pluginId": "cordova-plugin-media",+ "clobbers": [+ "window.Media"+ ]+ }+];+module.exports.metadata =+// TOP OF METADATA+{+ "cordova-plugin-camera": "4.0.3",+ "cordova-plugin-device": "2.0.2",+ "cordova-plugin-file": "6.0.1",+ "cordova-plugin-media": "5.0.2",+ "cordova-plugin-whitelist": "1.3.3"+};+// BOTTOM OF METADATA});\ No newline at end of filediff --git a/cordova/platforms/android/platform_www/plugins/cordova-plugin-media/www/Media.js b/cordova/platforms/android/platform_www/plugins/cordova-plugin-media/www/Media.jsnew file mode 100644index 000000000..2ca4b2d28--- /dev/null+++ b/cordova/platforms/android/platform_www/plugins/cordova-plugin-media/www/Media.js@@ -0,0 +1,260 @@+cordova.define("cordova-plugin-media.Media", function(require, exports, module) {+/*+ *+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ *+*/++var argscheck = require('cordova/argscheck'),+ utils = require('cordova/utils'),+ exec = require('cordova/exec');++var mediaObjects = {};++/**+ * This class provides access to the device media, interfaces to both sound and video+ *+ * @constructor+ * @param src The file name or url to play+ * @param successCallback The callback to be called when the file is done playing or recording.+ * successCallback()+ * @param errorCallback The callback to be called if there is an error.+ * errorCallback(int errorCode) - OPTIONAL+ * @param statusCallback The callback to be called when media status has changed.+ * statusCallback(int statusCode) - OPTIONAL+ */+var Media = function(src, successCallback, errorCallback, statusCallback) {+ argscheck.checkArgs('sFFF', 'Media', arguments);+ this.id = utils.createUUID();+ mediaObjects[this.id] = this;+ this.src = src;+ this.successCallback = successCallback;+ this.errorCallback = errorCallback;+ this.statusCallback = statusCallback;+ this._duration = -1;+ this._position = -1;+ exec(null, this.errorCallback, "Media", "create", [this.id, this.src]);+};++// Media messages+Media.MEDIA_STATE = 1;+Media.MEDIA_DURATION = 2;+Media.MEDIA_POSITION = 3;+Media.MEDIA_ERROR = 9;++// Media states+Media.MEDIA_NONE = 0;+Media.MEDIA_STARTING = 1;+Media.MEDIA_RUNNING = 2;+Media.MEDIA_PAUSED = 3;+Media.MEDIA_STOPPED = 4;+Media.MEDIA_MSG = ["None", "Starting", "Running", "Paused", "Stopped"];++// "static" function to return existing objs.+Media.get = function(id) {+ return mediaObjects[id];+};++/**+ * Start or resume playing audio file.+ */+Media.prototype.play = function(options) {+ exec(null, null, "Media", "startPlayingAudio", [this.id, this.src, options]);+};++/**+ * Stop playing audio file.+ */+Media.prototype.stop = function() {+ var me = this;+ exec(function() {+ me._position = 0;+ }, this.errorCallback, "Media", "stopPlayingAudio", [this.id]);+};++/**+ * Seek or jump to a new time in the track..+ */+Media.prototype.seekTo = function(milliseconds) {+ var me = this;+ exec(function(p) {+ me._position = p;+ }, this.errorCallback, "Media", "seekToAudio", [this.id, milliseconds]);+};++/**+ * Pause playing audio file.+ */+Media.prototype.pause = function() {+ exec(null, this.errorCallback, "Media", "pausePlayingAudio", [this.id]);+};++/**+ * Get duration of an audio file.+ * The duration is only set for audio that is playing, paused or stopped.+ *+ * @return duration or -1 if not known.+ */+Media.prototype.getDuration = function() {+ return this._duration;+};++/**+ * Get position of audio.+ */+Media.prototype.getCurrentPosition = function(success, fail) {+ var me = this;+ exec(function(p) {+ me._position = p;+ success(p);+ }, fail, "Media", "getCurrentPositionAudio", [this.id]);+};++/**+ * Start recording audio file.+ */+Media.prototype.startRecord = function() {+ exec(null, this.errorCallback, "Media", "startRecordingAudio", [this.id, this.src]);+};++/**+ * Stop recording audio file.+ */+Media.prototype.stopRecord = function() {+ exec(null, this.errorCallback, "Media", "stopRecordingAudio", [this.id]);+};++/**+ * Pause recording audio file.+ */+Media.prototype.pauseRecord = function() {+ exec(null, this.errorCallback, "Media", "pauseRecordingAudio", [this.id]);+};++/**+* Resume recording audio file.+*/+Media.prototype.resumeRecord = function() {+ exec(null, this.errorCallback, "Media", "resumeRecordingAudio", [this.id]);+};++/**+ * Release the resources.+ */+Media.prototype.release = function() {+ exec(null, this.errorCallback, "Media", "release", [this.id]);+};++/**+ * Adjust the volume.+ */+Media.prototype.setVolume = function(volume) {+ exec(null, null, "Media", "setVolume", [this.id, volume]);+};++/**+ * Adjust the playback rate.+ */+Media.prototype.setRate = function(rate) {+ if (cordova.platformId === 'ios'){+ exec(null, null, "Media", "setRate", [this.id, rate]);+ } else {+ console.warn('media.setRate method is currently not supported for', cordova.platformId, 'platform.');+ }+};++/**+ * Get amplitude of audio.+ */+Media.prototype.getCurrentAmplitude = function(success, fail) {+ exec(function(p) {+ success(p);+ }, fail, "Media", "getCurrentAmplitudeAudio", [this.id]);+};++/**+ * Audio has status update.+ * PRIVATE+ *+ * @param id The media object id (string)+ * @param msgType The 'type' of update this is+ * @param value Use of value is determined by the msgType+ */+Media.onStatus = function(id, msgType, value) {++ var media = mediaObjects[id];++ if (media) {+ switch(msgType) {+ case Media.MEDIA_STATE :+ if (media.statusCallback) {+ media.statusCallback(value);+ }+ if (value == Media.MEDIA_STOPPED) {+ if (media.successCallback) {+ media.successCallback();+ }+ }+ break;+ case Media.MEDIA_DURATION :+ media._duration = value;+ break;+ case Media.MEDIA_ERROR :+ if (media.errorCallback) {+ media.errorCallback(value);+ }+ break;+ case Media.MEDIA_POSITION :+ media._position = Number(value);+ break;+ default :+ if (console.error) {+ console.error("Unhandled Media.onStatus :: " + msgType);+ }+ break;+ }+ } else if (console.error) {+ console.error("Received Media.onStatus callback for unknown media :: " + id);+ }++};++module.exports = Media;++function onMessageFromNative(msg) {+ if (msg.action == 'status') {+ Media.onStatus(msg.status.id, msg.status.msgType, msg.status.value);+ } else {+ throw new Error('Unknown media action' + msg.action);+ }+}++if (cordova.platformId === 'android' || cordova.platformId === 'amazon-fireos' || cordova.platformId === 'windowsphone') {++ var channel = require('cordova/channel');++ channel.createSticky('onMediaPluginReady');+ channel.waitForInitialization('onMediaPluginReady');++ channel.onCordovaReady.subscribe(function() {+ exec(onMessageFromNative, undefined, 'Media', 'messageChannel', []);+ channel.initializationComplete('onMediaPluginReady');+ });+}++});diff --git a/cordova/platforms/android/platform_www/plugins/cordova-plugin-media/www/MediaError.js b/cordova/platforms/android/platform_www/plugins/cordova-plugin-media/www/MediaError.jsnew file mode 100644index 000000000..6c31335af--- /dev/null+++ b/cordova/platforms/android/platform_www/plugins/cordova-plugin-media/www/MediaError.js@@ -0,0 +1,58 @@+cordova.define("cordova-plugin-media.MediaError", function(require, exports, module) {+/*+ *+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ *+*/++/**+ * This class contains information about any Media errors.+*/+/*+ According to :: http://dev.w3.org/html5/spec-author-view/video.html#mediaerror+ We should never be creating these objects, we should just implement the interface+ which has 1 property for an instance, 'code'++ instead of doing :+ errorCallbackFunction( new MediaError(3,'msg') );+we should simply use a literal :+ errorCallbackFunction( {'code':3} );+ */++ var _MediaError = window.MediaError;+++if(!_MediaError) {+ window.MediaError = _MediaError = function(code, msg) {+ this.code = (typeof code != 'undefined') ? code : null;+ this.message = msg || ""; // message is NON-standard! do not use!+ };+}++_MediaError.MEDIA_ERR_NONE_ACTIVE = _MediaError.MEDIA_ERR_NONE_ACTIVE || 0;+_MediaError.MEDIA_ERR_ABORTED = _MediaError.MEDIA_ERR_ABORTED || 1;+_MediaError.MEDIA_ERR_NETWORK = _MediaError.MEDIA_ERR_NETWORK || 2;+_MediaError.MEDIA_ERR_DECODE = _MediaError.MEDIA_ERR_DECODE || 3;+_MediaError.MEDIA_ERR_NONE_SUPPORTED = _MediaError.MEDIA_ERR_NONE_SUPPORTED || 4;+// TODO: MediaError.MEDIA_ERR_NONE_SUPPORTED is legacy, the W3 spec now defines it as below.+// as defined by http://dev.w3.org/html5/spec-author-view/video.html#error-codes+_MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = _MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED || 4;++module.exports = _MediaError;++});diff --git a/cordova/yarn.lock b/cordova/yarn.lockindex 858de1b34..ad46c1210 100644--- a/cordova/yarn.lock+++ b/cordova/yarn.lock@@ -279,6 +279,11 @@ cordova-plugin-file@^6.0.1:resolved "https://registry.yarnpkg.com/cordova-plugin-file/-/cordova-plugin-file-6.0.1.tgz#49606b8c15a5688d4728f92e4a7325a061de07f5"integrity sha1-SWBrjBWlaI1HKPkuSnMloGHeB/U=+cordova-plugin-media@^5.0.2:+ version "5.0.2"+ resolved "https://registry.yarnpkg.com/cordova-plugin-media/-/cordova-plugin-media-5.0.2.tgz#3345769c07e6a46a71c97e1bb434dacca5c8d80b"+ integrity sha1-M0V2nAfmpGpxyX4btDTazKXI2As=+cordova-plugin-whitelist@^1.3.3:version "1.3.3"resolved "https://registry.yarnpkg.com/cordova-plugin-whitelist/-/cordova-plugin-whitelist-1.3.3.tgz#b5e85ecdbbfe5aeded40a1bf4ee2372e67d96fb4"