From 9a477c7f54dac4b763f1c926fe202ae0e5c136ca Mon Sep 17 00:00:00 2001 From: umasoodch Date: Tue, 14 Sep 2021 12:12:21 +0300 Subject: [PATCH 1/4] Added cordova-hms-plugin folder --- .../CordovaHMSGMSCheckPlugin/plugin.xml | 29 +++ .../scripts/after_prepare.js | 37 ++++ .../scripts/android/after_plugin_install.js | 9 + .../android/before_plugin_uninstall.js | 7 + .../scripts/android/helper.js | 131 +++++++++++++ .../scripts/lib/utilities.js | 93 +++++++++ .../src/android/CordovaHMSGMSCheckPlugin.java | 88 +++++++++ .../src/android/build.gradle | 29 +++ .../CordovaHMSLocationPlugin/plugin.xml | 29 +++ .../scripts/after_prepare.js | 38 ++++ .../scripts/android/after_plugin_install.js | 9 + .../android/before_plugin_uninstall.js | 7 + .../scripts/android/helper.js | 117 +++++++++++ .../scripts/lib/utilities.js | 88 +++++++++ .../src/android/CordovaHMSLocationPlugin.java | 185 ++++++++++++++++++ .../src/android/build.gradle | 29 +++ .../CordovaHMSPushPlugin/plugin.xml | 38 ++++ .../scripts/after_prepare.js | 38 ++++ .../scripts/android/after_plugin_install.js | 9 + .../android/before_plugin_uninstall.js | 7 + .../scripts/android/helper.js | 117 +++++++++++ .../scripts/lib/utilities.js | 88 +++++++++ .../src/android/CordovaHMSPushPlugin.java | 112 +++++++++++ .../src/android/MessageService.java | 32 +++ .../src/android/build.gradle | 29 +++ 25 files changed, 1395 insertions(+) create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/plugin.xml create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/after_prepare.js create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/android/after_plugin_install.js create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/android/before_plugin_uninstall.js create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/android/helper.js create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/lib/utilities.js create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/src/android/CordovaHMSGMSCheckPlugin.java create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/src/android/build.gradle create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/plugin.xml create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/after_prepare.js create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/android/after_plugin_install.js create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/android/before_plugin_uninstall.js create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/android/helper.js create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/lib/utilities.js create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/src/android/CordovaHMSLocationPlugin.java create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/src/android/build.gradle create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/plugin.xml create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/after_prepare.js create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/android/after_plugin_install.js create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/android/before_plugin_uninstall.js create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/android/helper.js create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/lib/utilities.js create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/src/android/CordovaHMSPushPlugin.java create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/src/android/MessageService.java create mode 100644 Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/src/android/build.gradle diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/plugin.xml b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/plugin.xml new file mode 100644 index 00000000..63d1d203 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/plugin.xml @@ -0,0 +1,29 @@ + + + CordovaHMSGMSCheckPlugin + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/after_prepare.js b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/after_prepare.js new file mode 100644 index 00000000..b3da28cf --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/after_prepare.js @@ -0,0 +1,37 @@ +#!/usr/bin/env node + +"use strict"; + +/** + * This hook makes sure projects using [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) + * will build properly and have the required key files copied to the proper destinations when the app is build on Ionic Cloud using the package command. + * Credits: https://github.com/arnesson. + */ +var fs = require("fs"); +var path = require("path"); +var utilities = require("./lib/utilities"); + +var config = fs.readFileSync("config.xml").toString(); +var name = utilities.getValue(config, "name"); + +var ANDROID_DIR = "platforms/android"; + +var PLATFORM = { + ANDROID: { + dest: [ANDROID_DIR + "/app/agconnect-services.json"], + src: ["agconnect-services.json"], + }, +}; + +module.exports = function (context) { + //get platform from the context supplied by cordova + var platforms = context.opts.platforms; + // Copy key files to their platform specific folders + if ( + platforms.indexOf("android") !== -1 && + utilities.directoryExists(ANDROID_DIR) + ) { + console.log("Preparing HMS GMS Check Kit on Android"); + // utilities.copyKey(PLATFORM.ANDROID); + } +}; diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/android/after_plugin_install.js b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/android/after_plugin_install.js new file mode 100644 index 00000000..09e73419 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/android/after_plugin_install.js @@ -0,0 +1,9 @@ +var helper = require('./helper'); + +module.exports = function(context) { + + // Modify the Gradle build file to add a task that will upload the debug symbols + // at build time. + helper.restoreRootBuildGradle(); + helper.modifyRootBuildGradle(); +}; \ No newline at end of file diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/android/before_plugin_uninstall.js b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/android/before_plugin_uninstall.js new file mode 100644 index 00000000..9c32e552 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/android/before_plugin_uninstall.js @@ -0,0 +1,7 @@ +var helper = require('./helper'); + +module.exports = function(context) { + + // Remove the Gradle modifications that were added when the plugin was installed. + helper.restoreRootBuildGradle(); +}; \ No newline at end of file diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/android/helper.js b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/android/helper.js new file mode 100644 index 00000000..cd4b8111 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/android/helper.js @@ -0,0 +1,131 @@ +var fs = require("fs"); +var path = require("path"); + +function rootBuildGradleExists() { + var target = path.join("platforms", "android", "build.gradle"); + return fs.existsSync(target); +} + +/* + * Helper function to read the build.gradle that sits at the root of the project + */ +function readRootBuildGradle() { + var target = path.join("platforms", "android", "build.gradle"); + return fs.readFileSync(target, "utf-8"); +} + +/* + * Added a dependency on 'com.google.gms' based on the position of the know 'com.android.tools.build' dependency in the build.gradle + */ +function addDependencies(buildGradle) { + // find the known line to match + var match = buildGradle.match( + /^(\s*)classpath 'com.android.tools.build(.*)/m + ); + var whitespace = match[1]; + + // modify the line to add the necessary dependencies + var agcDependency = + whitespace + "classpath 'com.huawei.agconnect:agcp:1.2.0.300'"; + + var modifiedLine = match[0] + "\n" + agcDependency; + + // modify the actual line + return buildGradle.replace( + /^(\s*)classpath 'com.android.tools.build(.*)/m, + modifiedLine + ); +} + +/* + * Add 'google()' and Crashlytics to the repository repo list + */ +function addRepos(buildGradle) { + // find the known line to match + var match = buildGradle.match(/^(\s*)jcenter\(\)/m); + var whitespace = match[1]; + + // modify the line to add the necessary repo + var huaweiMavenRepo = + whitespace + "maven { url 'http://developer.huawei.com/repo/' }"; + var modifiedLine = match[0] + "\n" + huaweiMavenRepo; + + // modify the actual line + buildGradle = buildGradle.replace(/^(\s*)jcenter\(\)/m, modifiedLine); + + // update the all projects grouping + var allProjectsIndex = buildGradle.indexOf("allprojects"); + if (allProjectsIndex > 0) { + // split the string on allprojects because jcenter is in both groups and we need to modify the 2nd instance + var firstHalfOfFile = buildGradle.substring(0, allProjectsIndex); + var secondHalfOfFile = buildGradle.substring(allProjectsIndex); + + // Add google() to the allprojects section of the string + match = secondHalfOfFile.match(/^(\s*)jcenter\(\)/m); + var huaweiMavenRepo = + whitespace + "maven { url 'http://developer.huawei.com/repo/' }"; + modifiedLine = match[0] + "\n" + huaweiMavenRepo; + // modify the part of the string that is after 'allprojects' + secondHalfOfFile = secondHalfOfFile.replace( + /^(\s*)jcenter\(\)/m, + modifiedLine + ); + + // recombine the modified line + buildGradle = firstHalfOfFile + secondHalfOfFile; + } else { + // this should not happen, but if it does, we should try to add the dependency to the buildscript + match = buildGradle.match(/^(\s*)jcenter\(\)/m); + var huaweiMavenRepo = + whitespace + "maven { url 'http://developer.huawei.com/repo/' }"; + modifiedLine = match[0] + "\n" + huaweiMavenRepo; + // modify the part of the string that is after 'allprojects' + buildGradle = buildGradle.replace(/^(\s*)jcenter\(\)/m, modifiedLine); + } + + return buildGradle; +} + +/* + * Helper function to write to the build.gradle that sits at the root of the project + */ +function writeRootBuildGradle(contents) { + var target = path.join("platforms", "android", "build.gradle"); + fs.writeFileSync(target, contents); +} + +module.exports = { + modifyRootBuildGradle: function () { + // be defensive and don't crash if the file doesn't exist + if (!rootBuildGradleExists) { + return; + } + + var buildGradle = readRootBuildGradle(); + + // Add Google Play Services Dependency + buildGradle = addDependencies(buildGradle); + + // Add Google's Maven Repo + buildGradle = addRepos(buildGradle); + + writeRootBuildGradle(buildGradle); + }, + + restoreRootBuildGradle: function () { + // be defensive and don't crash if the file doesn't exist + if (!rootBuildGradleExists) { + return; + } + + var buildGradle = readRootBuildGradle(); + + // remove any lines we added + buildGradle = buildGradle.replace( + /(?:^|\r?\n)(.*)com.huawei.cordovahmsgmscheckplugin*?(?=$|\r?\n)/g, + "" + ); + + writeRootBuildGradle(buildGradle); + }, +}; diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/lib/utilities.js b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/lib/utilities.js new file mode 100644 index 00000000..89ecc01f --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/scripts/lib/utilities.js @@ -0,0 +1,93 @@ +/** + * Utilities and shared functionality for the build hooks. + */ +var fs = require("fs"); +var path = require("path"); + +fs.ensureDirSync = function (dir) { + if (!fs.existsSync(dir)) { + dir.split(path.sep).reduce(function (currentPath, folder) { + currentPath += folder + path.sep; + if (!fs.existsSync(currentPath)) { + fs.mkdirSync(currentPath); + } + return currentPath; + }, ""); + } +}; + +module.exports = { + /** + * Used to get the name of the application as defined in the config.xml. + * + * @param {object} context - The Cordova context. + * @returns {string} The value of the name element in config.xml. + */ + getAppName: function (context) { + var ConfigParser = context.requireCordovaModule("cordova-lib").configparser; + var config = new ConfigParser("config.xml"); + return config.name(); + }, + + /** + * The ID of the plugin; this should match the ID in plugin.xml. + */ + getPluginId: function () { + return "com.huawei.cordovahmsgmscheckplugin"; + }, + + copyKey: function (platform) { + for (var i = 0; i < platform.src.length; i++) { + var file = platform.src[i]; + if (this.fileExists(file)) { + try { + var contents = fs.readFileSync(file).toString(); + + try { + platform.dest.forEach(function (destinationPath) { + var folder = destinationPath.substring( + 0, + destinationPath.lastIndexOf("/") + ); + fs.ensureDirSync(folder); + fs.writeFileSync(destinationPath, contents); + }); + } catch (e) { + // skip + } + } catch (err) { + console.log(err); + } + + break; + } + } + }, + + getValue: function (config, name) { + var value = config.match( + new RegExp("<" + name + "(.*?)>(.*?)", "i") + ); + if (value && value[2]) { + return value[2]; + } else { + return null; + } + }, + + fileExists: function (path) { + try { + return fs.statSync(path).isFile(); + } catch (e) { + return false; + } + }, + + directoryExists: function (path) { + try { + return fs.statSync(path).isDirectory(); + } catch (e) { + return false; + } + }, +}; diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/src/android/CordovaHMSGMSCheckPlugin.java b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/src/android/CordovaHMSGMSCheckPlugin.java new file mode 100644 index 00000000..86307e6b --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/src/android/CordovaHMSGMSCheckPlugin.java @@ -0,0 +1,88 @@ +package com.huawei.cordovahmsgmscheckplugin; + +import android.content.Context; +import android.content.Intent; +import android.util.Log; + +import com.huawei.hms.api.HuaweiApiAvailability; +// import com.google.android.gms.common.GoogleApiAvailability; + +import org.apache.cordova.CordovaInterface; +import org.apache.cordova.CordovaInterfaceImpl; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.CallbackContext; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * This class echoes a string called from JavaScript. + */ +public class CordovaHMSGMSCheckPlugin extends CordovaPlugin { + + private static final String TAG = CordovaHMSGMSCheckPlugin.class.getSimpleName(); + private CallbackContext mCallbackContext; + + @Override + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { + switch (action) { + case "isHmsAvailable": + mCallbackContext = callbackContext; + cordova.getThreadPool().execute(this::isHmsAvailable); + return true; + case "isGmsAvailable": + // mCallbackContext = callbackContext; + // cordova.getThreadPool().execute(this::isGmsAvailable); + return false; + } + return false; + } + + private void isHmsAvailable() { + boolean isAvailable = false; + Context context = cordova.getContext(); + if (null != cordova.getContext()) { + int result = HuaweiApiAvailability.getInstance().isHuaweiMobileServicesAvailable(context); + isAvailable = (com.huawei.hms.api.ConnectionResult.SUCCESS == result); + } + Log.i("Cordova", "isHmsAvailable: " + isAvailable); + String msg = "false"; + if(isAvailable){ + msg = "true"; + } + outputCallbackContext(0, msg); + } + + // private void isGmsAvailable() { + // boolean isAvailable = false; + // Context context = cordova.getContext(); + // if (null != context) { + // int result = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context); + // isAvailable = (com.google.android.gms.common.ConnectionResult.SUCCESS == result); + // } + // Log.i("Cordova", "isGmsAvailable: " + isAvailable); + // String msg = "false"; + // if(isAvailable){ + // msg = "true"; + // } + // outputCallbackContext(0, msg); + // } + + /** + * @param type 0-success,1-error + * @param msg message + */ + private void outputCallbackContext(int type, String msg) { + if (mCallbackContext != null) { + switch (type) { + case 0: + mCallbackContext.success(msg); + break; + case 1: + mCallbackContext.error(msg); + break; + } + } + } +} diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/src/android/build.gradle b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/src/android/build.gradle new file mode 100644 index 00000000..30dda1bf --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSGMSCheckPlugin/src/android/build.gradle @@ -0,0 +1,29 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + repositories { + google() + jcenter() + // huawei maven + maven { url 'http://developer.huawei.com/repo/' } + } + dependencies { + classpath 'com.android.tools.build:gradle:3.2.0' + // classpath 'com.huawei.agconnect:agcp:1.2.0.300' + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + jcenter() + // huawei maven + maven { url 'http://developer.huawei.com/repo/' } + } +} + +cdvPluginPostBuildExtras.add({ + apply plugin: 'com.huawei.agconnect' +}) diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/plugin.xml b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/plugin.xml new file mode 100644 index 00000000..126ffbc8 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/plugin.xml @@ -0,0 +1,29 @@ + + + CordovaHMSLocationPlugin + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/after_prepare.js b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/after_prepare.js new file mode 100644 index 00000000..adc5a480 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/after_prepare.js @@ -0,0 +1,38 @@ +#!/usr/bin/env node + +'use strict'; + +/** + * This hook makes sure projects using [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) + * will build properly and have the required key files copied to the proper destinations when the app is build on Ionic Cloud using the package command. + * Credits: https://github.com/arnesson. + */ +var fs = require('fs'); +var path = require('path'); +var utilities = require("./lib/utilities"); + +var config = fs.readFileSync('config.xml').toString(); +var name = utilities.getValue(config, 'name'); + +var ANDROID_DIR = 'platforms/android'; + +var PLATFORM = { + ANDROID: { + dest: [ + ANDROID_DIR + '/app/agconnect-services.json' + ], + src: [ + 'agconnect-services.json' + ], + } +}; + +module.exports = function (context) { + //get platform from the context supplied by cordova + var platforms = context.opts.platforms; + // Copy key files to their platform specific folders + if (platforms.indexOf('android') !== -1 && utilities.directoryExists(ANDROID_DIR)) { + console.log('Preparing HMS Location Kit on Android'); + utilities.copyKey(PLATFORM.ANDROID); + } +}; \ No newline at end of file diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/android/after_plugin_install.js b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/android/after_plugin_install.js new file mode 100644 index 00000000..09e73419 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/android/after_plugin_install.js @@ -0,0 +1,9 @@ +var helper = require('./helper'); + +module.exports = function(context) { + + // Modify the Gradle build file to add a task that will upload the debug symbols + // at build time. + helper.restoreRootBuildGradle(); + helper.modifyRootBuildGradle(); +}; \ No newline at end of file diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/android/before_plugin_uninstall.js b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/android/before_plugin_uninstall.js new file mode 100644 index 00000000..9c32e552 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/android/before_plugin_uninstall.js @@ -0,0 +1,7 @@ +var helper = require('./helper'); + +module.exports = function(context) { + + // Remove the Gradle modifications that were added when the plugin was installed. + helper.restoreRootBuildGradle(); +}; \ No newline at end of file diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/android/helper.js b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/android/helper.js new file mode 100644 index 00000000..da715c24 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/android/helper.js @@ -0,0 +1,117 @@ +var fs = require("fs"); +var path = require("path"); + +function rootBuildGradleExists() { + var target = path.join("platforms", "android", "build.gradle"); + return fs.existsSync(target); +} + +/* + * Helper function to read the build.gradle that sits at the root of the project + */ +function readRootBuildGradle() { + var target = path.join("platforms", "android", "build.gradle"); + return fs.readFileSync(target, "utf-8"); +} + +/* + * Added a dependency on 'com.google.gms' based on the position of the know 'com.android.tools.build' dependency in the build.gradle + */ +function addDependencies(buildGradle) { + // find the known line to match + var match = buildGradle.match(/^(\s*)classpath 'com.android.tools.build(.*)/m); + var whitespace = match[1]; + + // modify the line to add the necessary dependencies + var agcDependency = whitespace + 'classpath \'com.huawei.agconnect:agcp:1.2.0.300\'' + + var modifiedLine = match[0] + '\n' + agcDependency; + + // modify the actual line + return buildGradle.replace(/^(\s*)classpath 'com.android.tools.build(.*)/m, modifiedLine); +} + +/* + * Add 'google()' and Crashlytics to the repository repo list + */ +function addRepos(buildGradle) { + // find the known line to match + var match = buildGradle.match(/^(\s*)jcenter\(\)/m); + var whitespace = match[1]; + + // modify the line to add the necessary repo + var huaweiMavenRepo = whitespace + 'maven { url \'http://developer.huawei.com/repo/\' }' + var modifiedLine = match[0] + '\n' + huaweiMavenRepo; + + // modify the actual line + buildGradle = buildGradle.replace(/^(\s*)jcenter\(\)/m, modifiedLine); + + // update the all projects grouping + var allProjectsIndex = buildGradle.indexOf('allprojects'); + if (allProjectsIndex > 0) { + // split the string on allprojects because jcenter is in both groups and we need to modify the 2nd instance + var firstHalfOfFile = buildGradle.substring(0, allProjectsIndex); + var secondHalfOfFile = buildGradle.substring(allProjectsIndex); + + // Add google() to the allprojects section of the string + match = secondHalfOfFile.match(/^(\s*)jcenter\(\)/m); + var huaweiMavenRepo = whitespace + 'maven { url \'http://developer.huawei.com/repo/\' }' + modifiedLine = match[0] + '\n' + huaweiMavenRepo; + // modify the part of the string that is after 'allprojects' + secondHalfOfFile = secondHalfOfFile.replace(/^(\s*)jcenter\(\)/m, modifiedLine); + + // recombine the modified line + buildGradle = firstHalfOfFile + secondHalfOfFile; + } else { + // this should not happen, but if it does, we should try to add the dependency to the buildscript + match = buildGradle.match(/^(\s*)jcenter\(\)/m); + var huaweiMavenRepo = whitespace + 'maven { url \'http://developer.huawei.com/repo/\' }' + modifiedLine = match[0] + '\n' + huaweiMavenRepo; + // modify the part of the string that is after 'allprojects' + buildGradle = buildGradle.replace(/^(\s*)jcenter\(\)/m, modifiedLine); + } + + return buildGradle; +} + +/* + * Helper function to write to the build.gradle that sits at the root of the project + */ +function writeRootBuildGradle(contents) { + var target = path.join("platforms", "android", "build.gradle"); + fs.writeFileSync(target, contents); +} + +module.exports = { + + modifyRootBuildGradle: function() { + // be defensive and don't crash if the file doesn't exist + if (!rootBuildGradleExists) { + return; + } + + var buildGradle = readRootBuildGradle(); + + // Add Google Play Services Dependency + buildGradle = addDependencies(buildGradle); + + // Add Google's Maven Repo + buildGradle = addRepos(buildGradle); + + writeRootBuildGradle(buildGradle); + }, + + restoreRootBuildGradle: function() { + // be defensive and don't crash if the file doesn't exist + if (!rootBuildGradleExists) { + return; + } + + var buildGradle = readRootBuildGradle(); + + // remove any lines we added + buildGradle = buildGradle.replace(/(?:^|\r?\n)(.*)com.huawei.cordovahmspushplugin*?(?=$|\r?\n)/g, ''); + + writeRootBuildGradle(buildGradle); + } +}; \ No newline at end of file diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/lib/utilities.js b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/lib/utilities.js new file mode 100644 index 00000000..015f6831 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/scripts/lib/utilities.js @@ -0,0 +1,88 @@ +/** + * Utilities and shared functionality for the build hooks. + */ +var fs = require('fs'); +var path = require("path"); + +fs.ensureDirSync = function (dir) { + if (!fs.existsSync(dir)) { + dir.split(path.sep).reduce(function (currentPath, folder) { + currentPath += folder + path.sep; + if (!fs.existsSync(currentPath)) { + fs.mkdirSync(currentPath); + } + return currentPath; + }, ''); + } +}; + +module.exports = { + /** + * Used to get the name of the application as defined in the config.xml. + * + * @param {object} context - The Cordova context. + * @returns {string} The value of the name element in config.xml. + */ + getAppName: function (context) { + var ConfigParser = context.requireCordovaModule("cordova-lib").configparser; + var config = new ConfigParser("config.xml"); + return config.name(); + }, + + /** + * The ID of the plugin; this should match the ID in plugin.xml. + */ + getPluginId: function () { + return "com.huawei.cordovahmspushplugin"; + }, + + copyKey: function (platform) { + for (var i = 0; i < platform.src.length; i++) { + var file = platform.src[i]; + if (this.fileExists(file)) { + try { + var contents = fs.readFileSync(file).toString(); + + try { + platform.dest.forEach(function (destinationPath) { + var folder = destinationPath.substring(0, destinationPath.lastIndexOf('/')); + fs.ensureDirSync(folder); + fs.writeFileSync(destinationPath, contents); + }); + } catch (e) { + // skip + } + } catch (err) { + console.log(err); + } + + break; + } + } + }, + + getValue: function (config, name) { + var value = config.match(new RegExp('<' + name + '(.*?)>(.*?)', 'i')); + if (value && value[2]) { + return value[2] + } else { + return null + } + }, + + fileExists: function (path) { + try { + return fs.statSync(path).isFile(); + } catch (e) { + return false; + } + }, + + directoryExists: function (path) { + try { + return fs.statSync(path).isDirectory(); + } catch (e) { + return false; + } + } +}; \ No newline at end of file diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/src/android/CordovaHMSLocationPlugin.java b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/src/android/CordovaHMSLocationPlugin.java new file mode 100644 index 00000000..caef5fd0 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/src/android/CordovaHMSLocationPlugin.java @@ -0,0 +1,185 @@ +package com.huawei.cordovahmslocationplugin; + +import android.Manifest; +import android.content.IntentSender; +import android.location.Location; +import android.os.Build; +import android.os.Looper; +import android.util.Log; + +import com.huawei.hms.common.ApiException; +import com.huawei.hms.common.ResolvableApiException; +import com.huawei.hms.location.FusedLocationProviderClient; +import com.huawei.hms.location.LocationCallback; +import com.huawei.hms.location.LocationRequest; +import com.huawei.hms.location.LocationResult; +import com.huawei.hms.location.LocationServices; +import com.huawei.hms.location.LocationSettingsRequest; +import com.huawei.hms.location.LocationSettingsStatusCodes; +import com.huawei.hms.location.SettingsClient; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.PluginResult; +import org.json.JSONArray; +import org.json.JSONException; + +/** + * + */ +public class CordovaHMSLocationPlugin extends CordovaPlugin { + + private static final String TAG = CordovaHMSLocationPlugin.class.getSimpleName(); + + private FusedLocationProviderClient fusedLocationProviderClient; + private LocationRequest mLocationRequest; + private LocationCallback mLocationCallback; + private CallbackContext mCallbackContext; + + @Override + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { + requestPermission(); + if (fusedLocationProviderClient == null) { + fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(cordova.getContext()); + } + switch (action) { + case "requestLocation": + this.setLocationRequest(); + this.setLocationCallback(); + this.checkLocationSetting(callbackContext); + return true; + case "removeLocation": + this.stopLocation(); + return true; + case "getLastlocation": + this.getLastlocation(callbackContext); + return true; + default: + return false; + } + } + + private void returnLocation(Location location) { + if (mCallbackContext != null) { + Log.d(TAG, "returnLocation"); + String message = location.getLatitude() + "," + location.getLongitude(); + PluginResult result = new PluginResult(PluginResult.Status.OK, message); + result.setKeepCallback(true); + mCallbackContext.sendPluginResult(result); + } + } + + private void getLastlocation(CallbackContext callbackContext) { + fusedLocationProviderClient.getLastLocation().addOnSuccessListener(location -> { + Log.d(TAG, "getLastlocation success"); + if (location == null) { + return; + } + // Location对象的处理逻辑 + String message = location.getLatitude() + "," + location.getLongitude(); + callbackContext.success(message); + }).addOnFailureListener(e -> { + // 异常处理逻辑 + callbackContext.error("getLastlocation fail"); + }); + } + + private void stopLocation() { + if (fusedLocationProviderClient == null) { + Log.d(TAG, "fusedLocationProviderClient is null"); + return; + } + // 注意:停止位置更新时,mLocationCallback必须与requestLocationUpdates方法中的LocationCallback参数为同一对象。 + fusedLocationProviderClient.removeLocationUpdates(mLocationCallback) + .addOnSuccessListener(aVoid -> { + // 停止位置更新成功 + Log.d(TAG, "stop success"); + mCallbackContext = null; + }) + .addOnFailureListener(e -> { + // 停止位置更新失败 + Log.d(TAG, "stop fail"); + }); + } + + private void setLocationCallback() { + mLocationCallback = new LocationCallback() { + @Override + public void onLocationResult(LocationResult locationResult) { + if (locationResult != null) { + //处理位置回调结果 + if (mLocationCallback != null) { + Log.d(TAG, "onLocationResult"); + Location location = locationResult.getLocations().get(0); + returnLocation(location); + } + } + } + }; + } + + private void setLocationRequest() { + mLocationRequest = new LocationRequest(); + // 设置位置更新的间隔(毫秒为单位) + mLocationRequest.setInterval(10000); +// mLocationRequest.setNumUpdates(1); + // 设置权重 + mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); + } + + private void checkLocationSetting(CallbackContext callbackContext) { + SettingsClient settingsClient = LocationServices.getSettingsClient(cordova.getContext()); + LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); + builder.addLocationRequest(mLocationRequest); + LocationSettingsRequest locationSettingsRequest = builder.build(); + // 检查设备定位设置 + settingsClient.checkLocationSettings(locationSettingsRequest) + .addOnSuccessListener(locationSettingsResponse -> { + + // 设置满足定位条件,再发起位置请求 + fusedLocationProviderClient + .requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper()) + .addOnSuccessListener(aVoid -> { + // 接口调用成功的处理 + Log.d(TAG, "request success"); + mCallbackContext = callbackContext; + }); + }) + .addOnFailureListener(e -> { + // 设置不满足定位条件 + int statusCode = ((ApiException) e).getStatusCode(); + switch (statusCode) { + case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: + try { + ResolvableApiException rae = (ResolvableApiException) e; + // 调用startResolutionForResult可以弹窗提示用户打开相应权限 + rae.startResolutionForResult(cordova.getActivity(), 0); + } catch (IntentSender.SendIntentException sie) { + Log.d(TAG, sie.getMessage()); + } + break; + } + }); + } + + private void requestPermission() { + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) { + Log.i(TAG, "sdk < 29 Q"); + if (!cordova.hasPermission(Manifest.permission.ACCESS_FINE_LOCATION) + || !cordova.hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION)) { + String[] strings = + {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}; + cordova.requestPermissions(this, 1, strings); + } + } else { + if (!cordova.hasPermission(Manifest.permission.ACCESS_FINE_LOCATION) + || !cordova.hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION) + || !cordova.hasPermission("android.permission.ACCESS_BACKGROUND_LOCATION")) { + String[] strings = {android.Manifest.permission.ACCESS_FINE_LOCATION, + android.Manifest.permission.ACCESS_COARSE_LOCATION, + "android.permission.ACCESS_BACKGROUND_LOCATION"}; + cordova.requestPermissions(this, 2, strings); + } + } + } +} diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/src/android/build.gradle b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/src/android/build.gradle new file mode 100644 index 00000000..23296fb7 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/src/android/build.gradle @@ -0,0 +1,29 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + repositories { + google() + jcenter() + // huawei maven + maven { url 'http://developer.huawei.com/repo/' } + } + dependencies { + classpath 'com.android.tools.build:gradle:3.2.0' + classpath 'com.huawei.agconnect:agcp:1.2.0.300' + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + jcenter() + // huawei maven + maven { url 'http://developer.huawei.com/repo/' } + } +} + +cdvPluginPostBuildExtras.add({ + apply plugin: 'com.huawei.agconnect' +}) diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/plugin.xml b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/plugin.xml new file mode 100644 index 00000000..d7ccbfa7 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/plugin.xml @@ -0,0 +1,38 @@ + + + + + + + CordovaHMSPushPlugin + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/after_prepare.js b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/after_prepare.js new file mode 100644 index 00000000..ab6c7b7e --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/after_prepare.js @@ -0,0 +1,38 @@ +#!/usr/bin/env node + +'use strict'; + +/** + * This hook makes sure projects using [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) + * will build properly and have the required key files copied to the proper destinations when the app is build on Ionic Cloud using the package command. + * Credits: https://github.com/arnesson. + */ +var fs = require('fs'); +var path = require('path'); +var utilities = require("./lib/utilities"); + +var config = fs.readFileSync('config.xml').toString(); +var name = utilities.getValue(config, 'name'); + +var ANDROID_DIR = 'platforms/android'; + +var PLATFORM = { + ANDROID: { + dest: [ + ANDROID_DIR + '/app/agconnect-services.json' + ], + src: [ + 'agconnect-services.json' + ], + } +}; + +module.exports = function (context) { + //get platform from the context supplied by cordova + var platforms = context.opts.platforms; + // Copy key files to their platform specific folders + if (platforms.indexOf('android') !== -1 && utilities.directoryExists(ANDROID_DIR)) { + console.log('Preparing HMS Push Kit on Android'); + utilities.copyKey(PLATFORM.ANDROID); + } +}; \ No newline at end of file diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/android/after_plugin_install.js b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/android/after_plugin_install.js new file mode 100644 index 00000000..09e73419 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/android/after_plugin_install.js @@ -0,0 +1,9 @@ +var helper = require('./helper'); + +module.exports = function(context) { + + // Modify the Gradle build file to add a task that will upload the debug symbols + // at build time. + helper.restoreRootBuildGradle(); + helper.modifyRootBuildGradle(); +}; \ No newline at end of file diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/android/before_plugin_uninstall.js b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/android/before_plugin_uninstall.js new file mode 100644 index 00000000..9c32e552 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/android/before_plugin_uninstall.js @@ -0,0 +1,7 @@ +var helper = require('./helper'); + +module.exports = function(context) { + + // Remove the Gradle modifications that were added when the plugin was installed. + helper.restoreRootBuildGradle(); +}; \ No newline at end of file diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/android/helper.js b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/android/helper.js new file mode 100644 index 00000000..da715c24 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/android/helper.js @@ -0,0 +1,117 @@ +var fs = require("fs"); +var path = require("path"); + +function rootBuildGradleExists() { + var target = path.join("platforms", "android", "build.gradle"); + return fs.existsSync(target); +} + +/* + * Helper function to read the build.gradle that sits at the root of the project + */ +function readRootBuildGradle() { + var target = path.join("platforms", "android", "build.gradle"); + return fs.readFileSync(target, "utf-8"); +} + +/* + * Added a dependency on 'com.google.gms' based on the position of the know 'com.android.tools.build' dependency in the build.gradle + */ +function addDependencies(buildGradle) { + // find the known line to match + var match = buildGradle.match(/^(\s*)classpath 'com.android.tools.build(.*)/m); + var whitespace = match[1]; + + // modify the line to add the necessary dependencies + var agcDependency = whitespace + 'classpath \'com.huawei.agconnect:agcp:1.2.0.300\'' + + var modifiedLine = match[0] + '\n' + agcDependency; + + // modify the actual line + return buildGradle.replace(/^(\s*)classpath 'com.android.tools.build(.*)/m, modifiedLine); +} + +/* + * Add 'google()' and Crashlytics to the repository repo list + */ +function addRepos(buildGradle) { + // find the known line to match + var match = buildGradle.match(/^(\s*)jcenter\(\)/m); + var whitespace = match[1]; + + // modify the line to add the necessary repo + var huaweiMavenRepo = whitespace + 'maven { url \'http://developer.huawei.com/repo/\' }' + var modifiedLine = match[0] + '\n' + huaweiMavenRepo; + + // modify the actual line + buildGradle = buildGradle.replace(/^(\s*)jcenter\(\)/m, modifiedLine); + + // update the all projects grouping + var allProjectsIndex = buildGradle.indexOf('allprojects'); + if (allProjectsIndex > 0) { + // split the string on allprojects because jcenter is in both groups and we need to modify the 2nd instance + var firstHalfOfFile = buildGradle.substring(0, allProjectsIndex); + var secondHalfOfFile = buildGradle.substring(allProjectsIndex); + + // Add google() to the allprojects section of the string + match = secondHalfOfFile.match(/^(\s*)jcenter\(\)/m); + var huaweiMavenRepo = whitespace + 'maven { url \'http://developer.huawei.com/repo/\' }' + modifiedLine = match[0] + '\n' + huaweiMavenRepo; + // modify the part of the string that is after 'allprojects' + secondHalfOfFile = secondHalfOfFile.replace(/^(\s*)jcenter\(\)/m, modifiedLine); + + // recombine the modified line + buildGradle = firstHalfOfFile + secondHalfOfFile; + } else { + // this should not happen, but if it does, we should try to add the dependency to the buildscript + match = buildGradle.match(/^(\s*)jcenter\(\)/m); + var huaweiMavenRepo = whitespace + 'maven { url \'http://developer.huawei.com/repo/\' }' + modifiedLine = match[0] + '\n' + huaweiMavenRepo; + // modify the part of the string that is after 'allprojects' + buildGradle = buildGradle.replace(/^(\s*)jcenter\(\)/m, modifiedLine); + } + + return buildGradle; +} + +/* + * Helper function to write to the build.gradle that sits at the root of the project + */ +function writeRootBuildGradle(contents) { + var target = path.join("platforms", "android", "build.gradle"); + fs.writeFileSync(target, contents); +} + +module.exports = { + + modifyRootBuildGradle: function() { + // be defensive and don't crash if the file doesn't exist + if (!rootBuildGradleExists) { + return; + } + + var buildGradle = readRootBuildGradle(); + + // Add Google Play Services Dependency + buildGradle = addDependencies(buildGradle); + + // Add Google's Maven Repo + buildGradle = addRepos(buildGradle); + + writeRootBuildGradle(buildGradle); + }, + + restoreRootBuildGradle: function() { + // be defensive and don't crash if the file doesn't exist + if (!rootBuildGradleExists) { + return; + } + + var buildGradle = readRootBuildGradle(); + + // remove any lines we added + buildGradle = buildGradle.replace(/(?:^|\r?\n)(.*)com.huawei.cordovahmspushplugin*?(?=$|\r?\n)/g, ''); + + writeRootBuildGradle(buildGradle); + } +}; \ No newline at end of file diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/lib/utilities.js b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/lib/utilities.js new file mode 100644 index 00000000..015f6831 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/scripts/lib/utilities.js @@ -0,0 +1,88 @@ +/** + * Utilities and shared functionality for the build hooks. + */ +var fs = require('fs'); +var path = require("path"); + +fs.ensureDirSync = function (dir) { + if (!fs.existsSync(dir)) { + dir.split(path.sep).reduce(function (currentPath, folder) { + currentPath += folder + path.sep; + if (!fs.existsSync(currentPath)) { + fs.mkdirSync(currentPath); + } + return currentPath; + }, ''); + } +}; + +module.exports = { + /** + * Used to get the name of the application as defined in the config.xml. + * + * @param {object} context - The Cordova context. + * @returns {string} The value of the name element in config.xml. + */ + getAppName: function (context) { + var ConfigParser = context.requireCordovaModule("cordova-lib").configparser; + var config = new ConfigParser("config.xml"); + return config.name(); + }, + + /** + * The ID of the plugin; this should match the ID in plugin.xml. + */ + getPluginId: function () { + return "com.huawei.cordovahmspushplugin"; + }, + + copyKey: function (platform) { + for (var i = 0; i < platform.src.length; i++) { + var file = platform.src[i]; + if (this.fileExists(file)) { + try { + var contents = fs.readFileSync(file).toString(); + + try { + platform.dest.forEach(function (destinationPath) { + var folder = destinationPath.substring(0, destinationPath.lastIndexOf('/')); + fs.ensureDirSync(folder); + fs.writeFileSync(destinationPath, contents); + }); + } catch (e) { + // skip + } + } catch (err) { + console.log(err); + } + + break; + } + } + }, + + getValue: function (config, name) { + var value = config.match(new RegExp('<' + name + '(.*?)>(.*?)', 'i')); + if (value && value[2]) { + return value[2] + } else { + return null + } + }, + + fileExists: function (path) { + try { + return fs.statSync(path).isFile(); + } catch (e) { + return false; + } + }, + + directoryExists: function (path) { + try { + return fs.statSync(path).isDirectory(); + } catch (e) { + return false; + } + } +}; \ No newline at end of file diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/src/android/CordovaHMSPushPlugin.java b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/src/android/CordovaHMSPushPlugin.java new file mode 100644 index 00000000..d2ef10b4 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/src/android/CordovaHMSPushPlugin.java @@ -0,0 +1,112 @@ +package com.huawei.cordovahmspushplugin; + +import android.text.TextUtils; +import android.util.Log; + +import com.huawei.agconnect.config.AGConnectServicesConfig; +import com.huawei.hms.aaid.HmsInstanceId; +import com.huawei.hms.push.HmsMessaging; +import com.huawei.hmf.tasks.OnCompleteListener; +import com.huawei.hmf.tasks.Task; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.PluginResult; +import org.json.JSONArray; +import org.json.JSONException; + +/** + * This class echoes a string called from JavaScript. + */ +public class CordovaHMSPushPlugin extends CordovaPlugin { + + private static final String TAG = CordovaHMSPushPlugin.class.getSimpleName(); + + private static CallbackContext mCallbackContext; + private static CallbackContext mTokenCallback; + + @Override + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { + switch (action) { + case "getToken": + this.getToken(callbackContext); + return true; + case "getMessageCallback": + Log.d(TAG, "getMessageCallback"); + mCallbackContext = callbackContext; + return true; + case "subscribeTopic": + Log.d(TAG, "subscribeTopic"); + try { + String topic = args.getString(0); + this.subscribeTopic(topic, callbackContext); + } catch (JSONException e) { + return true; + } + return true; + default: + return false; + } + } + + public static void returnMessage(String message) { + if (mCallbackContext != null) { + Log.d(TAG, "returnMessage"); + PluginResult result = new PluginResult(PluginResult.Status.OK, message); + result.setKeepCallback(true); + mCallbackContext.sendPluginResult(result); + } + } + + public static void returnToken(String token) { + if (mTokenCallback != null) { + mTokenCallback.success(token); + mTokenCallback = null; + } + } + + /** + * get push token + */ + private void getToken(CallbackContext callbackContext) { + Log.i(TAG, "get token: begin"); + + try { + String appId = AGConnectServicesConfig.fromContext(cordova.getContext()).getString("client/app_id"); + String pushToken = HmsInstanceId.getInstance(cordova.getContext()).getToken(appId, "HCM"); + if (!TextUtils.isEmpty(pushToken)) { + Log.i(TAG, "get token:" + pushToken); + callbackContext.success(pushToken); + }else { + mTokenCallback = callbackContext; + } + } catch (Exception e) { + Log.e(TAG, "getToken Failed, " + e); + callbackContext.error("getToken Failed, error : " + e.getMessage()); + } + } + + public void subscribeTopic(String topic, final CallbackContext callBack) { + // callBack.success("user subscribe to topic named as: "+ topic); + if (topic == null || topic.toString().equals("")) { + callBack.error("topic is empty!"); + return; + } + try { + HmsMessaging.getInstance(cordova.getContext()).subscribe(topic). + addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(Task task) { + if (task.isSuccessful()) { + callBack.success("user subscribe to topic: "+ topic); + } else { + callBack.error("getToken Failed, error : " + task.getException().getMessage()); + } + } + }); + } catch (Exception e) { + callBack.error("getToken Failed, error : " + e.getMessage()); + } + } + +} diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/src/android/MessageService.java b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/src/android/MessageService.java new file mode 100644 index 00000000..d32542ef --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/src/android/MessageService.java @@ -0,0 +1,32 @@ +package com.huawei.cordovahmspushplugin; + +import com.huawei.cordovahmspushplugin.CordovaHMSPushPlugin; +import com.huawei.hms.push.HmsMessageService; +import com.huawei.hms.push.RemoteMessage; + +import android.util.Log; + +public class MessageService extends HmsMessageService { + + private static final String TAG = MessageService.class.getSimpleName(); + + @Override + public void onMessageReceived(RemoteMessage remoteMessage) { + super.onMessageReceived(remoteMessage); + Log.d(TAG, "onMessageReceived"); + if (remoteMessage != null) { + String message = remoteMessage.getData(); + Log.d(TAG, message); + CordovaHMSPushPlugin.returnMessage(message); + } + } + + @Override + public void onNewToken(String s) { + super.onNewToken(s); + if (s != null) { + Log.d(TAG, "token:" + s); + CordovaHMSPushPlugin.returnToken(s); + } + } +} diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/src/android/build.gradle b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/src/android/build.gradle new file mode 100644 index 00000000..23296fb7 --- /dev/null +++ b/Mohem/CordovaHMSPlugin/CordovaHMSPushPlugin/src/android/build.gradle @@ -0,0 +1,29 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + repositories { + google() + jcenter() + // huawei maven + maven { url 'http://developer.huawei.com/repo/' } + } + dependencies { + classpath 'com.android.tools.build:gradle:3.2.0' + classpath 'com.huawei.agconnect:agcp:1.2.0.300' + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + jcenter() + // huawei maven + maven { url 'http://developer.huawei.com/repo/' } + } +} + +cdvPluginPostBuildExtras.add({ + apply plugin: 'com.huawei.agconnect' +}) From 438a8dce0337961401a4b2bf87189c44f3620f58 Mon Sep 17 00:00:00 2001 From: umasoodch Date: Tue, 14 Sep 2021 12:37:15 +0300 Subject: [PATCH 2/4] added hmg_utils file --- Mohem/src/app/hmg-common/hmg_utils.ts | 121 ++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 Mohem/src/app/hmg-common/hmg_utils.ts diff --git a/Mohem/src/app/hmg-common/hmg_utils.ts b/Mohem/src/app/hmg-common/hmg_utils.ts new file mode 100644 index 00000000..f8a7737b --- /dev/null +++ b/Mohem/src/app/hmg-common/hmg_utils.ts @@ -0,0 +1,121 @@ +import { Injectable } from "@angular/core"; +import { BackgroundGeolocation } from '@ionic-native/background-geolocation/ngx'; +import { CommonService } from "src/app/hmg-common/services/common/common.service"; +import { TranslatorService } from "src/app/hmg-common/services/translator/translator.service"; +import { DevicePermissionsService } from 'src/app/hmg-common/services/device-permissions/device-permissions.service'; +import { Geolocation } from '@ionic-native/geolocation/ngx'; +import { Platform } from "@ionic/angular"; + +declare var cordova: any; + +@Injectable({ + providedIn: 'root' +}) +export class HMGUtils { + constructor( + public backgroundGeolocation: BackgroundGeolocation, + public common: CommonService, + public ts: TranslatorService, + private geolocation: Geolocation, + public platform: Platform, + public devicePermissionsService:DevicePermissionsService, + ) { } + + async getCurrentLocation(callBack: Function) { + if (this.platform.is('android')) { + this.devicePermissionsService.requestLocationAutherization().then( async granted => { + if(granted == true){ + if ((await this.isHuaweiDevice())) { + this.getHMSLocation(callBack); + } else { + this.getGMSLocation(callBack); + } + }else{ + this.common.presentAlert(this.ts.trPK('general', 'location-permission-dialog')); + } + }); + } else { + this.getIOSLocation(callBack); + } + } + + + async isHuaweiDevice(): Promise { + var result = await new Promise((resolve, reject) => { + cordova.plugins.CordovaHMSGMSCheckPlugin.isHmsAvailable( + "index.js", + (_res) => { + var hmsAvailable = _res === "true"; + resolve(hmsAvailable); + }, + (_err) => { + reject({ "status": false, "error": JSON.stringify(_err) }); + alert("Error checking device HMS/GMS") + } + ); + }); + + return (result == true); + } + + private getHMSLocation(callBack: Function) { + try { + + console.log("Huawei Location [Getting]"); + cordova.plugins.CordovaHMSLocationPlugin.requestLocation( + "index.js", + (_res) => { + console.log("Huawei Location Success: [Stop Getting]"); + cordova.plugins.CordovaHMSLocationPlugin.removeLocation("", (_res) => { }, (_err) => { }); + var location = _res.split(',') + if (location.length == 2) { + var lat = Number(_res.split(',')[0]); + var long = Number(_res.split(',')[1]); + callBack({"latitude":lat, "longitude":long, "isfake":false}) + } else { + alert("Invalid Huawei location from plugin."); + } + }, + (_err) => { + console.log("Huawei Location [Getting Error]: " + + JSON.stringify(_err)); + alert("Error while getting Huawei location"); + } + ); + + } catch (_err) { + console.log("Huawei Location Plugin [Error]: " + + JSON.stringify(_err)); + alert("Error while initializing Huawei Location Plugin"); + } + } + + private getGMSLocation(callBack: Function) { + this.backgroundGeolocation.getCurrentLocation({ timeout: 10000, enableHighAccuracy: true, maximumAge: 3000 }).then((resp) => { + if (resp && (resp.latitude && resp.longitude)) { + var isFakeLocation = resp.isFromMockProvider || resp.mockLocationsEnabled; + var lat = resp.latitude; + var long = resp.longitude; + callBack({"latitude":lat, "longitude":long, "isfake":isFakeLocation}) + } else { + this.common.presentAlert(this.ts.trPK('home', 'position-error')); + } + }, (error) => { + this.common.presentAlert(this.ts.trPK('home', 'position-error')); + }); + } + + private getIOSLocation(callBack: Function) { + this.geolocation.getCurrentPosition({ maximumAge: 3000, timeout: 10000, enableHighAccuracy: true }).then(resp => { + if (resp && resp.coords.latitude && resp.coords.longitude) { + var lat = resp.coords.latitude; + var long = resp.coords.longitude; + callBack({"latitude":lat, "longitude":long, "isfake":false}) + } else { + this.common.presentAlert(this.ts.trPK('home', 'position-error')); + } + }).catch(error => { + this.common.presentAlert(this.ts.trPK('home', 'position-error')); + }); + } + + +} \ No newline at end of file From 5411a068bfe9d4e33dd17c551d3bda97cdf57df8 Mon Sep 17 00:00:00 2001 From: umasoodch Date: Wed, 15 Sep 2021 11:00:26 +0300 Subject: [PATCH 3/4] added check code for huawei device --- .../src/android/CordovaHMSLocationPlugin.java | 3 ++- Mohem/config.xml | 2 +- Mohem/package.json | 4 ++++ Mohem/src/app/hmg-common/hmg_utils.ts | 10 ++++++---- .../attendance-options.component.html | 1 + .../attendance-options.component.ts | 18 +++++++++++++++++- 6 files changed, 31 insertions(+), 7 deletions(-) diff --git a/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/src/android/CordovaHMSLocationPlugin.java b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/src/android/CordovaHMSLocationPlugin.java index caef5fd0..4b094ad5 100644 --- a/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/src/android/CordovaHMSLocationPlugin.java +++ b/Mohem/CordovaHMSPlugin/CordovaHMSLocationPlugin/src/android/CordovaHMSLocationPlugin.java @@ -27,6 +27,7 @@ import org.json.JSONException; /** * */ + // https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-References-V1/data-types-0000001056511617-V1#section2512153819346 public class CordovaHMSLocationPlugin extends CordovaPlugin { private static final String TAG = CordovaHMSLocationPlugin.class.getSimpleName(); @@ -62,7 +63,7 @@ public class CordovaHMSLocationPlugin extends CordovaPlugin { private void returnLocation(Location location) { if (mCallbackContext != null) { Log.d(TAG, "returnLocation"); - String message = location.getLatitude() + "," + location.getLongitude(); + String message = location.getLatitude() + "," + location.getLongitude() + "," + location.isFromMockProvider(); PluginResult result = new PluginResult(PluginResult.Status.OK, message); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); diff --git a/Mohem/config.xml b/Mohem/config.xml index f1bfd97d..5ad4f1b7 100644 --- a/Mohem/config.xml +++ b/Mohem/config.xml @@ -106,7 +106,7 @@ - + diff --git a/Mohem/package.json b/Mohem/package.json index 94d82c02..21093409 100644 --- a/Mohem/package.json +++ b/Mohem/package.json @@ -136,6 +136,8 @@ "@types/jasminewd2": "~2.0.3", "@types/node": "~10.12.0", "codelyzer": "~4.5.0", + "com.huawei.cordovahmsgmscheckplugin": "file:CordovaHMSPlugin/CordovaHMSGMSCheckPlugin", + "com.huawei.cordovahmslocationplugin": "file:CordovaHMSPlugin/CordovaHMSLocationPlugin", "cordova-ios": "^6.2.0", "cordova-plugin-wifiwizard2": "^3.1.1", "es6-promise-plugin": "^4.1.0", @@ -201,6 +203,8 @@ }, "phonegap-nfc": {}, "wifiwizard2": {}, + "com.huawei.cordovahmsgmscheckplugin": {}, + "com.huawei.cordovahmslocationplugin": {}, "cordova-plugin-x-socialsharing": {}, "cordova-plugin-firebasex": { "FIREBASE_ANALYTICS_COLLECTION_ENABLED": "true", diff --git a/Mohem/src/app/hmg-common/hmg_utils.ts b/Mohem/src/app/hmg-common/hmg_utils.ts index f8a7737b..d2e72588 100644 --- a/Mohem/src/app/hmg-common/hmg_utils.ts +++ b/Mohem/src/app/hmg-common/hmg_utils.ts @@ -41,7 +41,7 @@ export class HMGUtils { async isHuaweiDevice(): Promise { - var result = await new Promise((resolve, reject) => { + var result: any = await new Promise((resolve, reject) => { cordova.plugins.CordovaHMSGMSCheckPlugin.isHmsAvailable( "index.js", (_res) => { @@ -50,12 +50,12 @@ export class HMGUtils { }, (_err) => { reject({ "status": false, "error": JSON.stringify(_err) }); - alert("Error checking device HMS/GMS") + alert("Error checking device HMS/GMS") // add your popup } ); }); - return (result == true); + return result; } private getHMSLocation(callBack: Function) { @@ -68,10 +68,12 @@ export class HMGUtils { console.log("Huawei Location Success: [Stop Getting]"); cordova.plugins.CordovaHMSLocationPlugin.removeLocation("", (_res) => { }, (_err) => { }); var location = _res.split(',') + console.log(location); if (location.length == 2) { var lat = Number(_res.split(',')[0]); var long = Number(_res.split(',')[1]); - callBack({"latitude":lat, "longitude":long, "isfake":false}) + var mock = Boolean(_res.split(',')[2]); + callBack({"latitude":lat, "longitude":long, "isfake":mock}) } else { alert("Invalid Huawei location from plugin."); } diff --git a/Mohem/src/app/home/attendance-options/attendance-options.component.html b/Mohem/src/app/home/attendance-options/attendance-options.component.html index 145721f3..6c847e84 100644 --- a/Mohem/src/app/home/attendance-options/attendance-options.component.html +++ b/Mohem/src/app/home/attendance-options/attendance-options.component.html @@ -19,6 +19,7 @@ +

umarrrrrrrrrrrrrrrr {{check}}

diff --git a/Mohem/src/app/home/attendance-options/attendance-options.component.ts b/Mohem/src/app/home/attendance-options/attendance-options.component.ts index 8de622b0..df7428bd 100644 --- a/Mohem/src/app/home/attendance-options/attendance-options.component.ts +++ b/Mohem/src/app/home/attendance-options/attendance-options.component.ts @@ -19,7 +19,9 @@ import { DevicePermissionsService } from 'src/app/hmg-common/services/device-per import { Geolocation } from '@ionic-native/geolocation/ngx'; import { BackgroundGeolocation } from '@ionic-native/background-geolocation/ngx'; import { FirebaseX } from '@ionic-native/firebase-x/ngx'; +import { HMGUtils } from 'src/app/hmg-common/hmg_utils'; +declare var cordova: any; @Component({ selector: "app-attendance-options", @@ -47,6 +49,7 @@ export class AttendanceOptionsComponent implements OnInit { public firebasex: FirebaseX public isDocumentAvailable = false; public document: any; + public check: any; constructor( @@ -63,7 +66,8 @@ export class AttendanceOptionsComponent implements OnInit { private openNativeSettings: OpenNativeSettings, private devicePermissionsService:DevicePermissionsService, private geolocation: Geolocation, - public backgroundGeolocation: BackgroundGeolocation + public backgroundGeolocation: BackgroundGeolocation, + public hmgUtils: HMGUtils ) {} ngOnInit() { @@ -76,6 +80,18 @@ export class AttendanceOptionsComponent implements OnInit { this.priviligeList = AuthenticationService.servicePrivilage; this.setServicesPrivilage(); this.checkNFCStatus("one"); + this.test(); + } + + async test () { + const test = await this.hmgUtils.isHuaweiDevice(); + if (test) { + this.check = 'this device is huawei device :' + test; + console.log('this device is huawei device :' + test); + } else { + this.check = 'this device is not huawei device :' + test; + console.log('this device is non-huawei device :' + test); + } } public checkFirebaseDocument() { From f00643dbf62037a6d0506220b111245fd83bae71 Mon Sep 17 00:00:00 2001 From: umasoodch Date: Mon, 27 Sep 2021 09:57:27 +0300 Subject: [PATCH 4/4] fixed production abscence issue --- .../submit-absence.component.html | 2 +- Mohem/src/app/hmg-common/hmg_utils.ts | 38 +++++++++---------- .../attendance-options.component.ts | 4 ++ .../src/app/profile/home/home.component.html | 2 +- .../src/app/profile/home/home.component.scss | 2 + Mohem/src/assets/localization/i18n.json | 8 ++++ 6 files changed, 34 insertions(+), 22 deletions(-) diff --git a/Mohem/src/app/absence/submit-absence/submit-absence.component.html b/Mohem/src/app/absence/submit-absence/submit-absence.component.html index ec40c78c..3eead9c9 100644 --- a/Mohem/src/app/absence/submit-absence/submit-absence.component.html +++ b/Mohem/src/app/absence/submit-absence/submit-absence.component.html @@ -7,7 +7,7 @@
-
diff --git a/Mohem/src/app/hmg-common/hmg_utils.ts b/Mohem/src/app/hmg-common/hmg_utils.ts index d2e72588..301b3997 100644 --- a/Mohem/src/app/hmg-common/hmg_utils.ts +++ b/Mohem/src/app/hmg-common/hmg_utils.ts @@ -6,7 +6,7 @@ import { DevicePermissionsService } from 'src/app/hmg-common/services/device-per import { Geolocation } from '@ionic-native/geolocation/ngx'; import { Platform } from "@ionic/angular"; -declare var cordova: any; +declare const cordova: any; @Injectable({ providedIn: 'root' @@ -41,16 +41,16 @@ export class HMGUtils { async isHuaweiDevice(): Promise { - var result: any = await new Promise((resolve, reject) => { + const result: any = await new Promise((resolve, reject) => { cordova.plugins.CordovaHMSGMSCheckPlugin.isHmsAvailable( "index.js", (_res) => { - var hmsAvailable = _res === "true"; + const hmsAvailable = _res === "true"; resolve(hmsAvailable); }, (_err) => { reject({ "status": false, "error": JSON.stringify(_err) }); - alert("Error checking device HMS/GMS") // add your popup + this.common.presentAlert(this.ts.trPK('general', 'huawei-hms-gms-error')); } ); }); @@ -60,42 +60,40 @@ export class HMGUtils { private getHMSLocation(callBack: Function) { try { - - console.log("Huawei Location [Getting]"); cordova.plugins.CordovaHMSLocationPlugin.requestLocation( "index.js", (_res) => { console.log("Huawei Location Success: [Stop Getting]"); cordova.plugins.CordovaHMSLocationPlugin.removeLocation("", (_res) => { }, (_err) => { }); - var location = _res.split(',') + const location = _res.split(',') console.log(location); - if (location.length == 2) { - var lat = Number(_res.split(',')[0]); - var long = Number(_res.split(',')[1]); - var mock = Boolean(_res.split(',')[2]); + if (location.length == 3) { + const lat = Number(_res.split(',')[0]); + const long = Number(_res.split(',')[1]); + const mock = Boolean(_res.split(',')[2]); callBack({"latitude":lat, "longitude":long, "isfake":mock}) } else { - alert("Invalid Huawei location from plugin."); + this.common.presentAlert(this.ts.trPK('general', 'invalid-huawei-location')); } }, (_err) => { - console.log("Huawei Location [Getting Error]: " + + JSON.stringify(_err)); - alert("Error while getting Huawei location"); + console.log("Huawei Location [Getting Error]: " + JSON.stringify(_err)); + this.common.presentAlert(this.ts.trPK('general', 'invalid-huawei-location')); } ); } catch (_err) { console.log("Huawei Location Plugin [Error]: " + + JSON.stringify(_err)); - alert("Error while initializing Huawei Location Plugin"); + this.common.presentAlert('Error while initializing Huawei Location Plugin'); } } private getGMSLocation(callBack: Function) { this.backgroundGeolocation.getCurrentLocation({ timeout: 10000, enableHighAccuracy: true, maximumAge: 3000 }).then((resp) => { if (resp && (resp.latitude && resp.longitude)) { - var isFakeLocation = resp.isFromMockProvider || resp.mockLocationsEnabled; - var lat = resp.latitude; - var long = resp.longitude; + const isFakeLocation = resp.isFromMockProvider || resp.mockLocationsEnabled; + const lat = resp.latitude; + const long = resp.longitude; callBack({"latitude":lat, "longitude":long, "isfake":isFakeLocation}) } else { this.common.presentAlert(this.ts.trPK('home', 'position-error')); @@ -108,8 +106,8 @@ export class HMGUtils { private getIOSLocation(callBack: Function) { this.geolocation.getCurrentPosition({ maximumAge: 3000, timeout: 10000, enableHighAccuracy: true }).then(resp => { if (resp && resp.coords.latitude && resp.coords.longitude) { - var lat = resp.coords.latitude; - var long = resp.coords.longitude; + const lat = resp.coords.latitude; + const long = resp.coords.longitude; callBack({"latitude":lat, "longitude":long, "isfake":false}) } else { this.common.presentAlert(this.ts.trPK('home', 'position-error')); diff --git a/Mohem/src/app/home/attendance-options/attendance-options.component.ts b/Mohem/src/app/home/attendance-options/attendance-options.component.ts index df7428bd..b2f97ee4 100644 --- a/Mohem/src/app/home/attendance-options/attendance-options.component.ts +++ b/Mohem/src/app/home/attendance-options/attendance-options.component.ts @@ -92,6 +92,10 @@ export class AttendanceOptionsComponent implements OnInit { this.check = 'this device is not huawei device :' + test; console.log('this device is non-huawei device :' + test); } + + this.hmgUtils.getCurrentLocation((data) => { + console.log(data); + }); } public checkFirebaseDocument() { diff --git a/Mohem/src/app/profile/home/home.component.html b/Mohem/src/app/profile/home/home.component.html index 7b87ba62..96b8ea1b 100644 --- a/Mohem/src/app/profile/home/home.component.html +++ b/Mohem/src/app/profile/home/home.component.html @@ -142,7 +142,7 @@ - + diff --git a/Mohem/src/app/profile/home/home.component.scss b/Mohem/src/app/profile/home/home.component.scss index 8ea8bfd1..97bbfbb6 100644 --- a/Mohem/src/app/profile/home/home.component.scss +++ b/Mohem/src/app/profile/home/home.component.scss @@ -1209,6 +1209,8 @@ $actionBtnSize: 36px; height: 35px; color: white; border-radius: 50%; + position: absolute; + right: 30px; } .name{ diff --git a/Mohem/src/assets/localization/i18n.json b/Mohem/src/assets/localization/i18n.json index 01c556c6..58896854 100644 --- a/Mohem/src/assets/localization/i18n.json +++ b/Mohem/src/assets/localization/i18n.json @@ -209,6 +209,14 @@ } }, "general": { + "invalid-huawei-location": { + "en": "Error while getting location from Huawei HMS services", + "ar": "خطأ أثناء الحصول على الموقع من خدمات Huawei HMS" + }, + "huawei-hms-gms-error": { + "en": "Error checking device HMS/GMS availability", + "ar": "خطأ في التحقق من توفر جهاز HMS / GMS" + }, "location-permission-dialog": { "en": "Allow the Mohemm app to access your location for marking your attendance", "ar": "اسمح لتطبيق مهم بالوصول إلى موقعك لتحديد حضورك"