diff --git a/Assets/Huawei/Demos/APM/APMDemoManager.cs b/Assets/Huawei/Demos/APM/APMDemoManager.cs index 0c30adcf..cb5767b6 100644 --- a/Assets/Huawei/Demos/APM/APMDemoManager.cs +++ b/Assets/Huawei/Demos/APM/APMDemoManager.cs @@ -1,3 +1,4 @@ +using HmsPlugin; using HuaweiMobileServices.APM; using UnityEngine; diff --git a/Assets/Huawei/Demos/CrashKit/CrashDemoManager.cs b/Assets/Huawei/Demos/CrashKit/CrashDemoManager.cs index 6154c073..a9bf26f4 100644 --- a/Assets/Huawei/Demos/CrashKit/CrashDemoManager.cs +++ b/Assets/Huawei/Demos/CrashKit/CrashDemoManager.cs @@ -1,4 +1,5 @@ +using HmsPlugin; using UnityEngine; public class CrashDemoManager : MonoBehaviour diff --git a/Assets/Huawei/Demos/Location/ActivityIdentificationDemo.cs b/Assets/Huawei/Demos/Location/ActivityIdentificationDemo.cs index e5e9aecd..7fd36ee5 100644 --- a/Assets/Huawei/Demos/Location/ActivityIdentificationDemo.cs +++ b/Assets/Huawei/Demos/Location/ActivityIdentificationDemo.cs @@ -1,4 +1,4 @@ -using HuaweiMobileServices.Location; +using HuaweiMobileServices.Location; using HuaweiMobileServices.Location.Activity; using HuaweiMobileServices.Utils; using UnityEngine; @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Text; using Huawei.Scripts.Location; +using HmsPlugin; namespace Huawei.Demos.Location { @@ -103,7 +104,7 @@ private void SetParameterForActivityConversion() ActivityConversionInfo activityConversionInfoStillEnter = new ActivityConversionInfo( ActivityIdentificationData.STILL, ActivityConversionInfo.ENTER_ACTIVITY_CONVERSION); - // Create an information object for switching from the activity state to the static state. + // Create an information object for switching from the activity state to the static state. ActivityConversionInfo activityConversionInfoStillExit = new ActivityConversionInfo( ActivityIdentificationData.FOOT, ActivityConversionInfo.EXIT_ACTIVITY_CONVERSION); List activityConversionInfos = new List(); diff --git a/Assets/Huawei/Demos/Location/FusedLocationDemo.cs b/Assets/Huawei/Demos/Location/FusedLocationDemo.cs index 580e2107..99ed2a62 100644 --- a/Assets/Huawei/Demos/Location/FusedLocationDemo.cs +++ b/Assets/Huawei/Demos/Location/FusedLocationDemo.cs @@ -1,5 +1,6 @@ using System; using System.Text; +using HmsPlugin; using HuaweiMobileServices.Location; using HuaweiMobileServices.Location.Location; using UnityEngine; diff --git a/Assets/Huawei/Demos/Location/GeofenceDemo.cs b/Assets/Huawei/Demos/Location/GeofenceDemo.cs index f947d688..e0226892 100644 --- a/Assets/Huawei/Demos/Location/GeofenceDemo.cs +++ b/Assets/Huawei/Demos/Location/GeofenceDemo.cs @@ -8,6 +8,7 @@ using Huawei.Scripts.Location; using HuaweiMobileServices.Location; using HuaweiMobileServices.Location.Location; +using HmsPlugin; public class GeofenceDemo : MonoBehaviour { diff --git a/Assets/Huawei/Demos/RemoteConfig/RemoteConfigDemo.cs b/Assets/Huawei/Demos/RemoteConfig/RemoteConfigDemo.cs index 9c4e12ca..7d4e1062 100644 --- a/Assets/Huawei/Demos/RemoteConfig/RemoteConfigDemo.cs +++ b/Assets/Huawei/Demos/RemoteConfig/RemoteConfigDemo.cs @@ -1,3 +1,4 @@ +using HmsPlugin; using HuaweiMobileServices.RemoteConfig; using HuaweiMobileServices.Utils; diff --git a/Assets/Huawei/Demos/Scan/ScanKitDemo.cs b/Assets/Huawei/Demos/Scan/ScanKitDemo.cs index 9a065a48..f4634bfd 100644 --- a/Assets/Huawei/Demos/Scan/ScanKitDemo.cs +++ b/Assets/Huawei/Demos/Scan/ScanKitDemo.cs @@ -1,3 +1,4 @@ +using HmsPlugin; using HuaweiMobileServices.Scan; using UnityEngine; diff --git a/Assets/Huawei/Editor/Utils/HMSExcelHelper.cs b/Assets/Huawei/Editor/Utils/HMSExcelHelper.cs index 0b01d94c..98320992 100644 --- a/Assets/Huawei/Editor/Utils/HMSExcelHelper.cs +++ b/Assets/Huawei/Editor/Utils/HMSExcelHelper.cs @@ -1,47 +1,50 @@ -using OfficeOpenXml; +using OfficeOpenXml; using System; using System.IO; -public static class HMSExcelHelper +namespace HmsPlugin { - public static string[,] ReadExcel(string path) + public static class HMSExcelHelper { - string[,] result = null; - - using (ExcelPackage package = new ExcelPackage(new FileInfo(path))) + public static string[,] ReadExcel(string path) { - ExcelWorksheet sheet = package.Workbook.Worksheets[1]; - result = ToStringArray(sheet.Cells.Value); + string[,] result = null; - } - return result; - } + using (ExcelPackage package = new ExcelPackage(new FileInfo(path))) + { + ExcelWorksheet sheet = package.Workbook.Worksheets[1]; + result = ToStringArray(sheet.Cells.Value); - private static string[,] ToStringArray(object arg) - { - string[,] result = null; + } + return result; + } - if (arg is Array) + private static string[,] ToStringArray(object arg) { - int rank = ((Array)arg).Rank; - if (rank == 2) - { - int columnCount = ((Array)arg).GetLength(1) - 1; - int rowCount = ((Array)arg).GetLength(0); - result = new string[rowCount, columnCount]; + string[,] result = null; - for (int i = 0; i < rowCount; i++) + if (arg is Array) + { + int rank = ((Array)arg).Rank; + if (rank == 2) { - for (int j = 0; j < columnCount; j++) + int columnCount = ((Array)arg).GetLength(1) - 1; + int rowCount = ((Array)arg).GetLength(0); + result = new string[rowCount, columnCount]; + + for (int i = 0; i < rowCount; i++) { - var value = ((Array)arg).GetValue(i, j); - if (value != null) - result[i, j] = value.ToString(); + for (int j = 0; j < columnCount; j++) + { + var value = ((Array)arg).GetValue(i, j); + if (value != null) + result[i, j] = value.ToString(); + } } } } - } - return result; + return result; + } } } diff --git a/Assets/Huawei/Editor/Utils/HMSGradleFixer.cs b/Assets/Huawei/Editor/Utils/HMSGradleFixer.cs index e7a1b365..b4287c0f 100644 --- a/Assets/Huawei/Editor/Utils/HMSGradleFixer.cs +++ b/Assets/Huawei/Editor/Utils/HMSGradleFixer.cs @@ -1,5 +1,4 @@ -using HmsPlugin; -using System.IO; +using System.IO; using System.Text; using UnityEditor; using UnityEditor.Android; @@ -7,15 +6,17 @@ using System; using System.Text.RegularExpressions; -public class HMSGradleFixer : IPostGenerateGradleAndroidProject +namespace HmsPlugin { - public int callbackOrder => 1; - private const string MINGRADLEVERSION = "3.5.4"; - private const string agconnect_agcp = "classpath 'com.huawei.agconnect:agcp:1.6.1.300'"; - private const string build_gradle = "classpath 'com.android.tools.build:gradle:" + MINGRADLEVERSION + "'"; - - private void GradleVersionFixer(string gradleFileAsString, string path) + public class HMSGradleFixer : IPostGenerateGradleAndroidProject { + public int callbackOrder => 1; + private const string MINGRADLEVERSION = "3.5.4"; + private const string agconnect_agcp = "classpath 'com.huawei.agconnect:agcp:1.6.1.300'"; + private const string build_gradle = "classpath 'com.android.tools.build:gradle:" + MINGRADLEVERSION + "'"; + + private void GradleVersionFixer(string gradleFileAsString, string path) + { #if UNITY_2022_2_OR_NEWER // Grade 7.2 string currentBuildgradle = File.ReadAllText(Directory.GetParent(path).FullName + "/build.gradle").Replace("apply from: 'hmsBaseProjectTemplate.gradle'", ""); @@ -44,118 +45,118 @@ private void GradleVersionFixer(string gradleFileAsString, string path) File.WriteAllText(Directory.GetParent(path).FullName + "/settings.gradle", currentSettingsgradle.Replace("mavenCentral()", "mavenCentral()\n\t\tmaven { url 'https://developer.huawei.com/repo/' }")); #else - string gradleRowPattern = @".*gradle:(\d\.?)+"; - string gradleVersionPattern = @"(\d\.?)+"; + string gradleRowPattern = @".*gradle:(\d\.?)+"; + string gradleVersionPattern = @"(\d\.?)+"; - if (!Version.TryParse(MINGRADLEVERSION, out Version gradleMinVersion)) - { - gradleMinVersion = new Version(3, 5, 4); - } + if (!Version.TryParse(MINGRADLEVERSION, out Version gradleMinVersion)) + { + gradleMinVersion = new Version(3, 5, 4); + } - Match gradleRowMatch = Regex.Match(gradleFileAsString, gradleRowPattern); - Match gradleVersionMatch = Regex.Match(gradleRowMatch.Value, gradleVersionPattern); + Match gradleRowMatch = Regex.Match(gradleFileAsString, gradleRowPattern); + Match gradleVersionMatch = Regex.Match(gradleRowMatch.Value, gradleVersionPattern); - if (!Version.TryParse(gradleVersionMatch.Value, out Version gradleVersion)) - { - gradleVersion = new Version(3, 5, 4); - } - // if users gradle version is lesser than our minimum version. - if (gradleVersion.CompareTo(gradleMinVersion) < 0) - { - gradleFileAsString = gradleFileAsString.Replace(gradleVersion.ToString(), gradleMinVersion.ToString()); + if (!Version.TryParse(gradleVersionMatch.Value, out Version gradleVersion)) + { + gradleVersion = new Version(3, 5, 4); + } + // if users gradle version is lesser than our minimum version. + if (gradleVersion.CompareTo(gradleMinVersion) < 0) + { + gradleFileAsString = gradleFileAsString.Replace(gradleVersion.ToString(), gradleMinVersion.ToString()); #if UNITY_2019_3_OR_NEWER - File.WriteAllText(Directory.GetParent(path).FullName + "/build.gradle", gradleFileAsString); + File.WriteAllText(Directory.GetParent(path).FullName + "/build.gradle", gradleFileAsString); #elif UNITY_2018_1_OR_NEWER File.WriteAllText(path + "/build.gradle", gradleFileAsString); #endif - } + } #endif - } + } - public void OnPostGenerateGradleAndroidProject(string path) - { - if (!HMSPluginSettings.Instance.Settings.GetBool(PluginToggleEditor.PluginEnabled, true)) + public void OnPostGenerateGradleAndroidProject(string path) { - HMSEditorUtils.UpdateAssemblyDefinitions(false); - return; - } + if (!HMSPluginSettings.Instance.Settings.GetBool(PluginToggleEditor.PluginEnabled, true)) + { + HMSEditorUtils.UpdateAssemblyDefinitions(false); + return; + } - string fileName = "agconnect-services.json"; - string filePath = Path.Combine(Application.streamingAssetsPath, fileName); - string destPath = ""; + string fileName = "agconnect-services.json"; + string filePath = Path.Combine(Application.streamingAssetsPath, fileName); + string destPath = ""; #if UNITY_2019_3_OR_NEWER - destPath = Path.Combine(Directory.GetParent(path).FullName + Path.DirectorySeparatorChar + "launcher", fileName); + destPath = Path.Combine(Directory.GetParent(path).FullName + Path.DirectorySeparatorChar + "launcher", fileName); - string hmsMainTemplatePath = Application.dataPath + "/Huawei/Plugins/Android/hmsMainTemplate.gradle"; - FileUtil.ReplaceFile(hmsMainTemplatePath, Path.GetFullPath(path) + @"/hmsMainTemplate.gradle"); - using (var writer = File.AppendText(Path.GetFullPath(path) + "/build.gradle")) - writer.WriteLine("\napply from: 'hmsMainTemplate.gradle'"); + string hmsMainTemplatePath = Application.dataPath + "/Huawei/Plugins/Android/hmsMainTemplate.gradle"; + FileUtil.ReplaceFile(hmsMainTemplatePath, Path.GetFullPath(path) + @"/hmsMainTemplate.gradle"); + using (var writer = File.AppendText(Path.GetFullPath(path) + "/build.gradle")) + writer.WriteLine("\napply from: 'hmsMainTemplate.gradle'"); - string launcherTemplatePath = Application.dataPath + "/Huawei/Plugins/Android/hmsLauncherTemplate.gradle"; - FileUtil.ReplaceFile(launcherTemplatePath, Directory.GetParent(path).FullName + @"/launcher/hmsLauncherTemplate.gradle"); - using (var writer = File.AppendText(Directory.GetParent(path).FullName + "/launcher/build.gradle")) - writer.WriteLine("\napply from: 'hmsLauncherTemplate.gradle'"); + string launcherTemplatePath = Application.dataPath + "/Huawei/Plugins/Android/hmsLauncherTemplate.gradle"; + FileUtil.ReplaceFile(launcherTemplatePath, Directory.GetParent(path).FullName + @"/launcher/hmsLauncherTemplate.gradle"); + using (var writer = File.AppendText(Directory.GetParent(path).FullName + "/launcher/build.gradle")) + writer.WriteLine("\napply from: 'hmsLauncherTemplate.gradle'"); - string baseProjectTemplatePath = Application.dataPath + "/Huawei/Plugins/Android/hmsBaseProjectTemplate.gradle"; - FileUtil.ReplaceFile(baseProjectTemplatePath, Directory.GetParent(path).FullName + @"/hmsBaseProjectTemplate.gradle"); + string baseProjectTemplatePath = Application.dataPath + "/Huawei/Plugins/Android/hmsBaseProjectTemplate.gradle"; + FileUtil.ReplaceFile(baseProjectTemplatePath, Directory.GetParent(path).FullName + @"/hmsBaseProjectTemplate.gradle"); - //TODO: HMSMainKitsTabFactory.GetEnabledEditors() counts zero sometimes - // Get enabled Kits and check if they are one of the below, because only them needs to be updated to the latest version. - /*foreach (var toggle in HMSMainKitsTabFactory.GetEnabledEditors()) - { - if (toggle.GetType() == typeof(AccountToggleEditor) - || toggle.GetType() == typeof(PushToggleEditor) - || toggle.GetType() == typeof(IAPToggleEditor) - || toggle.GetType() == typeof(NearbyServiceToggleEditor) - || toggle.GetType() == typeof(AnalyticsToggleEditor)) + //TODO: HMSMainKitsTabFactory.GetEnabledEditors() counts zero sometimes + // Get enabled Kits and check if they are one of the below, because only them needs to be updated to the latest version. + /*foreach (var toggle in HMSMainKitsTabFactory.GetEnabledEditors()) { - GradleVersionFixer(File.ReadAllText(Directory.GetParent(path).FullName + "/build.gradle"), path); - } - }*/ + if (toggle.GetType() == typeof(AccountToggleEditor) + || toggle.GetType() == typeof(PushToggleEditor) + || toggle.GetType() == typeof(IAPToggleEditor) + || toggle.GetType() == typeof(NearbyServiceToggleEditor) + || toggle.GetType() == typeof(AnalyticsToggleEditor)) + { + GradleVersionFixer(File.ReadAllText(Directory.GetParent(path).FullName + "/build.gradle"), path); + } + }*/ #if UNITY_2022_2_OR_NEWER GradleVersionFixer(File.ReadAllText(Directory.GetParent(path).FullName + "/build.gradle"), path); #else - GradleVersionFixer(File.ReadAllText(Directory.GetParent(path).FullName + "/build.gradle"), path); - using (var writer = File.AppendText(Directory.GetParent(path).FullName + "/build.gradle")) - writer.WriteLine("\napply from: 'hmsBaseProjectTemplate.gradle'"); + GradleVersionFixer(File.ReadAllText(Directory.GetParent(path).FullName + "/build.gradle"), path); + using (var writer = File.AppendText(Directory.GetParent(path).FullName + "/build.gradle")) + writer.WriteLine("\napply from: 'hmsBaseProjectTemplate.gradle'"); #endif - if (HMSMainEditorSettings.Instance.Settings.GetBool(PushToggleEditor.PushKitEnabled)) - { - string unityPlayerActivityJavaPath = path + @"/src/main/java/com/unity3d/player/UnityPlayerActivity.java"; - - var sb = new StringBuilder(); - FileStream fs = new FileStream(unityPlayerActivityJavaPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None); - using (StreamReader sr = new StreamReader(fs)) + if (HMSMainEditorSettings.Instance.Settings.GetBool(PushToggleEditor.PushKitEnabled)) { - string line; - do + string unityPlayerActivityJavaPath = path + @"/src/main/java/com/unity3d/player/UnityPlayerActivity.java"; + + var sb = new StringBuilder(); + FileStream fs = new FileStream(unityPlayerActivityJavaPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None); + using (StreamReader sr = new StreamReader(fs)) { - line = sr.ReadLine(); - sb.AppendLine(line); + string line; + do + { + line = sr.ReadLine(); + sb.AppendLine(line); + } + while (line.Trim().TrimStart().TrimEnd() != "import android.os.Process;"); + sb.AppendLine("import org.m0skit0.android.hms.unity.push.PushBridge;"); + + do + { + line = sr.ReadLine(); + sb.AppendLine(line); + } + while (line.Trim().TrimStart().TrimEnd() != "mUnityPlayer.newIntent(intent);"); + sb.AppendLine("PushBridge.OnNotificationMessage(intent);"); + sb.Append(sr.ReadToEnd()); } - while (line.Trim().TrimStart().TrimEnd() != "import android.os.Process;"); - sb.AppendLine("import org.m0skit0.android.hms.unity.push.PushBridge;"); - do + using (var sw = new StreamWriter(unityPlayerActivityJavaPath)) { - line = sr.ReadLine(); - sb.AppendLine(line); + sw.Write(sb.ToString()); } - while (line.Trim().TrimStart().TrimEnd() != "mUnityPlayer.newIntent(intent);"); - sb.AppendLine("PushBridge.OnNotificationMessage(intent);"); - sb.Append(sr.ReadToEnd()); - } - - using (var sw = new StreamWriter(unityPlayerActivityJavaPath)) - { - sw.Write(sb.ToString()); } - } #elif UNITY_2018_1_OR_NEWER string hmsMainTemplatePath = Application.dataPath + @"/Huawei/Plugins/Android/hmsMainTemplate.gradle"; @@ -165,8 +166,9 @@ public void OnPostGenerateGradleAndroidProject(string path) GradleVersionFixer(File.ReadAllText(path + "/build.gradle"), path); destPath = Path.Combine(path, fileName); #endif - if (File.Exists(destPath)) - FileUtil.DeleteFileOrDirectory(destPath); - File.Copy(filePath, destPath); + if (File.Exists(destPath)) + FileUtil.DeleteFileOrDirectory(destPath); + File.Copy(filePath, destPath); + } } } diff --git a/Assets/Huawei/Editor/Utils/HMSPluginUpdater.cs b/Assets/Huawei/Editor/Utils/HMSPluginUpdater.cs index 77336cfb..8348f237 100644 --- a/Assets/Huawei/Editor/Utils/HMSPluginUpdater.cs +++ b/Assets/Huawei/Editor/Utils/HMSPluginUpdater.cs @@ -1,5 +1,4 @@ -using HmsPlugin; -using System; +using System; using System.Collections; using System.IO; using System.Threading.Tasks; @@ -7,183 +6,186 @@ using UnityEngine; using UnityEngine.Networking; -internal class HMSPluginUpdater +namespace HmsPlugin { - public static string sessionState = "hms_checked_update"; + internal class HMSPluginUpdater + { + public static string sessionState = "hms_checked_update"; - static HMSPluginUpdateRequest request; + static HMSPluginUpdateRequest request; - internal static void Request(bool ignoreSession = false) - { - if (!ignoreSession && SessionState.GetBool(sessionState, false)) + internal static void Request(bool ignoreSession = false) { - return; - } + if (!ignoreSession && SessionState.GetBool(sessionState, false)) + { + return; + } - SessionState.SetBool(sessionState, true); - HMSEditorUtils.UpdateAssemblyDefinitions(HMSPluginSettings.Instance.Settings.GetBool(PluginToggleEditor.PluginEnabled, true)); + SessionState.SetBool(sessionState, true); + HMSEditorUtils.UpdateAssemblyDefinitions(HMSPluginSettings.Instance.Settings.GetBool(PluginToggleEditor.PluginEnabled, true)); - Task.Delay(2000).ContinueWith(t => StartUpdateRequest(ignoreSession), TaskScheduler.FromCurrentSynchronizationContext()); - } + Task.Delay(2000).ContinueWith(t => StartUpdateRequest(ignoreSession), TaskScheduler.FromCurrentSynchronizationContext()); + } - private static void StartUpdateRequest(bool ignoreSession) - { - var obj = new GameObject("HMSPluginUpdateRequest") + private static void StartUpdateRequest(bool ignoreSession) { - hideFlags = HideFlags.HideAndDontSave - }; + var obj = new GameObject("HMSPluginUpdateRequest") + { + hideFlags = HideFlags.HideAndDontSave + }; - request = obj.AddComponent(); - request.StartRequest(ignoreSession); + request = obj.AddComponent(); + request.StartRequest(ignoreSession); + } } -} -public class HMSPluginUpdateRequest : MonoBehaviour -{ - public static string sessionStatePersisted = "hms_checked_update_persisted"; + public class HMSPluginUpdateRequest : MonoBehaviour + { + public static string sessionStatePersisted = "hms_checked_update_persisted"; - private IEnumerator coroutine; + private IEnumerator coroutine; - public void StartRequest(bool ignoreSession = false) - { - coroutine = FetchLatestVersion(ignoreSession); - StartCoroutine(coroutine); - } + public void StartRequest(bool ignoreSession = false) + { + coroutine = FetchLatestVersion(ignoreSession); + StartCoroutine(coroutine); + } - private IEnumerator FetchLatestVersion(bool ignoreSession) - { - var request = UnityWebRequest.Get("https://api.github.com/repos/EvilMindDevs/hms-unity-plugin/tags"); - yield return request.SendWebRequest(); + private IEnumerator FetchLatestVersion(bool ignoreSession) + { + var request = UnityWebRequest.Get("https://api.github.com/repos/EvilMindDevs/hms-unity-plugin/tags"); + yield return request.SendWebRequest(); #if UNITY_2020_1_OR_NEWER - var requestError = - request.result == UnityWebRequest.Result.ProtocolError || - request.result == UnityWebRequest.Result.ConnectionError; + var requestError = + request.result == UnityWebRequest.Result.ProtocolError || + request.result == UnityWebRequest.Result.ConnectionError; #else - bool requestError = - request.isNetworkError || - request.isHttpError; + bool requestError = + request.isNetworkError || + request.isHttpError; #endif - if (requestError) - { - if (request.error == null) - { - Debug.LogError("HMS Plugin Update Checker encountered an unknown error"); - } - else + if (requestError) { - Debug.LogError("HMS Plugin Update Checker encountered an error: " + request.error); + if (request.error == null) + { + Debug.LogError("HMS Plugin Update Checker encountered an unknown error"); + } + else + { + Debug.LogError("HMS Plugin Update Checker encountered an error: " + request.error); + } + DestroyImmediate(gameObject); + yield break; } - DestroyImmediate(gameObject); - yield break; - } - var json = JsonUtility.FromJson("{\"tags\":" + request.downloadHandler.text + "}"); - string latestVersionString = FindTheLatestVersion(json); - string currentVersionString = File.ReadAllText(Application.dataPath + "/Huawei/VERSION"); + var json = JsonUtility.FromJson("{\"tags\":" + request.downloadHandler.text + "}"); + string latestVersionString = FindTheLatestVersion(json); + string currentVersionString = File.ReadAllText(Application.dataPath + "/Huawei/VERSION"); - long latestVersion = ConvertVersionToLong(latestVersionString); - long currentVersion = ConvertVersionToLong(currentVersionString); - - if (latestVersion > currentVersion) - { - string updateMessage = $"A new version of the HMS Unity Plugin ({latestVersionString}) is available. You are currently using {currentVersionString}"; - Debug.LogWarning($"{updateMessage}\nYou can check releases page of our github. https://github.com/EvilMindDevs/hms-unity-plugin/releases"); + long latestVersion = ConvertVersionToLong(latestVersionString); + long currentVersion = ConvertVersionToLong(currentVersionString); - if (!ignoreSession) + if (latestVersion > currentVersion) { - if (SessionState.GetBool(sessionStatePersisted, false)) yield return null; - SessionState.SetBool(sessionStatePersisted, true); - if (!EditorPrefs.GetBool($"{sessionStatePersisted}{latestVersionString}", false)) + string updateMessage = $"A new version of the HMS Unity Plugin ({latestVersionString}) is available. You are currently using {currentVersionString}"; + Debug.LogWarning($"{updateMessage}\nYou can check releases page of our github. https://github.com/EvilMindDevs/hms-unity-plugin/releases"); + + if (!ignoreSession) + { + if (SessionState.GetBool(sessionStatePersisted, false)) yield return null; + SessionState.SetBool(sessionStatePersisted, true); + if (!EditorPrefs.GetBool($"{sessionStatePersisted}{latestVersionString}", false)) + DisplayDialog(latestVersionString, updateMessage); + } + else + { DisplayDialog(latestVersionString, updateMessage); + } } - else + else if (ignoreSession) { - DisplayDialog(latestVersionString, updateMessage); + EditorUtility.DisplayDialog("HMS Unity Plugin", "Your version is up to date", "Ok"); } + + + DestroyImmediate(gameObject); } - else if (ignoreSession) + + private string FindTheLatestVersion(TagList list) { - EditorUtility.DisplayDialog("HMS Unity Plugin", "Your version is up to date", "Ok"); - } + string latestVersion = "0.0.0"; + foreach (var tag in list.tags) + { + string tempVer = tag.name.RemoveAfter('-').Replace("v", ""); - DestroyImmediate(gameObject); - } + if (ConvertVersionToLong(latestVersion) < ConvertVersionToLong(tempVer)) + { + latestVersion = tempVer; + } + } - private string FindTheLatestVersion(TagList list) - { - string latestVersion = "0.0.0"; + return latestVersion; + } - foreach (var tag in list.tags) + // Helper method to convert version string to long + private long ConvertVersionToLong(string versionString) { - string tempVer = tag.name.RemoveAfter('-').Replace("v", ""); - - if (ConvertVersionToLong(latestVersion) < ConvertVersionToLong(tempVer)) + if (long.TryParse(versionString.Replace(".", "0").PadRight(8, '0'), out long version)) + { + return version; + } + else { - latestVersion = tempVer; + // Handle the case where the version string could not be parsed to a long + // This could be setting a default value, logging an error, etc. + return 0; } } - return latestVersion; - } - - // Helper method to convert version string to long - private long ConvertVersionToLong(string versionString) - { - if (long.TryParse(versionString.Replace(".", "0").PadRight(8, '0'), out long version)) + private static void DisplayDialog(string latestVersionString, string updateMessage) { - return version; + int option = EditorUtility.DisplayDialogComplex("HMS Unity Plugin Update available", updateMessage + ". Do you want to download the new version ?", "Don't Remind", "No", "Yes"); + switch (option) + { + case 0: + EditorPrefs.SetBool(sessionStatePersisted + latestVersionString, true); + break; + case 1: + // No action needed + break; + case 2: + Application.OpenURL("https://github.com/EvilMindDevs/hms-unity-plugin/releases"); + break; + default: + // All cases are handled + break; + } } - else + + [Serializable] + private class Commit { - // Handle the case where the version string could not be parsed to a long - // This could be setting a default value, logging an error, etc. - return 0; + public string sha; + public string url; } - } - private static void DisplayDialog(string latestVersionString, string updateMessage) - { - int option = EditorUtility.DisplayDialogComplex("HMS Unity Plugin Update available", updateMessage + ". Do you want to download the new version ?", "Don't Remind", "No", "Yes"); - switch (option) + [Serializable] + private class Tag { - case 0: - EditorPrefs.SetBool(sessionStatePersisted + latestVersionString, true); - break; - case 1: - // No action needed - break; - case 2: - Application.OpenURL("https://github.com/EvilMindDevs/hms-unity-plugin/releases"); - break; - default: - // All cases are handled - break; + public string name; + public string zipball_url; + public string tarball_url; + public Commit commit; + public string node_id; } - } - [Serializable] - private class Commit - { - public string sha; - public string url; - } - - [Serializable] - private class Tag - { - public string name; - public string zipball_url; - public string tarball_url; - public Commit commit; - public string node_id; - } - - [Serializable] - private class TagList - { - public Tag[] tags; + [Serializable] + private class TagList + { + public Tag[] tags; + } } } diff --git a/Assets/Huawei/Editor/Utils/HMSPluginUpdaterInit.cs b/Assets/Huawei/Editor/Utils/HMSPluginUpdaterInit.cs index f4da6b89..3423df89 100644 --- a/Assets/Huawei/Editor/Utils/HMSPluginUpdaterInit.cs +++ b/Assets/Huawei/Editor/Utils/HMSPluginUpdaterInit.cs @@ -1,18 +1,20 @@ #if UNITY_EDITOR using UnityEditor; - -[InitializeOnLoad] -public class HMSPluginUpdaterInit : AssetPostprocessor +namespace HmsPlugin { - static HMSPluginUpdaterInit() + [InitializeOnLoad] + public class HMSPluginUpdaterInit : AssetPostprocessor { - EditorApplication.delayCall += () => + static HMSPluginUpdaterInit() { EditorApplication.delayCall += () => { - EditorApplication.delayCall += () => HMSPluginUpdater.Request(); + EditorApplication.delayCall += () => + { + EditorApplication.delayCall += () => HMSPluginUpdater.Request(); + }; }; - }; + } } -} #endif +} diff --git a/Assets/Huawei/Editor/Utils/HMSWebRequestHelper.cs b/Assets/Huawei/Editor/Utils/HMSWebRequestHelper.cs index fde675c0..1440be0a 100644 --- a/Assets/Huawei/Editor/Utils/HMSWebRequestHelper.cs +++ b/Assets/Huawei/Editor/Utils/HMSWebRequestHelper.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; using System.Linq; @@ -8,218 +8,143 @@ using UnityEngine; using UnityEngine.Networking; -internal class HMSWebRequestHelper +namespace HmsPlugin { - private static HMSWebRequestHelper _instance; - public static HMSWebRequestHelper Instance + internal class HMSWebRequestHelper { - get + private static HMSWebRequestHelper _instance; + public static HMSWebRequestHelper Instance { - if (_instance == null) + get { - _instance = new HMSWebRequestHelper(); - } - if (persistedObj == null || behavior == null) - { - _instance.CheckPersistency(); - } + if (_instance == null) + { + _instance = new HMSWebRequestHelper(); + } + if (persistedObj == null || behavior == null) + { + _instance.CheckPersistency(); + } - return _instance; + return _instance; + } } - } - private static GameObject persistedObj; - private static HMSWebRequestBehaviour behavior; + private static GameObject persistedObj; + private static HMSWebRequestBehaviour behavior; - public void CheckPersistency() - { - var objs = GameObject.FindObjectsOfType(); - if (objs != null && objs.Any()) + public void CheckPersistency() { - foreach (var item in objs) + var objs = GameObject.FindObjectsOfType(); + if (objs != null && objs.Any()) { - UnityEngine.Object.DestroyImmediate(item.gameObject); + foreach (var item in objs) + { + UnityEngine.Object.DestroyImmediate(item.gameObject); + } } + persistedObj = new GameObject("[HMSWebRequestHelper]"); + persistedObj.hideFlags = HideFlags.HideAndDontSave; + behavior = persistedObj.AddComponent(); } - persistedObj = new GameObject("[HMSWebRequestHelper]"); - persistedObj.hideFlags = HideFlags.HideAndDontSave; - behavior = persistedObj.AddComponent(); - } - internal void PostRequest(string url, string bodyJsonString, Action callback) - { - behavior.Post(url, bodyJsonString, callback); - } - - internal async Task PostRequest(string url, string bodyJsonString) - { - return await behavior.PostAsync(url, bodyJsonString); - } - - internal void PostRequest(string url, string bodyJsonString, Dictionary requestHeaders, Action callback) - { - behavior.Post(url, bodyJsonString, requestHeaders, callback); - } - - internal void GetRequest(string url, Dictionary requestHeaders, Action callback) - { - behavior.Get(url, requestHeaders, callback); - } - internal void PostFormRequest(string url, MultipartFormFileSection file, string authCode, string fileCount, string parseType, Action callback, string progressBarTitle = null, string progressBarDesc = null) - { - behavior.PostFormData(url, file, authCode, fileCount, parseType, callback, progressBarTitle, progressBarDesc); - } - internal void PutRequest(string url, string bodyJsonString, Dictionary requestHeaders, Action callback) - { - behavior.Put(url, bodyJsonString, requestHeaders, callback); - } - - internal void GetFile(string url, string path, Action result = null) - { - behavior.GetFile(url, path, result); - } -} - -public class HMSWebRequestBehaviour : MonoBehaviour -{ - public void Post(string url, string bodyJsonString, Action callback) - { - StartCoroutine(PostCoroutine(url, bodyJsonString, callback)); - } - - public void Get(string url, Dictionary requestHeaders, Action callback) - { - StartCoroutine(GetCoroutine(url, requestHeaders, callback)); - } - - public void Post(string url, string bodyJsonString, Dictionary requestHeaders, Action callback) - { - StartCoroutine(PostCoroutine(url, bodyJsonString, requestHeaders, callback)); - } + internal void PostRequest(string url, string bodyJsonString, Action callback) + { + behavior.Post(url, bodyJsonString, callback); + } - public void Put(string url, string bodyJsonString, Dictionary requestHeaders, Action callback) - { - StartCoroutine(PutCoroutine(url, bodyJsonString, requestHeaders, callback)); - } + internal async Task PostRequest(string url, string bodyJsonString) + { + return await behavior.PostAsync(url, bodyJsonString); + } - public void PostFormData(string url, MultipartFormFileSection file, string authCode, string fileCount, string parseType, Action callback, string progressBarTitle = null, string progressBarDesc = null) - { - StartCoroutine(PostFormDataCoroutine(url, file, authCode, fileCount, parseType, callback, progressBarTitle, progressBarDesc)); - } + internal void PostRequest(string url, string bodyJsonString, Dictionary requestHeaders, Action callback) + { + behavior.Post(url, bodyJsonString, requestHeaders, callback); + } - public void GetFile(string url, string path, Action result = null) - { - StartCoroutine(GetFileCoroutine(url, path, result)); - } + internal void GetRequest(string url, Dictionary requestHeaders, Action callback) + { + behavior.Get(url, requestHeaders, callback); + } + internal void PostFormRequest(string url, MultipartFormFileSection file, string authCode, string fileCount, string parseType, Action callback, string progressBarTitle = null, string progressBarDesc = null) + { + behavior.PostFormData(url, file, authCode, fileCount, parseType, callback, progressBarTitle, progressBarDesc); + } + internal void PutRequest(string url, string bodyJsonString, Dictionary requestHeaders, Action callback) + { + behavior.Put(url, bodyJsonString, requestHeaders, callback); + } - public async Task PostAsync(string url, string bodyJsonString) - { - return await PostAsync(url, bodyJsonString, null); + internal void GetFile(string url, string path, Action result = null) + { + behavior.GetFile(url, path, result); + } } - public async Task PostAsync(string url, string bodyJsonString, Dictionary requestHeaders) + public class HMSWebRequestBehaviour : MonoBehaviour { - UnityWebRequest request = new UnityWebRequest(url, "POST"); - byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString); - request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); - request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); - request.SetRequestHeader("Content-Type", "application/json"); - if (requestHeaders != null) + public void Post(string url, string bodyJsonString, Action callback) { - foreach (var item in requestHeaders) - { - request.SetRequestHeader(item.Key, item.Value); - } + StartCoroutine(PostCoroutine(url, bodyJsonString, callback)); } - var asyncOp = request.SendWebRequest(); - while (true) + + public void Get(string url, Dictionary requestHeaders, Action callback) { - if (asyncOp.progress == 1) - break; + StartCoroutine(GetCoroutine(url, requestHeaders, callback)); } - return request; - } - public async Task PutAsync(string url, string bodyJsonString, Dictionary requestHeaders) - { - UnityWebRequest request = new UnityWebRequest(url, "PUT"); - byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString); - request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); - request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); - request.SetRequestHeader("Content-Type", "application/json"); - if (requestHeaders != null) + public void Post(string url, string bodyJsonString, Dictionary requestHeaders, Action callback) { - foreach (var item in requestHeaders) - { - request.SetRequestHeader(item.Key, item.Value); - } + StartCoroutine(PostCoroutine(url, bodyJsonString, requestHeaders, callback)); } - var asyncOp = request.SendWebRequest(); - while (true) + + public void Put(string url, string bodyJsonString, Dictionary requestHeaders, Action callback) { - if (asyncOp.progress == 1) - break; + StartCoroutine(PutCoroutine(url, bodyJsonString, requestHeaders, callback)); } - return request; - } - - private IEnumerator PostCoroutine(string url, string bodyJsonString, Action callback) - { - yield return PostCoroutine(url, bodyJsonString, null, callback); - } - private IEnumerator PostFormDataCoroutine(string url, MultipartFormFileSection file, string authCode, string fileCount, string parseType, Action callback, string progressBarTitle = null, string progressBarDesc = null) - { - var formData = new List(); - formData.Add(new MultipartFormDataSection("authCode", authCode)); - formData.Add(new MultipartFormDataSection("fileCount", fileCount)); - formData.Add(new MultipartFormDataSection("parseType", parseType)); - formData.Add(file); - UnityWebRequest request = UnityWebRequest.Post(url, formData); - var asyncOp = request.SendWebRequest(); - if (progressBarTitle != null && progressBarDesc != null) + public void PostFormData(string url, MultipartFormFileSection file, string authCode, string fileCount, string parseType, Action callback, string progressBarTitle = null, string progressBarDesc = null) { - while (!asyncOp.isDone) - { - EditorUtility.DisplayProgressBar(progressBarTitle, progressBarDesc, asyncOp.progress); - yield return null; - } + StartCoroutine(PostFormDataCoroutine(url, file, authCode, fileCount, parseType, callback, progressBarTitle, progressBarDesc)); } - else + + public void GetFile(string url, string path, Action result = null) { - yield return asyncOp; + StartCoroutine(GetFileCoroutine(url, path, result)); } -#if UNITY_2020_1_OR_NEWER - var requestError = - request.result == UnityWebRequest.Result.ProtocolError || - request.result == UnityWebRequest.Result.ConnectionError; -#else - bool requestError = - request.isNetworkError || - request.isHttpError; -#endif + public async Task PostAsync(string url, string bodyJsonString) + { + return await PostAsync(url, bodyJsonString, null); + } - if (requestError) + public async Task PostAsync(string url, string bodyJsonString, Dictionary requestHeaders) { - if (request.error == null) + UnityWebRequest request = new UnityWebRequest(url, "POST"); + byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString); + request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); + request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); + request.SetRequestHeader("Content-Type", "application/json"); + if (requestHeaders != null) { - Debug.LogError("HMSWebRequestHelper encountered an unknown error"); + foreach (var item in requestHeaders) + { + request.SetRequestHeader(item.Key, item.Value); + } } - else + var asyncOp = request.SendWebRequest(); + while (true) { - Debug.LogError("HMSWebRequestHelper encountered an error: " + request.error); + if (asyncOp.progress == 1) + break; } - yield break; + return request; } - callback(request); - } - - private IEnumerator PostCoroutine(string url, string bodyJsonString, Dictionary requestHeaders, Action callback) - { - using (UnityWebRequest request = new UnityWebRequest(url, "POST")) + public async Task PutAsync(string url, string bodyJsonString, Dictionary requestHeaders) { + UnityWebRequest request = new UnityWebRequest(url, "PUT"); byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString); request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); @@ -231,7 +156,45 @@ private IEnumerator PostCoroutine(string url, string bodyJsonString, Dictionary< request.SetRequestHeader(item.Key, item.Value); } } - yield return request.SendWebRequest(); + var asyncOp = request.SendWebRequest(); + while (true) + { + if (asyncOp.progress == 1) + break; + } + return request; + } + + private IEnumerator PostCoroutine(string url, string bodyJsonString, Action callback) + { + yield return PostCoroutine(url, bodyJsonString, null, callback); + } + k + k + private IEnumerator PostFormDataCoroutine(string url, MultipartFormFileSection file, string authCode, string fileCount, string parseType, Action callback, string progressBarTitle = null, string progressBarDesc = null) + { + var formData = new List + { + new MultipartFormDataSection("authCode", authCode), + new MultipartFormDataSection("fileCount", fileCount), + new MultipartFormDataSection("parseType", parseType), + file + }; + + UnityWebRequest request = UnityWebRequest.Post(url, formData); + var asyncOp = request.SendWebRequest(); + if (progressBarTitle != null && progressBarDesc != null) + { + while (!asyncOp.isDone) + { + EditorUtility.DisplayProgressBar(progressBarTitle, progressBarDesc, asyncOp.progress); + yield return null; + } + } + else + { + yield return asyncOp; + } #if UNITY_2020_1_OR_NEWER var requestError = @@ -258,125 +221,169 @@ private IEnumerator PostCoroutine(string url, string bodyJsonString, Dictionary< callback(request); } - } - private IEnumerator PutCoroutine(string url, string bodyJsonString, Dictionary requestHeaders, Action callback) - { - using (UnityWebRequest request = new UnityWebRequest(url, "PUT")) + private IEnumerator PostCoroutine(string url, string bodyJsonString, Dictionary requestHeaders, Action callback) { - byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString); - request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); - request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); - request.SetRequestHeader("Content-Type", "application/json"); - if (requestHeaders != null) + using (UnityWebRequest request = new UnityWebRequest(url, "POST")) { - foreach (var item in requestHeaders) + byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString); + request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); + request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); + request.SetRequestHeader("Content-Type", "application/json"); + if (requestHeaders != null) { - request.SetRequestHeader(item.Key, item.Value); + foreach (var item in requestHeaders) + { + request.SetRequestHeader(item.Key, item.Value); + } } - } - yield return request.SendWebRequest(); + yield return request.SendWebRequest(); #if UNITY_2020_1_OR_NEWER - var requestError = - request.result == UnityWebRequest.Result.ProtocolError || - request.result == UnityWebRequest.Result.ConnectionError; + var requestError = + request.result == UnityWebRequest.Result.ProtocolError || + request.result == UnityWebRequest.Result.ConnectionError; #else - bool requestError = - request.isNetworkError || - request.isHttpError; + bool requestError = + request.isNetworkError || + request.isHttpError; #endif - if (requestError) - { - if (request.error == null) - { - Debug.LogError("HMSWebRequestHelper encountered an unknown error"); - } - else + if (requestError) { - Debug.LogError("HMSWebRequestHelper encountered an error: " + request.error); + if (request.error == null) + { + Debug.LogError("HMSWebRequestHelper encountered an unknown error"); + } + else + { + Debug.LogError("HMSWebRequestHelper encountered an error: " + request.error); + } + yield break; } - yield break; - } - callback(request); + callback(request); + } } - } - private IEnumerator GetCoroutine(string url, Dictionary requestHeaders, Action callback) - { - using (UnityWebRequest request = new UnityWebRequest(url, "GET")) + private IEnumerator PutCoroutine(string url, string bodyJsonString, Dictionary requestHeaders, Action callback) { - request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); - request.SetRequestHeader("Content-Type", "application/json"); - if (requestHeaders != null) + using (UnityWebRequest request = new UnityWebRequest(url, "PUT")) { - foreach (var item in requestHeaders) + byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString); + request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); + request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); + request.SetRequestHeader("Content-Type", "application/json"); + if (requestHeaders != null) { - request.SetRequestHeader(item.Key, item.Value); + foreach (var item in requestHeaders) + { + request.SetRequestHeader(item.Key, item.Value); + } } - } - yield return request.SendWebRequest(); + yield return request.SendWebRequest(); #if UNITY_2020_1_OR_NEWER - var requestError = - request.result == UnityWebRequest.Result.ProtocolError || - request.result == UnityWebRequest.Result.ConnectionError; + var requestError = + request.result == UnityWebRequest.Result.ProtocolError || + request.result == UnityWebRequest.Result.ConnectionError; #else - bool requestError = - request.isNetworkError || - request.isHttpError; + bool requestError = + request.isNetworkError || + request.isHttpError; #endif - if (requestError) + if (requestError) + { + if (request.error == null) + { + Debug.LogError("HMSWebRequestHelper encountered an unknown error"); + } + else + { + Debug.LogError("HMSWebRequestHelper encountered an error: " + request.error); + } + yield break; + } + + callback(request); + } + } + + private IEnumerator GetCoroutine(string url, Dictionary requestHeaders, Action callback) + { + using (UnityWebRequest request = new UnityWebRequest(url, "GET")) { - if (request.error == null) + request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); + request.SetRequestHeader("Content-Type", "application/json"); + if (requestHeaders != null) { - Debug.LogError("HMSWebRequestHelper encountered an unknown error"); + foreach (var item in requestHeaders) + { + request.SetRequestHeader(item.Key, item.Value); + } } - else + yield return request.SendWebRequest(); + +#if UNITY_2020_1_OR_NEWER + var requestError = + request.result == UnityWebRequest.Result.ProtocolError || + request.result == UnityWebRequest.Result.ConnectionError; +#else + bool requestError = + request.isNetworkError || + request.isHttpError; +#endif + + if (requestError) { - Debug.LogError("HMSWebRequestHelper encountered an error: " + request.error); + if (request.error == null) + { + Debug.LogError("HMSWebRequestHelper encountered an unknown error"); + } + else + { + Debug.LogError("HMSWebRequestHelper encountered an error: " + request.error); + } + yield break; } - yield break; - } - callback(request); + callback(request); + } } - } - private IEnumerator GetFileCoroutine(string url, string path, Action result = null) - { - using (UnityWebRequest request = new UnityWebRequest(url, "GET")) + private IEnumerator GetFileCoroutine(string url, string path, Action result = null) { - request.downloadHandler = new DownloadHandlerFile(path, true); - yield return request.SendWebRequest(); + using (UnityWebRequest request = new UnityWebRequest(url, "GET")) + { + request.downloadHandler = new DownloadHandlerFile(path, true); + yield return request.SendWebRequest(); #if UNITY_2020_1_OR_NEWER - var requestError = - request.result == UnityWebRequest.Result.ProtocolError || - request.result == UnityWebRequest.Result.ConnectionError; + var requestError = + request.result == UnityWebRequest.Result.ProtocolError || + request.result == UnityWebRequest.Result.ConnectionError; #else - bool requestError = - request.isNetworkError || - request.isHttpError; + bool requestError = + request.isNetworkError || + request.isHttpError; #endif - if (requestError) - { - if (request.error == null) + if (requestError) { - Debug.LogError("HMSWebRequestHelper encountered an unknown error"); - } - else - { - Debug.LogError("HMSWebRequestHelper encountered an error: " + request.error); + if (request.error == null) + { + Debug.LogError("HMSWebRequestHelper encountered an unknown error"); + } + else + { + Debug.LogError("HMSWebRequestHelper encountered an error: " + request.error); + } + result?.Invoke(false); + yield break; } - result?.Invoke(false); - yield break; + result?.Invoke(true); } - result?.Invoke(true); } } } diff --git a/Assets/Huawei/Editor/Utils/HMSWebUtils.cs b/Assets/Huawei/Editor/Utils/HMSWebUtils.cs index 62b34308..3e760032 100644 --- a/Assets/Huawei/Editor/Utils/HMSWebUtils.cs +++ b/Assets/Huawei/Editor/Utils/HMSWebUtils.cs @@ -1,110 +1,113 @@ -using HmsPlugin; +using HmsPlugin; using System; using System.Threading.Tasks; using UnityEditor; using UnityEngine; -public static class HMSWebUtils +namespace HmsPlugin { - public static async Task GetAccessTokenAsync(string clientId = "", string clientSecret = "") + public static class HMSWebUtils { - if (string.IsNullOrEmpty(HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.ClientID, ""))) + public static async Task GetAccessTokenAsync(string clientId = "", string clientSecret = "") { - if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret)) //Abort here because it cant be empty to get the token. + if (string.IsNullOrEmpty(HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.ClientID, ""))) { - if (EditorUtility.DisplayDialog("Token Error", "Please enter clientId and clientSecret before obtaining the access token.", "Ok")) + if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret)) //Abort here because it cant be empty to get the token. { - HMSConnectAPIWindow.ShowWindow(); + if (EditorUtility.DisplayDialog("Token Error", "Please enter clientId and clientSecret before obtaining the access token.", "Ok")) + { + HMSConnectAPIWindow.ShowWindow(); + } + } + else + { + HMSConnectAPISettings.Instance.Settings.Set(HMSConnectAPISettings.ClientID, clientId); + HMSConnectAPISettings.Instance.Settings.Set(HMSConnectAPISettings.ClientSecret, clientSecret); + return await GetToken(); } } else { - HMSConnectAPISettings.Instance.Settings.Set(HMSConnectAPISettings.ClientID, clientId); - HMSConnectAPISettings.Instance.Settings.Set(HMSConnectAPISettings.ClientSecret, clientSecret); - return await GetToken(); - } - } - else - { - bool getNewToken = false; - if (!string.IsNullOrEmpty(clientId) && HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.ClientID) != clientId) - { - getNewToken = true; - HMSConnectAPISettings.Instance.Settings.Set(HMSConnectAPISettings.ClientID, clientId); - } + bool getNewToken = false; + if (!string.IsNullOrEmpty(clientId) && HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.ClientID) != clientId) + { + getNewToken = true; + HMSConnectAPISettings.Instance.Settings.Set(HMSConnectAPISettings.ClientID, clientId); + } - if (!string.IsNullOrEmpty(clientSecret) && HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.ClientSecret) != clientSecret) - { - getNewToken = true; - HMSConnectAPISettings.Instance.Settings.Set(HMSConnectAPISettings.ClientSecret, clientSecret); - } + if (!string.IsNullOrEmpty(clientSecret) && HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.ClientSecret) != clientSecret) + { + getNewToken = true; + HMSConnectAPISettings.Instance.Settings.Set(HMSConnectAPISettings.ClientSecret, clientSecret); + } - if (!string.IsNullOrEmpty(HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.AccessToken))) - { - var endDate = new DateTime(HMSConnectAPISettings.Instance.Settings.GetLong(HMSConnectAPISettings.ExpiresInTicks)); - if (endDate > DateTime.UtcNow && !getNewToken) + if (!string.IsNullOrEmpty(HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.AccessToken))) { - return HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.AccessToken); + var endDate = new DateTime(HMSConnectAPISettings.Instance.Settings.GetLong(HMSConnectAPISettings.ExpiresInTicks)); + if (endDate > DateTime.UtcNow && !getNewToken) + { + return HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.AccessToken); + } } + return await GetToken(); } - return await GetToken(); + + return string.Empty; } - return string.Empty; - } + private static async Task GetToken() + { + Debug.Log("[HMSWebUtils] Getting token from AGC."); + var tokenRequest = new TokenRequest("client_credentials", HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.ClientID), HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.ClientSecret)); + var request = await HMSWebRequestHelper.Instance.PostRequest("https://connect-api.cloud.huawei.com/api/oauth2/v1/token", JsonUtility.ToJson(tokenRequest)); - private static async Task GetToken() - { - Debug.Log("[HMSWebUtils] Getting token from AGC."); - var tokenRequest = new TokenRequest("client_credentials", HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.ClientID), HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.ClientSecret)); - var request = await HMSWebRequestHelper.Instance.PostRequest("https://connect-api.cloud.huawei.com/api/oauth2/v1/token", JsonUtility.ToJson(tokenRequest)); + var response = JsonUtility.FromJson(request.downloadHandler.text); - var response = JsonUtility.FromJson(request.downloadHandler.text); + if (response.ret.code == 0) + { + HMSConnectAPISettings.Instance.Settings.Set(HMSConnectAPISettings.AccessToken, response.access_token); + HMSConnectAPISettings.Instance.Settings.SetLong(HMSConnectAPISettings.ExpiresInTicks, DateTime.UtcNow.AddSeconds(response.expires_in).Ticks); + return response.access_token; + } + else + { + Debug.LogError($"[HMSWebUtils] GetToken Error on response. ErrorCode: {response.ret.code}, ErrorMessage: {response.ret.msg}."); + HMSConnectAPISettings.Instance.Settings.Set(HMSConnectAPISettings.AccessToken, string.Empty); + HMSConnectAPISettings.Instance.Settings.SetLong(HMSConnectAPISettings.ExpiresInTicks, 0); + } - if (response.ret.code == 0) - { - HMSConnectAPISettings.Instance.Settings.Set(HMSConnectAPISettings.AccessToken, response.access_token); - HMSConnectAPISettings.Instance.Settings.SetLong(HMSConnectAPISettings.ExpiresInTicks, DateTime.UtcNow.AddSeconds(response.expires_in).Ticks); + request.Dispose(); return response.access_token; } - else - { - Debug.LogError($"[HMSWebUtils] GetToken Error on response. ErrorCode: {response.ret.code}, ErrorMessage: {response.ret.msg}."); - HMSConnectAPISettings.Instance.Settings.Set(HMSConnectAPISettings.AccessToken, string.Empty); - HMSConnectAPISettings.Instance.Settings.SetLong(HMSConnectAPISettings.ExpiresInTicks, 0); - } - request.Dispose(); - return response.access_token; - } + [Serializable] + private class TokenRequest + { + public string grant_type; + public string client_id; + public string client_secret; - [Serializable] - private class TokenRequest - { - public string grant_type; - public string client_id; - public string client_secret; + public TokenRequest(string grant_type, string client_id, string client_secret) + { + this.grant_type = grant_type; + this.client_id = client_id; + this.client_secret = client_secret; + } + } - public TokenRequest(string grant_type, string client_id, string client_secret) + [Serializable] + private class TokenResponse { - this.grant_type = grant_type; - this.client_id = client_id; - this.client_secret = client_secret; + public string access_token; + public long expires_in; + public Ret ret; } - } - - [Serializable] - private class TokenResponse - { - public string access_token; - public long expires_in; - public Ret ret; - } - [Serializable] - private class Ret - { - public long code; - public string msg; + [Serializable] + private class Ret + { + public long code; + public string msg; + } } } diff --git a/Assets/Huawei/Editor/View/ConnectAPI/HMSConnectAPITabFactory.cs b/Assets/Huawei/Editor/View/ConnectAPI/HMSConnectAPITabFactory.cs index de1dbb79..8f056620 100644 --- a/Assets/Huawei/Editor/View/ConnectAPI/HMSConnectAPITabFactory.cs +++ b/Assets/Huawei/Editor/View/ConnectAPI/HMSConnectAPITabFactory.cs @@ -1,29 +1,30 @@ -using HmsPlugin; -using HmsPlugin.Button; +using HmsPlugin.Button; using HmsPlugin.ConnectAPI; -using HmsPlugin.Label; using System.IO; using UnityEngine; -internal class HMSConnectAPITabFactory +namespace HmsPlugin { - private static string versionInfo = ""; - - static HMSConnectAPITabFactory() + internal class HMSConnectAPITabFactory { - versionInfo = File.ReadAllText(Application.dataPath + "/Huawei/VERSION"); - } + private static string versionInfo = ""; - public static TabView CreateConnectAPITab(TabBar tabBar) - { - var tab = new TabView("Connect API"); - tabBar.AddTab(tab); + static HMSConnectAPITabFactory() + { + versionInfo = File.ReadAllText(Application.dataPath + "/Huawei/VERSION"); + } + + public static TabView CreateConnectAPITab(TabBar tabBar) + { + var tab = new TabView("Connect API"); + tabBar.AddTab(tab); - tab.AddDrawer(new HorizontalLine()); - tab.AddDrawer(new TokenObtainerEditor()); - tab.AddDrawer(new HorizontalLine()); - tab.AddDrawer(new Spacer()); - tab.AddDrawer(new Clickable(new Label("HMS Unity Plugin v" + versionInfo).SetBold(true), () => { Application.OpenURL("https://github.com/EvilMindDevs/hms-unity-plugin/"); })); - return tab; + tab.AddDrawer(new HorizontalLine()); + tab.AddDrawer(new TokenObtainerEditor()); + tab.AddDrawer(new HorizontalLine()); + tab.AddDrawer(new Spacer()); + tab.AddDrawer(new Clickable(new Label.Label("HMS Unity Plugin v" + versionInfo).SetBold(true), () => { Application.OpenURL("https://github.com/EvilMindDevs/hms-unity-plugin/"); })); + return tab; + } } } diff --git a/Assets/Huawei/Editor/View/ConnectAPI/HMSConnectAPIWindow.cs b/Assets/Huawei/Editor/View/ConnectAPI/HMSConnectAPIWindow.cs index 2d86fc87..31083f70 100644 --- a/Assets/Huawei/Editor/View/ConnectAPI/HMSConnectAPIWindow.cs +++ b/Assets/Huawei/Editor/View/ConnectAPI/HMSConnectAPIWindow.cs @@ -1,20 +1,22 @@ -using HmsPlugin; -using HmsPlugin.Window; +using HmsPlugin.Window; using UnityEditor; -public class HMSConnectAPIWindow : HMSEditorWindow +namespace HmsPlugin { - [MenuItem("Huawei/Connect API/Token Obtainer")] - public static void ShowWindow() + public class HMSConnectAPIWindow : HMSEditorWindow { - GetWindow(typeof(HMSConnectAPIWindow), false, "HMS Connect API"); - } + [MenuItem("Huawei/Connect API/Token Obtainer")] + public static void ShowWindow() + { + GetWindow(typeof(HMSConnectAPIWindow), false, "HMS Connect API"); + } - public override IDrawer CreateDrawer() - { - var tabBar = new TabBar(); - HMSConnectAPITabFactory.CreateConnectAPITab(tabBar); - return tabBar; + public override IDrawer CreateDrawer() + { + var tabBar = new TabBar(); + HMSConnectAPITabFactory.CreateConnectAPITab(tabBar); + return tabBar; + } } -} +} diff --git a/Assets/Huawei/Editor/View/KeyToolTab/HMSKeyToolWindow.cs b/Assets/Huawei/Editor/View/KeyToolTab/HMSKeyToolWindow.cs index e49b7135..259c51d1 100644 --- a/Assets/Huawei/Editor/View/KeyToolTab/HMSKeyToolWindow.cs +++ b/Assets/Huawei/Editor/View/KeyToolTab/HMSKeyToolWindow.cs @@ -7,231 +7,234 @@ using UnityEditor; using UnityEngine; -public class HMSKeyToolWindow : EditorWindow +namespace HmsPlugin { - #region Variables - private const string KeyToolHelpCommand = "-help"; + public class HMSKeyToolWindow : EditorWindow + { + #region Variables + private const string KeyToolHelpCommand = "-help"; - // File and password information. - private string filePath = string.Empty; - private string password = string.Empty; - private string aliasPassword = string.Empty; - private List aliases = new List(); - private int selectedAliasIndex = 0; + // File and password information. + private string filePath = string.Empty; + private string password = string.Empty; + private string aliasPassword = string.Empty; + private List aliases = new List(); + private int selectedAliasIndex = 0; - // Drag-and-drop state. - private bool isKeystoreDropped = false; + // Drag-and-drop state. + private bool isKeystoreDropped = false; - // SHA-256 result and command execution. - private string sha256 = string.Empty; - private bool isExecutable = false; + // SHA-256 result and command execution. + private string sha256 = string.Empty; + private bool isExecutable = false; - #endregion + #endregion - void OnGUI() - { - GUILayout.Label("Key Tool Drag & Drop Tool", EditorStyles.boldLabel); - EditorGUILayout.Space(); - EditorGUILayout.HelpBox("Drag and drop your keystore file below to generate SHA-256.", MessageType.Info); - EditorGUILayout.Space(); + void OnGUI() + { + GUILayout.Label("Key Tool Drag & Drop Tool", EditorStyles.boldLabel); + EditorGUILayout.Space(); + EditorGUILayout.HelpBox("Drag and drop your keystore file below to generate SHA-256.", MessageType.Info); + EditorGUILayout.Space(); - // Drag and drop area. - Rect dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true)); - GUI.Box(dropArea, "Drag & Drop Keystore File Here"); - HandleDragAndDrop(dropArea); + // Drag and drop area. + Rect dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true)); + GUI.Box(dropArea, "Drag & Drop Keystore File Here"); + HandleDragAndDrop(dropArea); - if (isKeystoreDropped) - { - ShowPasswordField("Keystore", ref password, ref isExecutable); - if (aliases.Count > 0) + if (isKeystoreDropped) { - ShowAliasSelection(); - ShowPasswordField("Alias", ref aliasPassword, ref isExecutable); + ShowPasswordField("Keystore", ref password, ref isExecutable); + if (aliases.Count > 0) + { + ShowAliasSelection(); + ShowPasswordField("Alias", ref aliasPassword, ref isExecutable); + } + ShowActionButton(); + ShowSHA256Result(); } - ShowActionButton(); - ShowSHA256Result(); - } - } - private void ShowPasswordField(string label, ref string passwordField, ref bool controlState) - { - EditorGUILayout.Space(); - string enteredPassword = EditorGUILayout.PasswordField($"{label} Password", passwordField); - - if (!string.IsNullOrWhiteSpace(enteredPassword)) - { - passwordField = enteredPassword; - controlState = true; - } - } - private void ShowAliasSelection() - { - EditorGUILayout.Space(); - GUILayout.Label("Select your alias:"); - EditorGUI.BeginChangeCheck(); - selectedAliasIndex = EditorGUILayout.Popup("Alias", selectedAliasIndex, aliases.ToArray()); - if (EditorGUI.EndChangeCheck()) - { - sha256 = string.Empty; - aliasPassword = string.Empty; } - } - private void ShowActionButton() - { - if (isExecutable) + private void ShowPasswordField(string label, ref string passwordField, ref bool controlState) { EditorGUILayout.Space(); - string buttonName = aliases.Count > 0 ? "Obtain SHA-256" : "Run"; - if (GUILayout.Button(buttonName)) + string enteredPassword = EditorGUILayout.PasswordField($"{label} Password", passwordField); + + if (!string.IsNullOrWhiteSpace(enteredPassword)) { - ExecuteKeyTool(); + passwordField = enteredPassword; + controlState = true; } } - } - private void ShowSHA256Result() - { - if (!string.IsNullOrWhiteSpace(sha256)) + private void ShowAliasSelection() { EditorGUILayout.Space(); - GUILayout.Label("Selected File: " + Path.GetFileName(filePath)); - EditorGUILayout.Space(); - GUILayout.Label("Your SHA-256: \n" + sha256, EditorStyles.wordWrappedLabel); - EditorGUILayout.Space(); - if (GUILayout.Button("Copy SHA-256 to Clipboard")) + GUILayout.Label("Select your alias:"); + EditorGUI.BeginChangeCheck(); + selectedAliasIndex = EditorGUILayout.Popup("Alias", selectedAliasIndex, aliases.ToArray()); + if (EditorGUI.EndChangeCheck()) { - GUIUtility.systemCopyBuffer = sha256; - EditorUtility.DisplayDialog("SHA-256 Copied", "The SHA-256 hash has been copied to clipboard.", "OK"); + sha256 = string.Empty; + aliasPassword = string.Empty; } } - } - private void HandleDragAndDrop(Rect dropArea) - { - Event evt = Event.current; - if ((evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform) && dropArea.Contains(evt.mousePosition)) + private void ShowActionButton() { - DragAndDrop.visualMode = DragAndDropVisualMode.Copy; - if (evt.type == EventType.DragPerform || evt.type == EventType.DragUpdated) - { - DragDropOperations(); - } - else if (evt.type == EventType.DragExited) + if (isExecutable) { - DragAndDrop.PrepareStartDrag(); + EditorGUILayout.Space(); + string buttonName = aliases.Count > 0 ? "Obtain SHA-256" : "Run"; + if (GUILayout.Button(buttonName)) + { + ExecuteKeyTool(); + } } - evt.Use(); } - } - private void DragDropOperations() - { - DragAndDrop.AcceptDrag(); - DragAndDrop.activeControlID = GUIUtility.GetControlID(FocusType.Passive); - - filePath = DragAndDrop.paths.FirstOrDefault() ?? string.Empty; - isKeystoreDropped = !string.IsNullOrWhiteSpace(filePath) && filePath.EndsWith(".keystore", StringComparison.OrdinalIgnoreCase); - if (!isKeystoreDropped) + private void ShowSHA256Result() { - EditorUtility.DisplayDialog("Invalid File", "Please drop a .keystore file.", "OK"); - } - else - { - isExecutable = false; - sha256 = string.Empty; - aliases = new List(); - password = string.Empty; - aliasPassword = string.Empty; - } - } - private void ExecuteKeyTool() - { - // Check if KeyTool executable is available. - string keytoolPath = CheckKeyTool(); - if (keytoolPath == "Keytool is not available.") - { - EditorUtility.DisplayDialog("Keytool Not Found", "Unable to find Keytool in your environment.", "OK"); - return; + if (!string.IsNullOrWhiteSpace(sha256)) + { + EditorGUILayout.Space(); + GUILayout.Label("Selected File: " + Path.GetFileName(filePath)); + EditorGUILayout.Space(); + GUILayout.Label("Your SHA-256: \n" + sha256, EditorStyles.wordWrappedLabel); + EditorGUILayout.Space(); + if (GUILayout.Button("Copy SHA-256 to Clipboard")) + { + GUIUtility.systemCopyBuffer = sha256; + EditorUtility.DisplayDialog("SHA-256 Copied", "The SHA-256 hash has been copied to clipboard.", "OK"); + } + } } - - string arguments = $"-list -v -keystore \"{filePath}\" -storepass {password}"; - if (aliases.Count > 0) + private void HandleDragAndDrop(Rect dropArea) { - arguments += $" -keypass {aliasPassword} -alias {aliases[selectedAliasIndex]}"; + Event evt = Event.current; + if ((evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform) && dropArea.Contains(evt.mousePosition)) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + if (evt.type == EventType.DragPerform || evt.type == EventType.DragUpdated) + { + DragDropOperations(); + } + else if (evt.type == EventType.DragExited) + { + DragAndDrop.PrepareStartDrag(); + } + evt.Use(); + } } - - // Start the KeyTool process. - ProcessStartInfo startInfo = new ProcessStartInfo + private void DragDropOperations() { - FileName = keytoolPath, - Arguments = arguments, - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - CreateNoWindow = true - }; - - using (Process process = Process.Start(startInfo)) - { - string output = process.StandardOutput.ReadToEnd(); - string errorOutput = process.StandardError.ReadToEnd(); - var errorCheck = errorOutput.ToLower().Contains("error") || output.ToLower().Contains("error"); - process.WaitForExit(); + DragAndDrop.AcceptDrag(); + DragAndDrop.activeControlID = GUIUtility.GetControlID(FocusType.Passive); - if (errorCheck) + filePath = DragAndDrop.paths.FirstOrDefault() ?? string.Empty; + isKeystoreDropped = !string.IsNullOrWhiteSpace(filePath) && filePath.EndsWith(".keystore", StringComparison.OrdinalIgnoreCase); + if (!isKeystoreDropped) { - string errorMessage = !string.IsNullOrWhiteSpace(errorOutput) ? errorOutput : output; - - EditorUtility.DisplayDialog("Keytool Error", $"An error occurred: {errorMessage}", "OK"); + EditorUtility.DisplayDialog("Invalid File", "Please drop a .keystore file.", "OK"); } else { - if (aliases.Count > 0) - { - sha256 = ExtractSHA256(output); - } - else - { - aliases = GetAliasNames(output); - if (aliases.Count == 0) - EditorUtility.DisplayDialog("No Aliases Found", "No aliases found in the keystore file.", "OK"); - } + isExecutable = false; + sha256 = string.Empty; + aliases = new List(); + password = string.Empty; + aliasPassword = string.Empty; } } - } - private string ExtractSHA256(string input) - { - var match = Regex.Match(input, @"SHA-?256:\s*(\S+)"); - return match.Success ? match.Groups[1].Value : null; - } - private List GetAliasNames(string text) - { - return Regex.Matches(text, @"Alias name: (.+)") - .Cast() - .Select(m => m.Groups[1].Value.Trim()) - .ToList(); - } - private string CheckKeyTool() - { - string keytoolPath = "keytool"; - try + private void ExecuteKeyTool() { + // Check if KeyTool executable is available. + string keytoolPath = CheckKeyTool(); + if (keytoolPath == "Keytool is not available.") + { + EditorUtility.DisplayDialog("Keytool Not Found", "Unable to find Keytool in your environment.", "OK"); + return; + } + + string arguments = $"-list -v -keystore \"{filePath}\" -storepass {password}"; + if (aliases.Count > 0) + { + arguments += $" -keypass {aliasPassword} -alias {aliases[selectedAliasIndex]}"; + } + + // Start the KeyTool process. ProcessStartInfo startInfo = new ProcessStartInfo { FileName = keytoolPath, - Arguments = KeyToolHelpCommand, + Arguments = arguments, UseShellExecute = false, RedirectStandardOutput = true, + RedirectStandardError = true, CreateNoWindow = true }; using (Process process = Process.Start(startInfo)) { + string output = process.StandardOutput.ReadToEnd(); + string errorOutput = process.StandardError.ReadToEnd(); + var errorCheck = errorOutput.ToLower().Contains("error") || output.ToLower().Contains("error"); process.WaitForExit(); - } - return keytoolPath; + if (errorCheck) + { + string errorMessage = !string.IsNullOrWhiteSpace(errorOutput) ? errorOutput : output; + + EditorUtility.DisplayDialog("Keytool Error", $"An error occurred: {errorMessage}", "OK"); + } + else + { + if (aliases.Count > 0) + { + sha256 = ExtractSHA256(output); + } + else + { + aliases = GetAliasNames(output); + if (aliases.Count == 0) + EditorUtility.DisplayDialog("No Aliases Found", "No aliases found in the keystore file.", "OK"); + } + } + } } - catch (Exception) + private string ExtractSHA256(string input) { - //if windows - return Path.GetDirectoryName(Path.Combine(EditorApplication.applicationContentsPath, "PlaybackEngines\\AndroidPlayer\\OpenJDK\\bin\\keytool.exe\\")).Replace("\\", "/"); + var match = Regex.Match(input, @"SHA-?256:\s*(\S+)"); + return match.Success ? match.Groups[1].Value : null; + } + private List GetAliasNames(string text) + { + return Regex.Matches(text, @"Alias name: (.+)") + .Cast() + .Select(m => m.Groups[1].Value.Trim()) + .ToList(); + } + private string CheckKeyTool() + { + string keytoolPath = "keytool"; + try + { + ProcessStartInfo startInfo = new ProcessStartInfo + { + FileName = keytoolPath, + Arguments = KeyToolHelpCommand, + UseShellExecute = false, + RedirectStandardOutput = true, + CreateNoWindow = true + }; + + using (Process process = Process.Start(startInfo)) + { + process.WaitForExit(); + } + + return keytoolPath; + } + catch (Exception) + { + //if windows + return Path.GetDirectoryName(Path.Combine(EditorApplication.applicationContentsPath, "PlaybackEngines\\AndroidPlayer\\OpenJDK\\bin\\keytool.exe\\")).Replace("\\", "/"); + } } } } diff --git a/Assets/Huawei/Editor/View/MainWindow/HMSMainKitsTabFactory.cs b/Assets/Huawei/Editor/View/MainWindow/HMSMainKitsTabFactory.cs index 0a0d5152..c19e00eb 100644 --- a/Assets/Huawei/Editor/View/MainWindow/HMSMainKitsTabFactory.cs +++ b/Assets/Huawei/Editor/View/MainWindow/HMSMainKitsTabFactory.cs @@ -1,4 +1,4 @@ -using HmsPlugin; +using HmsPlugin; using HmsPlugin.Button; using HmsPlugin.Label; using System.Collections.Generic; @@ -7,124 +7,127 @@ using UnityEditor; using UnityEngine; -internal class HMSMainKitsTabFactory +namespace HmsPlugin { - private static string versionInfo = ""; + internal class HMSMainKitsTabFactory + { + private static string versionInfo = ""; - private static List toggleEditors; - public static DisabledDrawer _disabledDrawer; - private static PluginToggleEditor pluginToggleEditor; + private static List toggleEditors; + public static DisabledDrawer _disabledDrawer; + private static PluginToggleEditor pluginToggleEditor; - static HMSMainKitsTabFactory() - { - versionInfo = File.ReadAllText(Application.dataPath + "/Huawei/VERSION"); - toggleEditors = new List(); - } + static HMSMainKitsTabFactory() + { + versionInfo = File.ReadAllText(Application.dataPath + "/Huawei/VERSION"); + toggleEditors = new List(); + } - public static TabView CreateKitsTab(TabBar tabBar) - { - toggleEditors.Clear(); - var tab = new TabView("Kits"); - tabBar.AddTab(tab); + public static TabView CreateKitsTab(TabBar tabBar) + { + toggleEditors.Clear(); + var tab = new TabView("Kits"); + tabBar.AddTab(tab); - pluginToggleEditor = new PluginToggleEditor(tabBar); - var adsToggleEditor = new AdsToggleEditor(tabBar); - var accountEditor = new AccountToggleEditor(); - var gameServiceToggleEditor = new GameServiceToggleEditor(tabBar, accountEditor); - var pushToggleEditor = new PushToggleEditor(); - var analyticsEditor = new AnalyticsToggleEditor(); - var authEditor = new AuthToggleEditor(); - var iapToggleEditor = new IAPToggleEditor(tabBar); - var remoteConfigToggleEditor = new RemoteConfigToggleEditor(tabBar, analyticsEditor); - var crashToggleEditor = new CrashToggleEditor(analyticsEditor); - var cloudDBToggleEditor = new CloudDBToggleEditor(tabBar, authEditor); - var driveToggleEditor = new DriveKitToggleEditor(accountEditor, pushToggleEditor); - var nearbyServiceToggleEditor = new NearbyServiceToggleEditor(); - var appMessagingToggleEditor = new AppMessagingToggleEditor(); - var appLinkingToggleEditor = new AppLinkingToggleEditor(analyticsEditor); - var locationToggleEditor = new LocationToggleEditor(); - var scanToogleEditor = new ScanKitToggleEditor(); - var cloudStorageToggleEditor = new CloudStorageToggleEditor(); - var apmToggleEditor = new APMToggleEditor(); - var modeling3DToggleEditor = new Modeling3dKitToggleEditor(tabBar); + pluginToggleEditor = new PluginToggleEditor(tabBar); + var adsToggleEditor = new AdsToggleEditor(tabBar); + var accountEditor = new AccountToggleEditor(); + var gameServiceToggleEditor = new GameServiceToggleEditor(tabBar, accountEditor); + var pushToggleEditor = new PushToggleEditor(); + var analyticsEditor = new AnalyticsToggleEditor(); + var authEditor = new AuthToggleEditor(); + var iapToggleEditor = new IAPToggleEditor(tabBar); + var remoteConfigToggleEditor = new RemoteConfigToggleEditor(tabBar, analyticsEditor); + var crashToggleEditor = new CrashToggleEditor(analyticsEditor); + var cloudDBToggleEditor = new CloudDBToggleEditor(tabBar, authEditor); + var driveToggleEditor = new DriveKitToggleEditor(accountEditor, pushToggleEditor); + var nearbyServiceToggleEditor = new NearbyServiceToggleEditor(); + var appMessagingToggleEditor = new AppMessagingToggleEditor(); + var appLinkingToggleEditor = new AppLinkingToggleEditor(analyticsEditor); + var locationToggleEditor = new LocationToggleEditor(); + var scanToogleEditor = new ScanKitToggleEditor(); + var cloudStorageToggleEditor = new CloudStorageToggleEditor(); + var apmToggleEditor = new APMToggleEditor(); + var modeling3DToggleEditor = new Modeling3dKitToggleEditor(tabBar); - tab.AddDrawer(new HorizontalSequenceDrawer(new Spacer(), pluginToggleEditor, new Spacer())); - tab.AddDrawer(new HorizontalLine()); - tab.AddDrawer(_disabledDrawer = new DisabledDrawer - ( - new VerticalSequenceDrawer + tab.AddDrawer(new HorizontalSequenceDrawer(new Spacer(), pluginToggleEditor, new Spacer())); + tab.AddDrawer(new HorizontalLine()); + tab.AddDrawer(_disabledDrawer = new DisabledDrawer ( - new HorizontalSequenceDrawer(new Spacer(), new Label("- HMS Core -").SetBold(true), new Spacer()), - new HorizontalSequenceDrawer(new HorizontalLine()), - new HorizontalSequenceDrawer(new Spacer(), accountEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), adsToggleEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), analyticsEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), appLinkingToggleEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), driveToggleEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), gameServiceToggleEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), iapToggleEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), locationToggleEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), nearbyServiceToggleEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), pushToggleEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), scanToogleEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), modeling3DToggleEditor, new Spacer()), - new Spacer(), - new HorizontalSequenceDrawer(new HorizontalLine()), - new HorizontalSequenceDrawer(new Spacer(), new Label("- AppGallery Connect -").SetBold(true), new Spacer()), - new HorizontalSequenceDrawer(new HorizontalLine()), - new HorizontalSequenceDrawer(new Spacer(), appMessagingToggleEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), apmToggleEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), authEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), cloudDBToggleEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), cloudStorageToggleEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), crashToggleEditor, new Spacer()), - new HorizontalSequenceDrawer(new Spacer(), remoteConfigToggleEditor, new Spacer()) + new VerticalSequenceDrawer + ( + new HorizontalSequenceDrawer(new Spacer(), new Label.Label("- HMS Core -").SetBold(true), new Spacer()), + new HorizontalSequenceDrawer(new HorizontalLine()), + new HorizontalSequenceDrawer(new Spacer(), accountEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), adsToggleEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), analyticsEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), appLinkingToggleEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), driveToggleEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), gameServiceToggleEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), iapToggleEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), locationToggleEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), nearbyServiceToggleEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), pushToggleEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), scanToogleEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), modeling3DToggleEditor, new Spacer()), + new Spacer(), + new HorizontalSequenceDrawer(new HorizontalLine()), + new HorizontalSequenceDrawer(new Spacer(), new Label.Label("- AppGallery Connect -").SetBold(true), new Spacer()), + new HorizontalSequenceDrawer(new HorizontalLine()), + new HorizontalSequenceDrawer(new Spacer(), appMessagingToggleEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), apmToggleEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), authEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), cloudDBToggleEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), cloudStorageToggleEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), crashToggleEditor, new Spacer()), + new HorizontalSequenceDrawer(new Spacer(), remoteConfigToggleEditor, new Spacer()) - ) - )); - //tab.AddDrawer(new HorizontalLine()); - tab.AddDrawer(new Spacer()); - tab.AddDrawer(new HorizontalSequenceDrawer(new Label("HMS Unity Plugin v" + versionInfo).SetBold(true), new Spacer(), new Clickable(new Label(guiContent: new GUIContent(EditorGUIUtility.FindTexture("_Help"))), () => { Application.OpenURL("https://evilminddevs.gitbook.io/hms-unity-plugin/"); }))); - tab.AddDrawer(new HelpboxAGConnectFile()); + ) + )); + //tab.AddDrawer(new HorizontalLine()); + tab.AddDrawer(new Spacer()); + tab.AddDrawer(new HorizontalSequenceDrawer(new Label.Label("HMS Unity Plugin v" + versionInfo).SetBold(true), new Spacer(), new Clickable(new Label.Label(guiContent: new GUIContent(EditorGUIUtility.FindTexture("_Help"))), () => { Application.OpenURL("https://evilminddevs.gitbook.io/hms-unity-plugin/"); }))); + tab.AddDrawer(new HelpboxAGConnectFile()); - toggleEditors.Add(adsToggleEditor); - toggleEditors.Add(accountEditor); - toggleEditors.Add(gameServiceToggleEditor); - toggleEditors.Add(pushToggleEditor); - toggleEditors.Add(analyticsEditor); - toggleEditors.Add(authEditor); - toggleEditors.Add(iapToggleEditor); - toggleEditors.Add(remoteConfigToggleEditor); - toggleEditors.Add(crashToggleEditor); - toggleEditors.Add(cloudDBToggleEditor); - toggleEditors.Add(driveToggleEditor); - toggleEditors.Add(nearbyServiceToggleEditor); - toggleEditors.Add(appMessagingToggleEditor); - toggleEditors.Add(appLinkingToggleEditor); - toggleEditors.Add(locationToggleEditor); - toggleEditors.Add(scanToogleEditor); - toggleEditors.Add(cloudStorageToggleEditor); - toggleEditors.Add(apmToggleEditor); - toggleEditors.Add(modeling3DToggleEditor); + toggleEditors.Add(adsToggleEditor); + toggleEditors.Add(accountEditor); + toggleEditors.Add(gameServiceToggleEditor); + toggleEditors.Add(pushToggleEditor); + toggleEditors.Add(analyticsEditor); + toggleEditors.Add(authEditor); + toggleEditors.Add(iapToggleEditor); + toggleEditors.Add(remoteConfigToggleEditor); + toggleEditors.Add(crashToggleEditor); + toggleEditors.Add(cloudDBToggleEditor); + toggleEditors.Add(driveToggleEditor); + toggleEditors.Add(nearbyServiceToggleEditor); + toggleEditors.Add(appMessagingToggleEditor); + toggleEditors.Add(appLinkingToggleEditor); + toggleEditors.Add(locationToggleEditor); + toggleEditors.Add(scanToogleEditor); + toggleEditors.Add(cloudStorageToggleEditor); + toggleEditors.Add(apmToggleEditor); + toggleEditors.Add(modeling3DToggleEditor); - _disabledDrawer.SetEnabled(!HMSPluginSettings.Instance.Settings.GetBool(PluginToggleEditor.PluginEnabled, true)); + _disabledDrawer.SetEnabled(!HMSPluginSettings.Instance.Settings.GetBool(PluginToggleEditor.PluginEnabled, true)); - return tab; - } + return tab; + } - public static List GetEnabledEditors() - { - return toggleEditors.FindAll(c => c.Enabled); - } + public static List GetEnabledEditors() + { + return toggleEditors.FindAll(c => c.Enabled); + } - public static void RefreshPluginStatus() - { - if (pluginToggleEditor != null) + public static void RefreshPluginStatus() { - pluginToggleEditor.RefreshDrawer(HMSPluginSettings.Instance.Settings.GetBool(PluginToggleEditor.PluginEnabled)); - pluginToggleEditor.RefreshToggle(); + if (pluginToggleEditor != null) + { + pluginToggleEditor.RefreshDrawer(HMSPluginSettings.Instance.Settings.GetBool(PluginToggleEditor.PluginEnabled)); + pluginToggleEditor.RefreshToggle(); + } + if (toggleEditors != null && toggleEditors.Count > 0) + toggleEditors.ForEach(c => c.RefreshToggles()); } - if (toggleEditors != null && toggleEditors.Count > 0) - toggleEditors.ForEach(c => c.RefreshToggles()); } } diff --git a/Assets/Huawei/Editor/View/MainWindow/HMSMainWindow.cs b/Assets/Huawei/Editor/View/MainWindow/HMSMainWindow.cs index f0182ff6..6fcc62b8 100644 --- a/Assets/Huawei/Editor/View/MainWindow/HMSMainWindow.cs +++ b/Assets/Huawei/Editor/View/MainWindow/HMSMainWindow.cs @@ -1,53 +1,55 @@ - -using HmsPlugin; + using HmsPlugin.Window; using UnityEditor; -public class HMSMainWindow : HMSEditorWindow +namespace HmsPlugin { - [MenuItem("Huawei/Kit Settings", priority = 1)] - public static void ShowWindow() - { - GetWindow(typeof(HMSMainWindow), false, "HMS Kit Settings"); - } - - [MenuItem("Huawei/Check for Updates", priority = 2)] - public static void CheckForUpdates() - { - HMSPluginUpdater.Request(true); - } - - [MenuItem("Huawei/Utils/Enable Plugin")] - public static void EnablePlugin() - { - HMSEditorUtils.SetHMSPlugin(true, true); - } - - [MenuItem("Huawei/Utils/Enable Plugin Without Managers")] - public static void EnableWithoutManagers() - { - HMSEditorUtils.SetHMSPlugin(true, false); - } - - [MenuItem("Huawei/Utils/Disable Plugin")] - public static void DisablePlugin() - { - HMSEditorUtils.SetHMSPlugin(false, false); - } - - [MenuItem("Huawei/Utils/Key Tool")] - public static void KeyTool() + public class HMSMainWindow : HMSEditorWindow { - GetWindow(typeof(HMSKeyToolWindow), false, "HMS Key Tool", true); - } - - public override IDrawer CreateDrawer() - { - var tabBar = new TabBar(); - - HMSMainKitsTabFactory.CreateKitsTab(tabBar); - - return tabBar; - + [MenuItem("Huawei/Kit Settings", priority = 1)] + public static void ShowWindow() + { + GetWindow(typeof(HMSMainWindow), false, "HMS Kit Settings"); + } + + [MenuItem("Huawei/Check for Updates", priority = 2)] + public static void CheckForUpdates() + { + HMSPluginUpdater.Request(true); + } + + [MenuItem("Huawei/Utils/Enable Plugin")] + public static void EnablePlugin() + { + HMSEditorUtils.SetHMSPlugin(true, true); + } + + [MenuItem("Huawei/Utils/Enable Plugin Without Managers")] + public static void EnableWithoutManagers() + { + HMSEditorUtils.SetHMSPlugin(true, false); + } + + [MenuItem("Huawei/Utils/Disable Plugin")] + public static void DisablePlugin() + { + HMSEditorUtils.SetHMSPlugin(false, false); + } + + [MenuItem("Huawei/Utils/Key Tool")] + public static void KeyTool() + { + GetWindow(typeof(HMSKeyToolWindow), false, "HMS Key Tool", true); + } + + public override IDrawer CreateDrawer() + { + var tabBar = new TabBar(); + + HMSMainKitsTabFactory.CreateKitsTab(tabBar); + + return tabBar; + + } } } diff --git a/Assets/Huawei/Editor/View/PMSWindow/AllIAPProductsWindow/HMSAllIAPProductsWindow.cs b/Assets/Huawei/Editor/View/PMSWindow/AllIAPProductsWindow/HMSAllIAPProductsWindow.cs index f1c7cadb..026ac1c6 100644 --- a/Assets/Huawei/Editor/View/PMSWindow/AllIAPProductsWindow/HMSAllIAPProductsWindow.cs +++ b/Assets/Huawei/Editor/View/PMSWindow/AllIAPProductsWindow/HMSAllIAPProductsWindow.cs @@ -1,32 +1,34 @@ -using HmsPlugin; -using HmsPlugin.Window; +using HmsPlugin.Window; using UnityEditor; using UnityEngine; -public class HMSAllIAPProductsWindow : HMSEditorWindow +namespace HmsPlugin { - [MenuItem("Huawei/Connect API/PMS API/Query IAP Products")] - public static void ShowProductWindow() + public class HMSAllIAPProductsWindow : HMSEditorWindow { - GetWindow(typeof(HMSAllIAPProductsWindow), false, "Query Products").minSize = new UnityEngine.Vector2(400, 700); - } + [MenuItem("Huawei/Connect API/PMS API/Query IAP Products")] + public static void ShowProductWindow() + { + GetWindow(typeof(HMSAllIAPProductsWindow), false, "Query Products").minSize = new UnityEngine.Vector2(400, 700); + } - // Validate the menu item defined by the function above. - // The menu item will be disabled if this function returns false. - [MenuItem("Huawei/Connect API/PMS API/Query IAP Products", true)] - static bool ValidatePMSAPIWindow() - { - Debug.Log("ValidatePMSAPIWindow"); - return !string.IsNullOrEmpty(HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.AccessToken, "")); - } + // Validate the menu item defined by the function above. + // The menu item will be disabled if this function returns false. + [MenuItem("Huawei/Connect API/PMS API/Query IAP Products", true)] + static bool ValidatePMSAPIWindow() + { + Debug.Log("ValidatePMSAPIWindow"); + return !string.IsNullOrEmpty(HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.AccessToken, "")); + } - public override IDrawer CreateDrawer() - { - var tabBar = new TabBar(); - HMSPMSAPITabFactory.AllProductsTab(tabBar); - return tabBar; + public override IDrawer CreateDrawer() + { + var tabBar = new TabBar(); + HMSPMSAPITabFactory.AllProductsTab(tabBar); + return tabBar; + } } -} +} diff --git a/Assets/Huawei/Editor/View/PMSWindow/CreateAProductWindow/HMSCreateAProductWindow.cs b/Assets/Huawei/Editor/View/PMSWindow/CreateAProductWindow/HMSCreateAProductWindow.cs index 6c13c91d..ac20c266 100644 --- a/Assets/Huawei/Editor/View/PMSWindow/CreateAProductWindow/HMSCreateAProductWindow.cs +++ b/Assets/Huawei/Editor/View/PMSWindow/CreateAProductWindow/HMSCreateAProductWindow.cs @@ -1,31 +1,34 @@ -using HmsPlugin; +using HmsPlugin.Button; using HmsPlugin.Window; using UnityEditor; using UnityEngine; -public class HMSCreateAProductWindow : HMSEditorWindow +namespace HmsPlugin { - [MenuItem("Huawei/Connect API/PMS API/Create a Product")] - public static void ShowProductWindow() + public class HMSCreateAProductWindow : HMSEditorWindow { - GetWindow(typeof(HMSCreateAProductWindow), false, "Create a Product").minSize = new UnityEngine.Vector2(400, 700); - } + [MenuItem("Huawei/Connect API/PMS API/Create a Product")] + public static void ShowProductWindow() + { + GetWindow(typeof(HMSCreateAProductWindow), false, "Create a Product").minSize = new UnityEngine.Vector2(400, 700); + } - // Validate the menu item defined by the function above. - // The menu item will be disabled if this function returns false. - [MenuItem("Huawei/Connect API/PMS API/Create a Product", true)] - static bool ValidatePMSAPIWindow() - { - Debug.Log("ValidatePMSAPIWindow"); - return !string.IsNullOrEmpty(HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.AccessToken, "")); - } + // Validate the menu item defined by the function above. + // The menu item will be disabled if this function returns false. + [MenuItem("Huawei/Connect API/PMS API/Create a Product", true)] + static bool ValidatePMSAPIWindow() + { + Debug.Log("ValidatePMSAPIWindow"); + return !string.IsNullOrEmpty(HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.AccessToken, "")); + } - public override IDrawer CreateDrawer() - { - var tabBar = new TabBar(); - HMSPMSAPITabFactory.CreateProductTab(tabBar); - return tabBar; + public override IDrawer CreateDrawer() + { + var tabBar = new TabBar(); + HMSPMSAPITabFactory.CreateProductTab(tabBar); + return tabBar; + } } -} +} diff --git a/Assets/Huawei/Editor/View/PMSWindow/CreateProductsWindow/HMSCreateProductsWindow.cs b/Assets/Huawei/Editor/View/PMSWindow/CreateProductsWindow/HMSCreateProductsWindow.cs index 7ba0fe15..061351f8 100644 --- a/Assets/Huawei/Editor/View/PMSWindow/CreateProductsWindow/HMSCreateProductsWindow.cs +++ b/Assets/Huawei/Editor/View/PMSWindow/CreateProductsWindow/HMSCreateProductsWindow.cs @@ -1,31 +1,34 @@ -using HmsPlugin; +using HmsPlugin; using HmsPlugin.Window; using UnityEditor; using UnityEngine; -public class HMSCreateProductsWindow : HMSEditorWindow +namespace HmsPlugin { - [MenuItem("Huawei/Connect API/PMS API/Create Products")] - public static void ShowProductWindow() + public class HMSCreateProductsWindow : HMSEditorWindow { - //TODO: set minimum size see example in HMSCreateAProductWindow - GetWindow(typeof(HMSCreateProductsWindow), false, "Create Products"); - } + [MenuItem("Huawei/Connect API/PMS API/Create Products")] + public static void ShowProductWindow() + { + //TODO: set minimum size see example in HMSCreateAProductWindow + GetWindow(typeof(HMSCreateProductsWindow), false, "Create Products"); + } - // Validate the menu item defined by the function above. - // The menu item will be disabled if this function returns false. - [MenuItem("Huawei/Connect API/PMS API/Create Products", true)] - static bool ValidatePMSAPIWindow() - { - Debug.Log("ValidatePMSAPIWindow"); - return !string.IsNullOrEmpty(HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.AccessToken, "")); - } + // Validate the menu item defined by the function above. + // The menu item will be disabled if this function returns false. + [MenuItem("Huawei/Connect API/PMS API/Create Products", true)] + static bool ValidatePMSAPIWindow() + { + Debug.Log("ValidatePMSAPIWindow"); + return !string.IsNullOrEmpty(HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.AccessToken, "")); + } - public override IDrawer CreateDrawer() - { - var tabBar = new TabBar(); - HMSPMSAPITabFactory.CreateProductsTab(tabBar); - return tabBar; + public override IDrawer CreateDrawer() + { + var tabBar = new TabBar(); + HMSPMSAPITabFactory.CreateProductsTab(tabBar); + return tabBar; + } } } diff --git a/Assets/Huawei/Editor/View/PMSWindow/HMSPMSAPITabFactory.cs b/Assets/Huawei/Editor/View/PMSWindow/HMSPMSAPITabFactory.cs index 5af858f3..cb71814a 100644 --- a/Assets/Huawei/Editor/View/PMSWindow/HMSPMSAPITabFactory.cs +++ b/Assets/Huawei/Editor/View/PMSWindow/HMSPMSAPITabFactory.cs @@ -1,39 +1,40 @@ -using HmsPlugin; -using HmsPlugin.ConnectAPI.PMSAPI; +using HmsPlugin.ConnectAPI.PMSAPI; - -internal class HMSPMSAPITabFactory +namespace HmsPlugin { - public static TabView CreateProductTab(TabBar tabBar) + internal class HMSPMSAPITabFactory { - var tab = new TabView("Create a Product"); - tabBar.AddTab(tab); - tab.AddDrawer(new CreateProductEditor()); - return tab; - } + public static TabView CreateProductTab(TabBar tabBar) + { + var tab = new TabView("Create a Product"); + tabBar.AddTab(tab); + tab.AddDrawer(new CreateProductEditor()); + return tab; + } - public static TabView CreateProductsTab(TabBar tabBar) - { - var tab = new TabView("Create Products"); - tabBar.AddTab(tab); - tab.AddDrawer(new CreateProductsEditor()); - return tab; - } + public static TabView CreateProductsTab(TabBar tabBar) + { + var tab = new TabView("Create Products"); + tabBar.AddTab(tab); + tab.AddDrawer(new CreateProductsEditor()); + return tab; + } - public static TabView AllProductsTab(TabBar tabBar) - { - var tab = new TabView("All Products"); - tabBar.AddTab(tab); - tab.AddDrawer(new AllIAPProductsEditor()); - return tab; - } + public static TabView AllProductsTab(TabBar tabBar) + { + var tab = new TabView("All Products"); + tabBar.AddTab(tab); + tab.AddDrawer(new AllIAPProductsEditor()); + return tab; + } - public static TabView UpdateProductTab(TabBar tabBar, AllIAPProductsEditor.Product product) - { - var tab = new TabView("Update Product"); - tabBar.AddTab(tab); - tab.AddDrawer(new UpdateIAPProductEditor(product)); - return tab; + public static TabView UpdateProductTab(TabBar tabBar, AllIAPProductsEditor.Product product) + { + var tab = new TabView("Update Product"); + tabBar.AddTab(tab); + tab.AddDrawer(new UpdateIAPProductEditor(product)); + return tab; + } } -} +} diff --git a/Assets/Huawei/Editor/View/PublishingAPI/HMSPublishingAPITabFactory.cs b/Assets/Huawei/Editor/View/PublishingAPI/HMSPublishingAPITabFactory.cs index 7788d0df..3bf8a644 100644 --- a/Assets/Huawei/Editor/View/PublishingAPI/HMSPublishingAPITabFactory.cs +++ b/Assets/Huawei/Editor/View/PublishingAPI/HMSPublishingAPITabFactory.cs @@ -1,13 +1,15 @@ -using HmsPlugin; -using HmsPlugin.PublishingAPI; +using HmsPlugin.PublishingAPI; -internal class HMSPublishingAPITabFactory +namespace HmsPlugin { - public static TabView CreateQueryingAppInformationTab(TabBar tabBar) + internal class HMSPublishingAPITabFactory { - var tab = new TabView("Query App Information"); - tabBar.AddTab(tab); - tab.AddDrawer(new QueryingAppInfoEditor()); - return tab; + public static TabView CreateQueryingAppInformationTab(TabBar tabBar) + { + var tab = new TabView("Query App Information"); + tabBar.AddTab(tab); + tab.AddDrawer(new QueryingAppInfoEditor()); + return tab; + } } } diff --git a/Assets/Huawei/Editor/View/PublishingAPI/QueryingAppInformation/QueryingAppInfoWindow.cs b/Assets/Huawei/Editor/View/PublishingAPI/QueryingAppInformation/QueryingAppInfoWindow.cs index 9300bd25..060c5084 100644 --- a/Assets/Huawei/Editor/View/PublishingAPI/QueryingAppInformation/QueryingAppInfoWindow.cs +++ b/Assets/Huawei/Editor/View/PublishingAPI/QueryingAppInformation/QueryingAppInfoWindow.cs @@ -1,30 +1,32 @@ -using HmsPlugin; using HmsPlugin.Window; using UnityEditor; using UnityEngine; -public class QueryingAppInformationWindow : HMSEditorWindow +namespace HmsPlugin { - [MenuItem("Huawei/Connect API/Publishing API/Querying App Information")] - public static void ShowQueryingAppInformationWindow() + public class QueryingAppInformationWindow : HMSEditorWindow { - GetWindow(typeof(QueryingAppInformationWindow), false, "Querying App Information").minSize = new UnityEngine.Vector2(400, 700); - } + [MenuItem("Huawei/Connect API/Publishing API/Querying App Information")] + public static void ShowQueryingAppInformationWindow() + { + GetWindow(typeof(QueryingAppInformationWindow), false, "Querying App Information").minSize = new UnityEngine.Vector2(400, 700); + } - // Validate the menu item defined by the function above. - // The menu item will be disabled if this function returns false. - [MenuItem("Huawei/Connect API/Publishing API/Querying App Information", true)] - static bool ValidateShowQueryingAppInformationWindow() - { - Debug.Log("ValidateShowQueryingAppInformationWindow"); - return !string.IsNullOrEmpty(HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.AccessToken, "")); - } + // Validate the menu item defined by the function above. + // The menu item will be disabled if this function returns false. + [MenuItem("Huawei/Connect API/Publishing API/Querying App Information", true)] + static bool ValidateShowQueryingAppInformationWindow() + { + Debug.Log("ValidateShowQueryingAppInformationWindow"); + return !string.IsNullOrEmpty(HMSConnectAPISettings.Instance.Settings.Get(HMSConnectAPISettings.AccessToken, "")); + } - public override IDrawer CreateDrawer() - { - var tabBar = new TabBar(); - HMSPublishingAPITabFactory.CreateQueryingAppInformationTab(tabBar); - return tabBar; + public override IDrawer CreateDrawer() + { + var tabBar = new TabBar(); + HMSPublishingAPITabFactory.CreateQueryingAppInformationTab(tabBar); + return tabBar; + } } } diff --git a/Assets/Huawei/Scripts/APM/HMSAPMManager.cs b/Assets/Huawei/Scripts/APM/HMSAPMManager.cs index 3c64a093..e1b62242 100644 --- a/Assets/Huawei/Scripts/APM/HMSAPMManager.cs +++ b/Assets/Huawei/Scripts/APM/HMSAPMManager.cs @@ -1,32 +1,31 @@ -using HmsPlugin; using HuaweiMobileServices.APM; using UnityEngine; - -public class HMSAPMManager : HMSManagerSingleton +namespace HmsPlugin { - private readonly string TAG = "[HMS] HMSAPMManager"; - - public HMSAPMManager() + public class HMSAPMManager : HMSManagerSingleton { - HMSManagerStart.Start(OnAwake, TAG); - } + private readonly string TAG = "[HMS] HMSAPMManager"; - private void OnAwake() - { - Debug.Log($"[{TAG}]: OnAwake() "); - } + public HMSAPMManager() + { + HMSManagerStart.Start(OnAwake, TAG); + } - public void EnableCollection(bool state) - { - APMS.GetInstance().EnableCollection(state); - } - - public void EnableAnrMonitor(bool state) - { - APMS.GetInstance().EnableAnrMonitor(state); - } + private void OnAwake() + { + Debug.Log($"[{TAG}]: OnAwake() "); + } + public void EnableCollection(bool state) + { + APMS.GetInstance().EnableCollection(state); + } + public void EnableAnrMonitor(bool state) + { + APMS.GetInstance().EnableAnrMonitor(state); + } + } } diff --git a/Assets/Huawei/Scripts/Analytics/HMSAnalyticsKitManager.cs b/Assets/Huawei/Scripts/Analytics/HMSAnalyticsKitManager.cs index 4520e41f..8bd3fb39 100644 --- a/Assets/Huawei/Scripts/Analytics/HMSAnalyticsKitManager.cs +++ b/Assets/Huawei/Scripts/Analytics/HMSAnalyticsKitManager.cs @@ -1,96 +1,98 @@ -using System.Collections.Generic; +using System.Collections.Generic; using UnityEngine; using HuaweiMobileServices.Analystics; using HuaweiMobileServices.Utils; -using HmsPlugin; -public class HMSAnalyticsKitManager : HMSManagerSingleton +namespace HmsPlugin { - private readonly string TAG = "[HMS] : HMSAnalyticsKitManager"; - private HiAnalyticsInstance hiAnalyticsInstance; - private AndroidJavaObject activity; - - public HMSAnalyticsKitManager() + public class HMSAnalyticsKitManager : HMSManagerSingleton { - HMSManagerStart.Start(TAG, true, InitializeAnalyticsInstant); - } + private readonly string TAG = "[HMS] : HMSAnalyticsKitManager"; + private HiAnalyticsInstance hiAnalyticsInstance; + private AndroidJavaObject activity; - void InitializeAnalyticsInstant() - { - Debug.Log($"{TAG} InitializeAnalyticsInstant"); - AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); - activity = jc.GetStatic("currentActivity"); - - activity.Call("runOnUiThread", new AndroidJavaRunnable(() => + public HMSAnalyticsKitManager() { - HiAnalyticsTools.EnableLog(); - hiAnalyticsInstance = HiAnalytics.GetInstance(activity); - hiAnalyticsInstance.SetAnalyticsEnabled(true); - })); - } + HMSManagerStart.Start(TAG, true, InitializeAnalyticsInstant); + } - public void SendEventWithBundle(string eventID, string key, string value) - { - activity.Call("runOnUiThread", new AndroidJavaRunnable(() => + void InitializeAnalyticsInstant() { - _SendEventWithBundle(eventID, key, value); - })); - } + Debug.Log($"{TAG} InitializeAnalyticsInstant"); + AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); + activity = jc.GetStatic("currentActivity"); - void _SendEventWithBundle(string eventID, string key, string value) - { - Bundle bundleUnity = new Bundle(); - bundleUnity.PutString(key, value); - Debug.Log($"{TAG} : Analytics Kits Event Id:{eventID} Key:{key} Value:{value}"); - hiAnalyticsInstance.OnEvent(eventID, bundleUnity); - } + activity.Call("runOnUiThread", new AndroidJavaRunnable(() => + { + HiAnalyticsTools.EnableLog(); + hiAnalyticsInstance = HiAnalytics.GetInstance(activity); + hiAnalyticsInstance.SetAnalyticsEnabled(true); + })); + } - public void SendEventWithBundle(string eventID, Dictionary values) - { - activity.Call("runOnUiThread", new AndroidJavaRunnable(() => + public void SendEventWithBundle(string eventID, string key, string value) { - _SendEventWithBundle(eventID, values); - })); - } + activity.Call("runOnUiThread", new AndroidJavaRunnable(() => + { + _SendEventWithBundle(eventID, key, value); + })); + } - void _SendEventWithBundle(string eventID, Dictionary values) - { - Bundle bundleUnity = new Bundle(); - foreach (var item in values) + void _SendEventWithBundle(string eventID, string key, string value) { - if (item.Value is int) + Bundle bundleUnity = new Bundle(); + bundleUnity.PutString(key, value); + Debug.Log($"{TAG} : Analytics Kits Event Id:{eventID} Key:{key} Value:{value}"); + hiAnalyticsInstance.OnEvent(eventID, bundleUnity); + } + + public void SendEventWithBundle(string eventID, Dictionary values) + { + activity.Call("runOnUiThread", new AndroidJavaRunnable(() => { - bundleUnity.PutInt(item.Key, (int)item.Value); - } - else if (item.Value is string) + _SendEventWithBundle(eventID, values); + })); + } + + void _SendEventWithBundle(string eventID, Dictionary values) + { + Bundle bundleUnity = new Bundle(); + foreach (var item in values) { - bundleUnity.PutString(item.Key, (string)item.Value); + if (item.Value is int) + { + bundleUnity.PutInt(item.Key, (int)item.Value); + } + else if (item.Value is string) + { + bundleUnity.PutString(item.Key, (string)item.Value); + } + else if (item.Value is bool) + { + bundleUnity.PutBoolean(item.Key, (bool)item.Value); + } } - else if (item.Value is bool) + Debug.Log($"{TAG} : Analytics Kits Event Id:{eventID}"); + foreach (var item in values) + Debug.Log($"{TAG} : Analytics Kits Key: {item.Key}, Value: {item.Value}"); + hiAnalyticsInstance.OnEvent(eventID, bundleUnity); + } + + public void SendEventWithBundle(string eventID, string key, int value) + { + activity.Call("runOnUiThread", new AndroidJavaRunnable(() => { - bundleUnity.PutBoolean(item.Key, (bool)item.Value); - } + _SendEventWithBundle(eventID, key, value); + })); } - Debug.Log($"{TAG} : Analytics Kits Event Id:{eventID}"); - foreach (var item in values) - Debug.Log($"{TAG} : Analytics Kits Key: {item.Key}, Value: {item.Value}"); - hiAnalyticsInstance.OnEvent(eventID, bundleUnity); - } - public void SendEventWithBundle(string eventID, string key, int value) - { - activity.Call("runOnUiThread", new AndroidJavaRunnable(() => + void _SendEventWithBundle(string eventID, string key, int value) { - _SendEventWithBundle(eventID, key, value); - })); - } + Bundle bundleUnity = new Bundle(); + bundleUnity.PutInt(key, value); + Debug.Log($"{TAG} : Analytics Kits Event Id:{eventID} Key:{key} Value:{value}"); + hiAnalyticsInstance.OnEvent(eventID, bundleUnity); + } - void _SendEventWithBundle(string eventID, string key, int value) - { - Bundle bundleUnity = new Bundle(); - bundleUnity.PutInt(key, value); - Debug.Log($"{TAG} : Analytics Kits Event Id:{eventID} Key:{key} Value:{value}"); - hiAnalyticsInstance.OnEvent(eventID, bundleUnity); } - } diff --git a/Assets/Huawei/Scripts/AppMessaging/HMSAppMessagingManager.cs b/Assets/Huawei/Scripts/AppMessaging/HMSAppMessagingManager.cs index 0fcf6341..66f12a1a 100644 --- a/Assets/Huawei/Scripts/AppMessaging/HMSAppMessagingManager.cs +++ b/Assets/Huawei/Scripts/AppMessaging/HMSAppMessagingManager.cs @@ -1,58 +1,60 @@ -using HmsPlugin; -using HuaweiMobileServices.AppMessaging; +using HuaweiMobileServices.AppMessaging; using HuaweiMobileServices.Base; using HuaweiMobileServices.Id; using System; using UnityEngine; -public class HMSAppMessagingManager : HMSManagerSingleton +namespace HmsPlugin { - private const string TAG = "[HMS] HMSAppMessagingManager"; - public Action OnMessageClicked { get; set; } - public Action OnMessageDisplay { get; set; } - public Action OnMessageDismiss { get; set; } - public Action AAIDResultAction { get; set; } - - public HMSAppMessagingManager() + public class HMSAppMessagingManager : HMSManagerSingleton { - HMSManagerStart.Start(OnAwake, TAG); - } + private const string TAG = "[HMS] HMSAppMessagingManager"; + public Action OnMessageClicked { get; set; } + public Action OnMessageDisplay { get; set; } + public Action OnMessageDismiss { get; set; } + public Action AAIDResultAction { get; set; } - private void OnAwake() - { - Debug.Log($"{TAG}: OnAwake"); - HmsInstanceId inst = HmsInstanceId.GetInstance(); - ITask idResult = inst.AAID; - idResult.AddOnSuccessListener((result) => + public HMSAppMessagingManager() { - AAIDResult AAIDResult = result; - Debug.Log($"{TAG}: result.Id"); - AAIDResultAction?.Invoke(result); - }).AddOnFailureListener((exception) => + HMSManagerStart.Start(OnAwake, TAG); + } + + private void OnAwake() { - Debug.LogError($"{TAG}: exception.Message"); - }); - OnMessageClicked = OnMessageClickFunction; - OnMessageDisplay = OnMessageDisplayFunction; - OnMessageDismiss = OnMessageDismissFunction; - AGConnectAppMessaging appMessaging = AGConnectAppMessaging.Instance; - appMessaging.AddOnClickListener(OnMessageClicked); - appMessaging.AddOnDisplayListener(OnMessageDisplay); - appMessaging.AddOnDismissListener(OnMessageDismiss); - appMessaging.SetForceFetch(); - } - private void OnMessageClickFunction(AppMessage obj) - { - Debug.Log($"{TAG} OnMessageClickFunction"); - } - private void OnMessageDisplayFunction(AppMessage obj) - { - Debug.Log($"{TAG} OnMessageDisplayFunction" + obj.MessageType); - } + Debug.Log($"{TAG}: OnAwake"); + HmsInstanceId inst = HmsInstanceId.GetInstance(); + ITask idResult = inst.AAID; + idResult.AddOnSuccessListener((result) => + { + AAIDResult AAIDResult = result; + Debug.Log($"{TAG}: result.Id"); + AAIDResultAction?.Invoke(result); + }).AddOnFailureListener((exception) => + { + Debug.LogError($"{TAG}: exception.Message"); + }); + OnMessageClicked = OnMessageClickFunction; + OnMessageDisplay = OnMessageDisplayFunction; + OnMessageDismiss = OnMessageDismissFunction; + AGConnectAppMessaging appMessaging = AGConnectAppMessaging.Instance; + appMessaging.AddOnClickListener(OnMessageClicked); + appMessaging.AddOnDisplayListener(OnMessageDisplay); + appMessaging.AddOnDismissListener(OnMessageDismiss); + appMessaging.SetForceFetch(); + } + private void OnMessageClickFunction(AppMessage obj) + { + Debug.Log($"{TAG} OnMessageClickFunction"); + } + private void OnMessageDisplayFunction(AppMessage obj) + { + Debug.Log($"{TAG} OnMessageDisplayFunction" + obj.MessageType); + } - private void OnMessageDismissFunction(AppMessage obj, DismissType dismissType) - { - Debug.Log($"{TAG} OnMessageDismissFunction" + obj.MessageType); + private void OnMessageDismissFunction(AppMessage obj, DismissType dismissType) + { + Debug.Log($"{TAG} OnMessageDismissFunction" + obj.MessageType); + } } -} +} diff --git a/Assets/Huawei/Scripts/Crash/HMSCrashManager.cs b/Assets/Huawei/Scripts/Crash/HMSCrashManager.cs index e6a0f654..71fb8cf3 100644 --- a/Assets/Huawei/Scripts/Crash/HMSCrashManager.cs +++ b/Assets/Huawei/Scripts/Crash/HMSCrashManager.cs @@ -1,59 +1,61 @@ -using HmsPlugin; -using HuaweiMobileServices.Crash; +using HuaweiMobileServices.Crash; using UnityEngine; using UnityEngine.Diagnostics; -public class HMSCrashManager : HMSManagerSingleton +namespace HmsPlugin { - IAGConnectCrash agConnectCrash; - - private readonly string TAG = "[HMS] HMSCrashManager "; - - public HMSCrashManager() - { - HMSManagerStart.Start(OnAwake, TAG); - } - - private void OnAwake() - { - Debug.Log($"{TAG}: Crash OnAwake - Initialized"); - agConnectCrash = AGConnectCrash.GetInstance(); - } - - //Crash Collection enable/disable method used on AnalyticsDemo scene with enable/disable radio button configuration - public void EnableCrashCollection(bool value) - { - agConnectCrash.EnableCrashCollection(value); - Debug.Log($"{TAG}enableCrashCollection {value}"); - } - - public void TestCrash() - { - Debug.Log($"{TAG}TestCrash"); - Utils.ForceCrash(0); - } - - enum Log - { - DEBUG = 3, - INFO = 4, - WARN = 5, - ERROR = 6, - } - - public void CustomReport() + public class HMSCrashManager : HMSManagerSingleton { - agConnectCrash.SetUserId("testuser"); - agConnectCrash.Log((int)Log.DEBUG, "set debug log."); - agConnectCrash.Log((int)Log.INFO, "set info log."); - agConnectCrash.Log((int)Log.WARN, "set warning log."); - agConnectCrash.Log((int)Log.ERROR, "set error log."); - agConnectCrash.SetCustomKey("stringKey", "Hello world"); - agConnectCrash.SetCustomKey("booleanKey", false); - agConnectCrash.SetCustomKey("doubleKey", 1.1); - agConnectCrash.SetCustomKey("floatKey", 1.1f); - agConnectCrash.SetCustomKey("intKey", 0); - agConnectCrash.SetCustomKey("longKey", 11L); - Debug.Log($"{TAG}CustomReport"); + IAGConnectCrash agConnectCrash; + + private readonly string TAG = "[HMS] HMSCrashManager "; + + public HMSCrashManager() + { + HMSManagerStart.Start(OnAwake, TAG); + } + + private void OnAwake() + { + Debug.Log($"{TAG}: Crash OnAwake - Initialized"); + agConnectCrash = AGConnectCrash.GetInstance(); + } + + //Crash Collection enable/disable method used on AnalyticsDemo scene with enable/disable radio button configuration + public void EnableCrashCollection(bool value) + { + agConnectCrash.EnableCrashCollection(value); + Debug.Log($"{TAG}enableCrashCollection {value}"); + } + + public void TestCrash() + { + Debug.Log($"{TAG}TestCrash"); + Utils.ForceCrash(0); + } + + enum Log + { + DEBUG = 3, + INFO = 4, + WARN = 5, + ERROR = 6, + } + + public void CustomReport() + { + agConnectCrash.SetUserId("testuser"); + agConnectCrash.Log((int)Log.DEBUG, "set debug log."); + agConnectCrash.Log((int)Log.INFO, "set info log."); + agConnectCrash.Log((int)Log.WARN, "set warning log."); + agConnectCrash.Log((int)Log.ERROR, "set error log."); + agConnectCrash.SetCustomKey("stringKey", "Hello world"); + agConnectCrash.SetCustomKey("booleanKey", false); + agConnectCrash.SetCustomKey("doubleKey", 1.1); + agConnectCrash.SetCustomKey("floatKey", 1.1f); + agConnectCrash.SetCustomKey("intKey", 0); + agConnectCrash.SetCustomKey("longKey", 11L); + Debug.Log($"{TAG}CustomReport"); + } } } diff --git a/Assets/Huawei/Scripts/Location/GeofenceReceiver.cs b/Assets/Huawei/Scripts/Location/GeofenceReceiver.cs index 644c1c42..d7601a6a 100644 --- a/Assets/Huawei/Scripts/Location/GeofenceReceiver.cs +++ b/Assets/Huawei/Scripts/Location/GeofenceReceiver.cs @@ -1,4 +1,5 @@ -using System; +using System; +using HmsPlugin; using HuaweiMobileServices.Location; using HuaweiMobileServices.Location.Geofences; using HuaweiMobileServices.Utils; diff --git a/Assets/Huawei/Scripts/Location/HMSLocationManager.cs b/Assets/Huawei/Scripts/Location/HMSLocationManager.cs index dcd2c285..0f58ba63 100644 --- a/Assets/Huawei/Scripts/Location/HMSLocationManager.cs +++ b/Assets/Huawei/Scripts/Location/HMSLocationManager.cs @@ -5,90 +5,92 @@ using UnityEngine; using UnityEngine.Android; using HuaweiMobileServices.Location.Location; -using HmsPlugin; -public class HMSLocationManager : HMSManagerSingleton +namespace HmsPlugin { - private const string TAG = "HMSLocationManager"; + public class HMSLocationManager : HMSManagerSingleton + { + private const string TAG = "HMSLocationManager"; - public Action onLocationResult; - public Action onLocationAvailability; + public Action onLocationResult; + public Action onLocationAvailability; - public HMSLocationManager() - { - HMSManagerStart.Start(OnAwake, OnStart, TAG); - } + public HMSLocationManager() + { + HMSManagerStart.Start(OnAwake, OnStart, TAG); + } - private void OnAwake() - { - Debug.Log($"{TAG} HMSLocationManager OnAwake"); - } + private void OnAwake() + { + Debug.Log($"{TAG} HMSLocationManager OnAwake"); + } - private void OnStart() - { - Debug.Log($"{TAG} HMSLocationManager OnStart"); - } + private void OnStart() + { + Debug.Log($"{TAG} HMSLocationManager OnStart"); + } - public AndroidPendingIntent GetPendingIntentFromLocation() => LocationBroadcastReceiver.GetPendingIntent(); - public AndroidPendingIntent GetPendingIntentFromGeofence() => GeofenceBroadcastReceiver.GetPendingIntent(); + public AndroidPendingIntent GetPendingIntentFromLocation() => LocationBroadcastReceiver.GetPendingIntent(); + public AndroidPendingIntent GetPendingIntentFromGeofence() => GeofenceBroadcastReceiver.GetPendingIntent(); - #region FusedLocation + #region FusedLocation - public LocationCallback DefineLocationCallback() - { - Debug.Log($"{TAG} HMSLocationManager DefineLocationCallback"); + public LocationCallback DefineLocationCallback() + { + Debug.Log($"{TAG} HMSLocationManager DefineLocationCallback"); - LocationBridge.SetLocationCallbackListener - (new LocationCallbackListener - (LocationCallbackListener_onLocationResult, LocationCallbackListener_onLocationAvailability)); + LocationBridge.SetLocationCallbackListener + (new LocationCallbackListener + (LocationCallbackListener_onLocationResult, LocationCallbackListener_onLocationAvailability)); - return LocationBridge.GetLocationResult(); - } + return LocationBridge.GetLocationResult(); + } - private void LocationCallbackListener_onLocationResult(LocationResult locationResult) - { - Debug.LogError($"{TAG} LocationCallbackListener_onLocationResult "); - onLocationResult?.Invoke(locationResult); - } + private void LocationCallbackListener_onLocationResult(LocationResult locationResult) + { + Debug.LogError($"{TAG} LocationCallbackListener_onLocationResult "); + onLocationResult?.Invoke(locationResult); + } - private void LocationCallbackListener_onLocationAvailability(LocationAvailability locationAvailability) - { - Debug.LogError($"{TAG} LocationCallbackListener_onLocationAvailability "); - onLocationAvailability?.Invoke(locationAvailability); - } + private void LocationCallbackListener_onLocationAvailability(LocationAvailability locationAvailability) + { + Debug.LogError($"{TAG} LocationCallbackListener_onLocationAvailability "); + onLocationAvailability?.Invoke(locationAvailability); + } - #endregion + #endregion - #region Permissions + #region Permissions - public void ApplyForAllLocationPermissions() - { - LocationPermissions.RequestActivityRecognitionPermissions(); - LocationPermissions.RequestBackgroundLocationPermissions(); - LocationPermissions.RequestLocationPermission(); - RequestFineLocationPermission(); - RequestCoarseLocationPermission(); - } + public void ApplyForAllLocationPermissions() + { + LocationPermissions.RequestActivityRecognitionPermissions(); + LocationPermissions.RequestBackgroundLocationPermissions(); + LocationPermissions.RequestLocationPermission(); + RequestFineLocationPermission(); + RequestCoarseLocationPermission(); + } - public void RequestActivityRecognitionPermissions() => LocationPermissions.RequestActivityRecognitionPermissions(); + public void RequestActivityRecognitionPermissions() => LocationPermissions.RequestActivityRecognitionPermissions(); - public void RequestBackgroundLocationPermissions() => LocationPermissions.RequestBackgroundLocationPermissions(); + public void RequestBackgroundLocationPermissions() => LocationPermissions.RequestBackgroundLocationPermissions(); - public void RequestFineLocationPermission() - { - if (!Permission.HasUserAuthorizedPermission(Permission.FineLocation)) + public void RequestFineLocationPermission() { - Permission.RequestUserPermission(Permission.FineLocation); + if (!Permission.HasUserAuthorizedPermission(Permission.FineLocation)) + { + Permission.RequestUserPermission(Permission.FineLocation); + } } - } - public void RequestCoarseLocationPermission() - { - if (!Permission.HasUserAuthorizedPermission(Permission.CoarseLocation)) + public void RequestCoarseLocationPermission() { - Permission.RequestUserPermission(Permission.CoarseLocation); + if (!Permission.HasUserAuthorizedPermission(Permission.CoarseLocation)) + { + Permission.RequestUserPermission(Permission.CoarseLocation); + } } - } - #endregion + #endregion + } } diff --git a/Assets/Huawei/Scripts/Location/LocationReceiver.cs b/Assets/Huawei/Scripts/Location/LocationReceiver.cs index 04da8e53..2df46c31 100644 --- a/Assets/Huawei/Scripts/Location/LocationReceiver.cs +++ b/Assets/Huawei/Scripts/Location/LocationReceiver.cs @@ -1,4 +1,5 @@ using System; +using HmsPlugin; using HuaweiMobileServices.Location; using HuaweiMobileServices.Utils; using UnityEngine; diff --git a/Assets/Huawei/Scripts/Modeling3D/HMSModeling3dKitManager.cs b/Assets/Huawei/Scripts/Modeling3D/HMSModeling3dKitManager.cs index 27334ad1..60f5d847 100644 --- a/Assets/Huawei/Scripts/Modeling3D/HMSModeling3dKitManager.cs +++ b/Assets/Huawei/Scripts/Modeling3D/HMSModeling3dKitManager.cs @@ -1,7 +1,6 @@ using UnityEngine; using System; using System.Linq; -using HmsPlugin; using HuaweiMobileServices.Utils; using HuaweiMobileServices.Modeling3D.ObjReconstructSdk; using HuaweiMobileServices.Modeling3D.ObjReconstructSdk.Cloud; @@ -11,545 +10,548 @@ using System.IO; using System.Collections; -public class HMSModeling3dKitManager : HMSManagerSingleton +namespace HmsPlugin { - private readonly string TAG = "[HMS] HMSModeling3dKitManager "; - private const string TASK_LIST_PREFS_KEY = "3dTaskList"; - - private readonly PlayerPrefsJsonDatabase modeling3dTaskEntity = new PlayerPrefsJsonDatabase(TASK_LIST_PREFS_KEY); - - private ReconstructApplication reconstructApplication; - private Modeling3dReconstructEngine modeling3DReconstructEngine; - private Modeling3dTextureEngine modeling3DTextureEngine; - - public Action OnUploadProgress; - public Action OnDownloadProgress; - public Action OnError; - public Action OnResultDownload; - public Action OnResultUpload; - public Action OnResultPreview; - public Action OnResult3dTextureDownload; - public Action OnResult3dTextureUpload; - public Action OnResult3dTexturePreview; - public Action OnResultCaptureImage; - public Action OnErrorCaptureImage; - public Action OnProgressCaptureImage; - - - public HMSModeling3dKitManager() + public class HMSModeling3dKitManager : HMSManagerSingleton { - HMSManagerStart.Start(OnAwake, TAG); - } - private void OnAwake() - { - Init(); - } - public void Init() - { - try - { - reconstructApplication = ReconstructApplication.GetInstance(); - modeling3DReconstructEngine = Modeling3dReconstructEngine.GetInstance(); - Debug.Log(TAG + "Init: " + reconstructApplication); - } - catch (Exception ex) - { - Debug.LogError(TAG + ex.Message); - } - } - public void AuthWithAccessToken(string accessToken) - { - reconstructApplication.SetAccessToken(accessToken); - } - public void AuthWithApiKey(string apiKey) - { - reconstructApplication.SetApiKey(apiKey); - } + private readonly string TAG = "[HMS] HMSModeling3dKitManager "; + private const string TASK_LIST_PREFS_KEY = "3dTaskList"; - #region Modeling3dReconstruct Part - public Modeling3dReconstructSetting Create3DReconstructionEngine(int? ReconstructMode = null, int? TextureMode = null, int? FaceLevel = null) - { - Modeling3dReconstructSetting.Factory factory = new Modeling3dReconstructSetting.Factory(); - SetDefaultParameters(ref ReconstructMode, ref TextureMode, ref FaceLevel); + private readonly PlayerPrefsJsonDatabase modeling3dTaskEntity = new PlayerPrefsJsonDatabase(TASK_LIST_PREFS_KEY); + private ReconstructApplication reconstructApplication; + private Modeling3dReconstructEngine modeling3DReconstructEngine; + private Modeling3dTextureEngine modeling3DTextureEngine; - var modeling3dSettings = factory.SetReconstructMode((int)ReconstructMode) - .SetTextureMode((int)TextureMode) - .SetFaceLevel((int)FaceLevel) - .Create(); - Debug.Log($"{TAG} Modelling Settings FaceLevel: {modeling3dSettings.FaceLevel}, TaskType: {modeling3dSettings.FaceLevel}, TextureMode: {modeling3dSettings.TextureMode}, ReconstructMode: {modeling3dSettings.ReconstructMode}, TaskId: {modeling3dSettings.TaskId}"); - return modeling3dSettings; - } - private void SetDefaultParameters(ref int? ReconstructMode, ref int? TextureMode, ref int? FaceLevel) - { - if (ReconstructMode == null) + public Action OnUploadProgress; + public Action OnDownloadProgress; + public Action OnError; + public Action OnResultDownload; + public Action OnResultUpload; + public Action OnResultPreview; + public Action OnResult3dTextureDownload; + public Action OnResult3dTextureUpload; + public Action OnResult3dTexturePreview; + public Action OnResultCaptureImage; + public Action OnErrorCaptureImage; + public Action OnProgressCaptureImage; + + + public HMSModeling3dKitManager() { - ReconstructMode = Modeling3dReconstructConstants.ReconstructMode.PICTURE; + HMSManagerStart.Start(OnAwake, TAG); } - - if (TextureMode == null) + private void OnAwake() { - TextureMode = Modeling3dReconstructConstants.TextureMode.PBR; + Init(); } - - if (FaceLevel == null) + public void Init() { - FaceLevel = Modeling3dReconstructConstants.FaceLevel.HIGH; + try + { + reconstructApplication = ReconstructApplication.GetInstance(); + modeling3DReconstructEngine = Modeling3dReconstructEngine.GetInstance(); + Debug.Log(TAG + "Init: " + reconstructApplication); + } + catch (Exception ex) + { + Debug.LogError(TAG + ex.Message); + } } - } - public Modeling3dReconstructInitResult InitTask(Modeling3dReconstructSetting setting) - { - var modeling3DReconstructInitResult = modeling3DReconstructEngine.InitTask(setting); - - foreach (var property in modeling3DReconstructInitResult.GetType().GetProperties()) + public void AuthWithAccessToken(string accessToken) { - Debug.Log($"{TAG} Modelling Init Result {property.Name}: {property.GetValue(modeling3DReconstructInitResult)}"); + reconstructApplication.SetAccessToken(accessToken); + } + public void AuthWithApiKey(string apiKey) + { + reconstructApplication.SetApiKey(apiKey); } - return modeling3DReconstructInitResult; - } - public void UploadFile(Modeling3dReconstructSetting setting, string path = null) - { - var modeling3DReconstructInitResult = InitTask(setting); + #region Modeling3dReconstruct Part + public Modeling3dReconstructSetting Create3DReconstructionEngine(int? ReconstructMode = null, int? TextureMode = null, int? FaceLevel = null) + { + Modeling3dReconstructSetting.Factory factory = new Modeling3dReconstructSetting.Factory(); + SetDefaultParameters(ref ReconstructMode, ref TextureMode, ref FaceLevel); - string initTaskId = modeling3DReconstructInitResult.TaskId; - Debug.Log(TAG + " Return TaskId: " + initTaskId); - PlayerPrefs.SetString("currentTaskId", initTaskId); + var modeling3dSettings = factory.SetReconstructMode((int)ReconstructMode) + .SetTextureMode((int)TextureMode) + .SetFaceLevel((int)FaceLevel) + .Create(); + Debug.Log($"{TAG} Modelling Settings FaceLevel: {modeling3dSettings.FaceLevel}, TaskType: {modeling3dSettings.FaceLevel}, TextureMode: {modeling3dSettings.TextureMode}, ReconstructMode: {modeling3dSettings.ReconstructMode}, TaskId: {modeling3dSettings.TaskId}"); + return modeling3dSettings; + } + private void SetDefaultParameters(ref int? ReconstructMode, ref int? TextureMode, ref int? FaceLevel) + { + if (ReconstructMode == null) + { + ReconstructMode = Modeling3dReconstructConstants.ReconstructMode.PICTURE; + } - var taskName = ""; + if (TextureMode == null) + { + TextureMode = Modeling3dReconstructConstants.TextureMode.PBR; + } - try - { - taskName = DateTime.UtcNow.ToString("yyyyMMddHHmmss") + "-" + initTaskId.Substring(initTaskId.Length - 4); - Debug.Log($"{TAG}{taskName}"); + if (FaceLevel == null) + { + FaceLevel = Modeling3dReconstructConstants.FaceLevel.HIGH; + } } - catch (Exception e) + public Modeling3dReconstructInitResult InitTask(Modeling3dReconstructSetting setting) { - //TODO: You can add here FAQ link what is APIKEY how we can get it and use it - Debug.LogError(TAG + " UploadFile exception:" + e + " \n**********\nHint: If exception is NullReferenceException check your APIKey is valid.\n********\n"); - return; - } + var modeling3DReconstructInitResult = modeling3DReconstructEngine.InitTask(setting); - OnUploadProgress += (taskId, progress, obj) => - { - //check prograss is integer or not - if (progress % 1 == 0) - Debug.Log($"{TAG} OnUploadProgress TaskId: {taskId} and Progress: {progress}"); - }; + foreach (var property in modeling3DReconstructInitResult.GetType().GetProperties()) + { + Debug.Log($"{TAG} Modelling Init Result {property.Name}: {property.GetValue(modeling3DReconstructInitResult)}"); + } - OnError += (taskId, errorCode, errorMessage) => + return modeling3DReconstructInitResult; + } + public void UploadFile(Modeling3dReconstructSetting setting, string path = null) { - Debug.LogError(TAG + "OnError taskId:" + taskId + " errorCode:" + errorCode + " errorMessage:" + errorMessage); - HMSDispatcher.InvokeAsync(() => + var modeling3DReconstructInitResult = InitTask(setting); + + string initTaskId = modeling3DReconstructInitResult.TaskId; + + Debug.Log(TAG + " Return TaskId: " + initTaskId); + PlayerPrefs.SetString("currentTaskId", initTaskId); + + var taskName = ""; + + try { - AndroidToast.MakeText($"{errorMessage} - {errorCode}").Show(); - }); - }; + taskName = DateTime.UtcNow.ToString("yyyyMMddHHmmss") + "-" + initTaskId.Substring(initTaskId.Length - 4); + Debug.Log($"{TAG}{taskName}"); + } + catch (Exception e) + { + //TODO: You can add here FAQ link what is APIKEY how we can get it and use it + Debug.LogError(TAG + " UploadFile exception:" + e + " \n**********\nHint: If exception is NullReferenceException check your APIKey is valid.\n********\n"); + return; + } - OnResultUpload += (taskId, result, obj) => - { - Debug.Log(TAG + "OnResult taskId:" + result.TaskId + " result:" + result); + OnUploadProgress += (taskId, progress, obj) => + { + //check prograss is integer or not + if (progress % 1 == 0) + Debug.Log($"{TAG} OnUploadProgress TaskId: {taskId} and Progress: {progress}"); + }; - }; + OnError += (taskId, errorCode, errorMessage) => + { + Debug.LogError(TAG + "OnError taskId:" + taskId + " errorCode:" + errorCode + " errorMessage:" + errorMessage); + HMSDispatcher.InvokeAsync(() => + { + AndroidToast.MakeText($"{errorMessage} - {errorCode}").Show(); + }); + }; + + OnResultUpload += (taskId, result, obj) => + { + Debug.Log(TAG + "OnResult taskId:" + result.TaskId + " result:" + result); - var listener = new Modeling3dReconstructUploadListener(new Modeling3dReconstructUploadORDownloadORPreviewListener(OnUploadProgress, OnError, OnResultUpload)); + }; - modeling3DReconstructEngine.SetReconstructUploadListener(listener); + var listener = new Modeling3dReconstructUploadListener(new Modeling3dReconstructUploadORDownloadORPreviewListener(OnUploadProgress, OnError, OnResultUpload)); - string uploadsPath = Application.persistentDataPath; - if (!string.IsNullOrWhiteSpace(path)) - { - if (!File.Exists(path)) - uploadsPath = Application.persistentDataPath.Split('/').Take(4).Aggregate((a, b) => a + "/" + b) + "/" + path.Split(':').Last(); - else - uploadsPath = path; - } - Debug.Log(TAG + "Enviroment " + uploadsPath); + modeling3DReconstructEngine.SetReconstructUploadListener(listener); + string uploadsPath = Application.persistentDataPath; + if (!string.IsNullOrWhiteSpace(path)) + { + if (!File.Exists(path)) + uploadsPath = Application.persistentDataPath.Split('/').Take(4).Aggregate((a, b) => a + "/" + b) + "/" + path.Split(':').Last(); + else + uploadsPath = path; + } + Debug.Log(TAG + "Enviroment " + uploadsPath); - //get all files in uploads folder cross platform - string file = Directory.GetFiles(uploadsPath).FirstOrDefault(); - Debug.Log(TAG + "UploadFile: " + file); + //get all files in uploads folder cross platform + string file = Directory.GetFiles(uploadsPath).FirstOrDefault(); + Debug.Log(TAG + "UploadFile: " + file); - modeling3dTaskEntity.Insert(new Modeling3dDTO() - { - TaskId = initTaskId, - Name = taskName, - Status = "Uploading", - Type = 1, - CoverImagePath = file - }); - RequestPermission(); - modeling3DReconstructEngine.UploadFile(initTaskId, uploadsPath); - } - public IEnumerator RequestPermission() - { - if (!UnityEngine.Android.Permission.HasUserAuthorizedPermission(UnityEngine.Android.Permission.ExternalStorageWrite)) + modeling3dTaskEntity.Insert(new Modeling3dDTO() + { + TaskId = initTaskId, + Name = taskName, + Status = "Uploading", + Type = 1, + CoverImagePath = file + }); + RequestPermission(); + modeling3DReconstructEngine.UploadFile(initTaskId, uploadsPath); + + } + public IEnumerator RequestPermission() { - UnityEngine.Android.Permission.RequestUserPermission(UnityEngine.Android.Permission.ExternalStorageWrite); - while (!UnityEngine.Android.Permission.HasUserAuthorizedPermission(UnityEngine.Android.Permission.ExternalStorageWrite)) + if (!UnityEngine.Android.Permission.HasUserAuthorizedPermission(UnityEngine.Android.Permission.ExternalStorageWrite)) { - yield return null; + UnityEngine.Android.Permission.RequestUserPermission(UnityEngine.Android.Permission.ExternalStorageWrite); + while (!UnityEngine.Android.Permission.HasUserAuthorizedPermission(UnityEngine.Android.Permission.ExternalStorageWrite)) + { + yield return null; + } } + Debug.Log("Permission Granted"); } - Debug.Log("Permission Granted"); - } - public void DownloadFile(Modeling3dReconstructDownloadConfig config, string taskID, string path) - { - OnDownloadProgress += (taskId, progress, obj) => + public void DownloadFile(Modeling3dReconstructDownloadConfig config, string taskID, string path) { - if (progress % 1 == 0) - Debug.Log(TAG + "OnDownloadProgress taskId:" + taskId + " progress:" + progress); - }; + OnDownloadProgress += (taskId, progress, obj) => + { + if (progress % 1 == 0) + Debug.Log(TAG + "OnDownloadProgress taskId:" + taskId + " progress:" + progress); + }; - OnError += (taskId, errorCode, errorMessage) => - { - Debug.LogError(TAG + "OnError taskId:" + taskId + " errorCode:" + errorCode + " errorMessage:" + errorMessage); - HMSDispatcher.InvokeAsync(() => + OnError += (taskId, errorCode, errorMessage) => { - AndroidToast.MakeText($"{errorMessage} - {errorCode}").Show(); - }); - }; + Debug.LogError(TAG + "OnError taskId:" + taskId + " errorCode:" + errorCode + " errorMessage:" + errorMessage); + HMSDispatcher.InvokeAsync(() => + { + AndroidToast.MakeText($"{errorMessage} - {errorCode}").Show(); + }); + }; + + OnResultDownload += (taskId, result, obj) => + { + Debug.Log(TAG + "OnResult taskId:" + taskId + " result:" + result); + }; - OnResultDownload += (taskId, result, obj) => - { - Debug.Log(TAG + "OnResult taskId:" + taskId + " result:" + result); - }; + string downloadsPath = path ?? Path.Combine(Application.persistentDataPath, "images"); - string downloadsPath = path ?? Path.Combine(Application.persistentDataPath, "images"); + if (!string.IsNullOrWhiteSpace(path)) + { + downloadsPath = Application.persistentDataPath.Split('/').Take(4).Aggregate((a, b) => a + "/" + b) + "/" + path.Split(':').Last(); + } + + Debug.Log(TAG + "DownloadsPath: " + downloadsPath); + + PlayerPrefs.SetString("currentTaskId", taskID); + + + var listener = new Modeling3dReconstructDownloadListener(new Modeling3dReconstructUploadORDownloadORPreviewListener(OnDownloadProgress, OnError, OnResultDownload)); + + modeling3DReconstructEngine.SetReconstructDownloadListener(listener); + + modeling3DReconstructEngine.DownloadModelWithConfig(taskID, downloadsPath, config); - if (!string.IsNullOrWhiteSpace(path)) - { - downloadsPath = Application.persistentDataPath.Split('/').Take(4).Aggregate((a, b) => a + "/" + b) + "/" + path.Split(':').Last(); } + public void PreviewFile(Modeling3dReconstructPreviewConfig config, string taskID) + { + OnError += (taskId, errorCode, errorMessage) => + { + Debug.LogError(TAG + "OnError taskId:" + taskId + " errorCode:" + errorCode + " errorMessage:" + errorMessage); + HMSDispatcher.InvokeAsync(() => + { + AndroidToast.MakeText($"{errorMessage} - {errorCode}").Show(); + }); + }; + + OnResultPreview += (taskId, obj) => + { + Debug.Log(TAG + "OnResult taskId:" + taskId + " result:" + obj); + }; + var listener = new Modeling3dReconstructPreviewListener(new Modeling3dReconstructUploadORDownloadORPreviewListener(OnError, OnResultPreview)); + PlayerPrefs.SetString("currentTaskId", taskID); - Debug.Log(TAG + "DownloadsPath: " + downloadsPath); + modeling3DReconstructEngine.PreviewModelWithConfig(taskID, config, listener); + } + public Modeling3dReconstructQueryResult QueryTask(string taskId) + { + var reconstructTaskUtils = Modeling3dReconstructTaskUtils.GetInstance(); - PlayerPrefs.SetString("currentTaskId", taskID); + var result = reconstructTaskUtils.QueryTask(taskId); + var restrictStatus = QueryTaskRestrictStatus(taskId); - var listener = new Modeling3dReconstructDownloadListener(new Modeling3dReconstructUploadORDownloadORPreviewListener(OnDownloadProgress, OnError, OnResultDownload)); + Debug.Log(TAG + "QueryTask result status:" + result.Status + " taskId:" + result.TaskId + " RedCode:" + result.RetCode + " RedMessage:" + result.RetMessage + " RedConstMessage:" + result?.ReconstructFailMessage); - modeling3DReconstructEngine.SetReconstructDownloadListener(listener); + Debug.Log(TAG + "QueryTask Restrict Status: " + restrictStatus); - modeling3DReconstructEngine.DownloadModelWithConfig(taskID, downloadsPath, config); + return result; - } - public void PreviewFile(Modeling3dReconstructPreviewConfig config, string taskID) - { - OnError += (taskId, errorCode, errorMessage) => + } + public int QueryTaskRestrictStatus(string taskId) { - Debug.LogError(TAG + "OnError taskId:" + taskId + " errorCode:" + errorCode + " errorMessage:" + errorMessage); - HMSDispatcher.InvokeAsync(() => - { - AndroidToast.MakeText($"{errorMessage} - {errorCode}").Show(); - }); - }; + var reconstructTaskUtils = Modeling3dReconstructTaskUtils.GetInstance(); + var result = reconstructTaskUtils.QueryTaskRestrictStatus(taskId); + Debug.LogFormat(TAG + "Query Task Restrict Status: {0}", result); + return result; - OnResultPreview += (taskId, obj) => + } + public void DeleteTask(string taskId) { - Debug.Log(TAG + "OnResult taskId:" + taskId + " result:" + obj); - }; - var listener = new Modeling3dReconstructPreviewListener(new Modeling3dReconstructUploadORDownloadORPreviewListener(OnError, OnResultPreview)); - PlayerPrefs.SetString("currentTaskId", taskID); + var result = Modeling3dReconstructTaskUtils.GetInstance().DeleteTask(taskId); - modeling3DReconstructEngine.PreviewModelWithConfig(taskID, config, listener); - } - public Modeling3dReconstructQueryResult QueryTask(string taskId) - { - var reconstructTaskUtils = Modeling3dReconstructTaskUtils.GetInstance(); + var text = string.Format("Task Deleted {0}. Result: {1}", taskId, result); - var result = reconstructTaskUtils.QueryTask(taskId); + AndroidToast.MakeText(text).Show(); - var restrictStatus = QueryTaskRestrictStatus(taskId); + Debug.Log(TAG + text); + } + public int CancelUpload3dReconstruct(string taskId) + { + Debug.LogFormat(TAG + "CancelUpload3dReconstruct taskId: {0}", taskId); + var result = modeling3DReconstructEngine.CancelUpload(taskId); + return result; + } + public int CancelDownload3dReconstruct(string taskId) + { + Debug.LogFormat(TAG + "CancelDownload3dReconstruct taskId: {0}", taskId); + var result = modeling3DReconstructEngine.CancelDownload(taskId); + return result; + } + #endregion - Debug.Log(TAG + "QueryTask result status:" + result.Status + " taskId:" + result.TaskId + " RedCode:" + result.RetCode + " RedMessage:" + result.RetMessage + " RedConstMessage:" + result?.ReconstructFailMessage); + #region Modeling3dCapture Part + public void Create3DCaptureImageEngine(AndroidJavaObject context) + { - Debug.Log(TAG + "QueryTask Restrict Status: " + restrictStatus); + var modeling3dCaptureImageEngine = Modeling3dCaptureImageEngine.GetInstance(); - return result; + var setting = new Modeling3dCaptureSetting.Factory().SetAzimuthNum(30).SetLatitudeNum(3).SetRadius(2).Create(); - } - public int QueryTaskRestrictStatus(string taskId) - { - var reconstructTaskUtils = Modeling3dReconstructTaskUtils.GetInstance(); - var result = reconstructTaskUtils.QueryTaskRestrictStatus(taskId); - Debug.LogFormat(TAG + "Query Task Restrict Status: {0}", result); - return result; + modeling3dCaptureImageEngine.SetCaptureConfig(setting); - } - public void DeleteTask(string taskId) - { - var result = Modeling3dReconstructTaskUtils.GetInstance().DeleteTask(taskId); - var text = string.Format("Task Deleted {0}. Result: {1}", taskId, result); + string fileSavePath = Application.persistentDataPath + (DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond); - AndroidToast.MakeText(text).Show(); + OnProgressCaptureImage += (progress) => + { + Debug.Log(TAG + "OnProgressCaptureImage progress:" + progress); + }; - Debug.Log(TAG + text); - } - public int CancelUpload3dReconstruct(string taskId) - { - Debug.LogFormat(TAG + "CancelUpload3dReconstruct taskId: {0}", taskId); - var result = modeling3DReconstructEngine.CancelUpload(taskId); - return result; - } - public int CancelDownload3dReconstruct(string taskId) - { - Debug.LogFormat(TAG + "CancelDownload3dReconstruct taskId: {0}", taskId); - var result = modeling3DReconstructEngine.CancelDownload(taskId); - return result; - } - #endregion + OnErrorCaptureImage += (errorCode, errorMessage) => + { + Debug.LogError(TAG + "OnError errorCode:" + errorCode + " errorMessage:" + errorMessage); + }; - #region Modeling3dCapture Part - public void Create3DCaptureImageEngine(AndroidJavaObject context) - { + OnResultCaptureImage += () => + { + Debug.Log(TAG + "OnResult"); + }; - var modeling3dCaptureImageEngine = Modeling3dCaptureImageEngine.GetInstance(); + var listener = new HuaweiMobileServices.Modeling3D.ModelingCaptureSdk.Modeling3dCaptureImageListener(new HmsPlugin.Modeling3dCaptureImageListener(OnProgressCaptureImage, OnErrorCaptureImage, OnResultCaptureImage)); - var setting = new Modeling3dCaptureSetting.Factory().SetAzimuthNum(30).SetLatitudeNum(3).SetRadius(2).Create(); - modeling3dCaptureImageEngine.SetCaptureConfig(setting); + modeling3dCaptureImageEngine.CaptureImage(fileSavePath, context, listener); - string fileSavePath = Application.persistentDataPath + (DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond); + Debug.Log(TAG + "Capture Image"); - OnProgressCaptureImage += (progress) => - { - Debug.Log(TAG + "OnProgressCaptureImage progress:" + progress); - }; + } + #endregion - OnErrorCaptureImage += (errorCode, errorMessage) => + #region MaterialGenerate Part + public Modeling3dTextureSetting Create3dTextureEngine() { - Debug.LogError(TAG + "OnError errorCode:" + errorCode + " errorMessage:" + errorMessage); - }; + modeling3DTextureEngine = Modeling3dTextureEngine.GetInstance(); + var settings = new Modeling3dTextureSetting.Factory().SetTextureMode(Modeling3dTextureConstants.AlgorithmMode.AI).Create(); - OnResultCaptureImage += () => - { - Debug.Log(TAG + "OnResult"); - }; + Debug.LogFormat(TAG + "Create3dTextureEngine settings texture mode: {0}", settings.TextureMode); - var listener = new HuaweiMobileServices.Modeling3D.ModelingCaptureSdk.Modeling3dCaptureImageListener(new HmsPlugin.Modeling3dCaptureImageListener(OnProgressCaptureImage, OnErrorCaptureImage, OnResultCaptureImage)); + return settings; + } + public Modeling3dTextureInitResult InitTask(Modeling3dTextureSetting setting) + { + var modeling3DTextureInitResult = modeling3DTextureEngine.InitTask(setting); + modeling3DTextureInitResult.GetType().GetProperties().ToList().ForEach(x => Debug.Log(TAG + "Modelling Init Result " + x.Name + ":" + x.GetValue(modeling3DTextureInitResult))); + return modeling3DTextureInitResult; + } + public string AsyncUploadFile(Modeling3dTextureSetting setting, string path) + { + var modeling3DTextureInitResult = InitTask(setting); - modeling3dCaptureImageEngine.CaptureImage(fileSavePath, context, listener); + string taskID = modeling3DTextureInitResult.TaskId; - Debug.Log(TAG + "Capture Image"); + OnUploadProgress += (taskId, progress, obj) => + { + Debug.Log(TAG + "OnUploadProgress taskId:" + taskId + " progress:" + progress); + }; - } - #endregion + OnError += (taskId, errorCode, errorMessage) => + { + Debug.LogError(TAG + "OnError taskId:" + taskId + " errorCode:" + errorCode + " errorMessage:" + errorMessage); + }; - #region MaterialGenerate Part - public Modeling3dTextureSetting Create3dTextureEngine() - { - modeling3DTextureEngine = Modeling3dTextureEngine.GetInstance(); - var settings = new Modeling3dTextureSetting.Factory().SetTextureMode(Modeling3dTextureConstants.AlgorithmMode.AI).Create(); + OnResult3dTextureUpload += (taskId, result, obj) => + { + Debug.Log(TAG + "OnResult taskId:" + result.TaskId + " result:" + result); + }; - Debug.LogFormat(TAG + "Create3dTextureEngine settings texture mode: {0}", settings.TextureMode); + Modeling3dTextureUploadListener listener = new Modeling3dTextureUploadListener(new Modeling3dTextureUploadORDownloadORPreviewListener(OnUploadProgress, OnError, OnResult3dTextureUpload)); - return settings; - } - public Modeling3dTextureInitResult InitTask(Modeling3dTextureSetting setting) - { - var modeling3DTextureInitResult = modeling3DTextureEngine.InitTask(setting); + if (modeling3DTextureEngine == null) + { + modeling3DTextureEngine = Modeling3dTextureEngine.GetInstance(); + } - modeling3DTextureInitResult.GetType().GetProperties().ToList().ForEach(x => Debug.Log(TAG + "Modelling Init Result " + x.Name + ":" + x.GetValue(modeling3DTextureInitResult))); + modeling3DTextureEngine.SetTextureUploadListener(listener); - return modeling3DTextureInitResult; - } - public string AsyncUploadFile(Modeling3dTextureSetting setting, string path) - { - var modeling3DTextureInitResult = InitTask(setting); + string uploadsPath = Application.persistentDataPath; + if (!string.IsNullOrWhiteSpace(path)) + { + if (!File.Exists(path)) + uploadsPath = Application.persistentDataPath.Split('/').Take(4).Aggregate((a, b) => a + "/" + b) + "/" + path.Split(':').Last(); + else + uploadsPath = path; + } - string taskID = modeling3DTextureInitResult.TaskId; + Debug.LogFormat(TAG + "AsyncUploadFile uploadPath: {0}", uploadsPath); - OnUploadProgress += (taskId, progress, obj) => - { - Debug.Log(TAG + "OnUploadProgress taskId:" + taskId + " progress:" + progress); - }; + modeling3DTextureEngine.AsyncUploadFile(taskID, uploadsPath); - OnError += (taskId, errorCode, errorMessage) => - { - Debug.LogError(TAG + "OnError taskId:" + taskId + " errorCode:" + errorCode + " errorMessage:" + errorMessage); - }; + Debug.LogFormat(TAG + "AsyncUploadFile taskId: {0}", taskID); - OnResult3dTextureUpload += (taskId, result, obj) => + return taskID; + } + public void AsyncDownloadFile(string taskID, string savePath) { - Debug.Log(TAG + "OnResult taskId:" + result.TaskId + " result:" + result); - }; - - Modeling3dTextureUploadListener listener = new Modeling3dTextureUploadListener(new Modeling3dTextureUploadORDownloadORPreviewListener(OnUploadProgress, OnError, OnResult3dTextureUpload)); + OnDownloadProgress += (taskId, progress, obj) => + { + Debug.Log(TAG + "OnDownloadProgress taskId:" + taskId + " progress:" + progress); + }; - if (modeling3DTextureEngine == null) - { - modeling3DTextureEngine = Modeling3dTextureEngine.GetInstance(); - } + OnError += (taskId, errorCode, errorMessage) => + { + Debug.LogError(TAG + "OnError taskId:" + taskId + " errorCode:" + errorCode + " errorMessage:" + errorMessage); + }; - modeling3DTextureEngine.SetTextureUploadListener(listener); + OnResultDownload += (taskId, result, obj) => + { + Debug.Log(TAG + "OnResult taskId:" + taskId + " result:" + result); + }; - string uploadsPath = Application.persistentDataPath; - if (!string.IsNullOrWhiteSpace(path)) - { - if (!File.Exists(path)) - uploadsPath = Application.persistentDataPath.Split('/').Take(4).Aggregate((a, b) => a + "/" + b) + "/" + path.Split(':').Last(); - else - uploadsPath = path; - } + string downloadsPath = Application.persistentDataPath; + if (!string.IsNullOrWhiteSpace(savePath)) + { + downloadsPath = Application.persistentDataPath.Split('/').Take(4).Aggregate((a, b) => a + "/" + b) + "/" + savePath.Split(':').Last(); + } + Debug.LogFormat(TAG + "AsyncDownloadFile taskId: {0} savePath: {1}", taskID, downloadsPath); - Debug.LogFormat(TAG + "AsyncUploadFile uploadPath: {0}", uploadsPath); + Modeling3dTextureDownloadListener listener = new Modeling3dTextureDownloadListener(new Modeling3dTextureUploadORDownloadORPreviewListener(OnDownloadProgress, OnError, OnResult3dTextureDownload)); - modeling3DTextureEngine.AsyncUploadFile(taskID, uploadsPath); + if (modeling3DTextureEngine == null) + { + modeling3DTextureEngine = Modeling3dTextureEngine.GetInstance(); + } - Debug.LogFormat(TAG + "AsyncUploadFile taskId: {0}", taskID); + modeling3DTextureEngine.SetTextureDownloadListener(listener); - return taskID; - } - public void AsyncDownloadFile(string taskID, string savePath) - { - OnDownloadProgress += (taskId, progress, obj) => + modeling3DTextureEngine.AsyncDownloadTexture(taskID, downloadsPath); + } + public void PreviewFile3dTexture(string taskID) { - Debug.Log(TAG + "OnDownloadProgress taskId:" + taskId + " progress:" + progress); - }; + OnDownloadProgress += (taskId, progress, obj) => + { + Debug.Log(TAG + "OnDownloadProgress taskId:" + taskId + " progress:" + progress); + }; - OnError += (taskId, errorCode, errorMessage) => - { - Debug.LogError(TAG + "OnError taskId:" + taskId + " errorCode:" + errorCode + " errorMessage:" + errorMessage); - }; + OnError += (taskId, errorCode, errorMessage) => + { + Debug.LogError(TAG + "OnError taskId:" + taskId + " errorCode:" + errorCode + " errorMessage:" + errorMessage); + }; - OnResultDownload += (taskId, result, obj) => - { - Debug.Log(TAG + "OnResult taskId:" + taskId + " result:" + result); - }; + OnResult3dTexturePreview += (taskId, obj) => + { + Debug.Log(TAG + "OnResult taskId:" + taskId + " result:" + obj); + }; - string downloadsPath = Application.persistentDataPath; - if (!string.IsNullOrWhiteSpace(savePath)) - { - downloadsPath = Application.persistentDataPath.Split('/').Take(4).Aggregate((a, b) => a + "/" + b) + "/" + savePath.Split(':').Last(); - } - Debug.LogFormat(TAG + "AsyncDownloadFile taskId: {0} savePath: {1}", taskID, downloadsPath); + Modeling3dTexturePreviewListener listener = new Modeling3dTexturePreviewListener(new Modeling3dTextureUploadORDownloadORPreviewListener(OnDownloadProgress, OnError, OnResult3dTexturePreview)); - Modeling3dTextureDownloadListener listener = new Modeling3dTextureDownloadListener(new Modeling3dTextureUploadORDownloadORPreviewListener(OnDownloadProgress, OnError, OnResult3dTextureDownload)); + if (modeling3DTextureEngine == null) + { + modeling3DTextureEngine = Modeling3dTextureEngine.GetInstance(); + } - if (modeling3DTextureEngine == null) - { - modeling3DTextureEngine = Modeling3dTextureEngine.GetInstance(); + modeling3DTextureEngine.PreviewTexture(taskID, listener); } + public Modeling3dTextureQueryResult QueryTaskModeling3dTexture(string taskId) + { + Modeling3dTextureTaskUtils texture3dTaskUtils = Modeling3dTextureTaskUtils.GetInstance(); - modeling3DTextureEngine.SetTextureDownloadListener(listener); + Modeling3dTextureQueryResult result = texture3dTaskUtils.QueryTask(taskId); - modeling3DTextureEngine.AsyncDownloadTexture(taskID, downloadsPath); - } - public void PreviewFile3dTexture(string taskID) - { - OnDownloadProgress += (taskId, progress, obj) => - { - Debug.Log(TAG + "OnDownloadProgress taskId:" + taskId + " progress:" + progress); - }; + Debug.Log(TAG + " Modeling3dTexture QueryTask result status:" + result.Status + " taskId:" + result.TaskId + " RedCode:" + result.RetCode + " RedMessage:" + result.RetMsg); - OnError += (taskId, errorCode, errorMessage) => + return result; + } + public int DeleteTaskModeling3dTexture(string taskId) { - Debug.LogError(TAG + "OnError taskId:" + taskId + " errorCode:" + errorCode + " errorMessage:" + errorMessage); - }; + var result = Modeling3dTextureTaskUtils.GetInstance().DeleteTask(taskId); - OnResult3dTexturePreview += (taskId, obj) => + Debug.Log(TAG + string.Format("Modeling3dTexture Task Deleted {0}", taskId)); + return result; + } + public int QueryTaskRestrictStatusModeling3dTexture(string taskId) { - Debug.Log(TAG + "OnResult taskId:" + taskId + " result:" + obj); - }; - - Modeling3dTexturePreviewListener listener = new Modeling3dTexturePreviewListener(new Modeling3dTextureUploadORDownloadORPreviewListener(OnDownloadProgress, OnError, OnResult3dTexturePreview)); + var reconstructTaskUtils = Modeling3dTextureTaskUtils.GetInstance(); + var result = reconstructTaskUtils.QueryTaskRestrictStatus(taskId); + Debug.LogFormat(TAG + "Modeling3dTexture Query Task Restrict Status: {0}", result); + return result; - if (modeling3DTextureEngine == null) + } + public int SetTaskRestrictStatusModeling3dTexture(string taskId, int restrictStatus) { - modeling3DTextureEngine = Modeling3dTextureEngine.GetInstance(); + var reconstructTaskUtils = Modeling3dTextureTaskUtils.GetInstance(); + var result = reconstructTaskUtils.SetTaskRestrictStatus(taskId, restrictStatus); + Debug.LogFormat(TAG + "Modeling3dTexture Set Task Restrict Status: {0}", result); + return result; } + /* Call the synchronous API, passing the file path of a single image, path for saving the texture map, and configurator. + Call the synchronous API to obtain the generated texture maps in real time.*/ + public int SyncGenerateTexture(string imagePath, string downloadPath, Modeling3dTextureSetting setting) + { + if (modeling3DTextureEngine == null) + { + modeling3DTextureEngine = Modeling3dTextureEngine.GetInstance(); + } - modeling3DTextureEngine.PreviewTexture(taskID, listener); - } - public Modeling3dTextureQueryResult QueryTaskModeling3dTexture(string taskId) - { - Modeling3dTextureTaskUtils texture3dTaskUtils = Modeling3dTextureTaskUtils.GetInstance(); - - Modeling3dTextureQueryResult result = texture3dTaskUtils.QueryTask(taskId); - - Debug.Log(TAG + " Modeling3dTexture QueryTask result status:" + result.Status + " taskId:" + result.TaskId + " RedCode:" + result.RetCode + " RedMessage:" + result.RetMsg); - - return result; - } - public int DeleteTaskModeling3dTexture(string taskId) - { - var result = Modeling3dTextureTaskUtils.GetInstance().DeleteTask(taskId); + int result = modeling3DTextureEngine.SyncGenerateTexture(imagePath, downloadPath, setting); - Debug.Log(TAG + string.Format("Modeling3dTexture Task Deleted {0}", taskId)); - return result; - } - public int QueryTaskRestrictStatusModeling3dTexture(string taskId) - { - var reconstructTaskUtils = Modeling3dTextureTaskUtils.GetInstance(); - var result = reconstructTaskUtils.QueryTaskRestrictStatus(taskId); - Debug.LogFormat(TAG + "Modeling3dTexture Query Task Restrict Status: {0}", result); - return result; + return result; + } - } - public int SetTaskRestrictStatusModeling3dTexture(string taskId, int restrictStatus) - { - var reconstructTaskUtils = Modeling3dTextureTaskUtils.GetInstance(); - var result = reconstructTaskUtils.SetTaskRestrictStatus(taskId, restrictStatus); - Debug.LogFormat(TAG + "Modeling3dTexture Set Task Restrict Status: {0}", result); - return result; - } - /* Call the synchronous API, passing the file path of a single image, path for saving the texture map, and configurator. - Call the synchronous API to obtain the generated texture maps in real time.*/ - public int SyncGenerateTexture(string imagePath, string downloadPath, Modeling3dTextureSetting setting) - { - if (modeling3DTextureEngine == null) + public string IdentifyProgressStatus(int status) { - modeling3DTextureEngine = Modeling3dTextureEngine.GetInstance(); + switch (status) + { + case (int)ProgressStatus.INITED: + return "Task initialization is complete."; + case (int)ProgressStatus.UPLOAD_COMPLETED: + return "File upload is complete."; + case (int)ProgressStatus.TEXTURE_START: + return "A material generation task starts."; + case (int)ProgressStatus.TEXTURE_COMPLETED: + return "A material generation task is complete."; + case (int)ProgressStatus.TEXTURE_FAILED: + return "A material generation task fails."; + default: + return "Unknown status."; + } } + #endregion - int result = modeling3DTextureEngine.SyncGenerateTexture(imagePath, downloadPath, setting); - - return result; - } - - public string IdentifyProgressStatus(int status) - { - switch (status) + public enum ProgressStatus { - case (int)ProgressStatus.INITED: - return "Task initialization is complete."; - case (int)ProgressStatus.UPLOAD_COMPLETED: - return "File upload is complete."; - case (int)ProgressStatus.TEXTURE_START: - return "A material generation task starts."; - case (int)ProgressStatus.TEXTURE_COMPLETED: - return "A material generation task is complete."; - case (int)ProgressStatus.TEXTURE_FAILED: - return "A material generation task fails."; - default: - return "Unknown status."; + INITED, + UPLOAD_COMPLETED, + TEXTURE_START, + TEXTURE_COMPLETED, + TEXTURE_FAILED + } + public enum RestrictStatus + { + UNRESTRICT, + RESTRICT } } - #endregion - public enum ProgressStatus - { - INITED, - UPLOAD_COMPLETED, - TEXTURE_START, - TEXTURE_COMPLETED, - TEXTURE_FAILED - } - public enum RestrictStatus - { - UNRESTRICT, - RESTRICT - } } - diff --git a/Assets/Huawei/Scripts/Modeling3D/Modeling3dDTO.cs b/Assets/Huawei/Scripts/Modeling3D/Modeling3dDTO.cs index 49f375cd..95111644 100644 --- a/Assets/Huawei/Scripts/Modeling3D/Modeling3dDTO.cs +++ b/Assets/Huawei/Scripts/Modeling3D/Modeling3dDTO.cs @@ -1,35 +1,38 @@ using System; -[Serializable] -public class Modeling3dDTO +namespace HmsPlugin { - public string TaskId; - public string Status; - public int Type; //1-Upload, 2-Download, 3-Preview - public string Name; - public string CoverImagePath; - public string UploadFilePath; - public string DownloadFilePath; - - public override string ToString() + [Serializable] + public class Modeling3dDTO { - return $"TaskId: {TaskId} Status: {Status} Type: {Type} Name: {Name}"; - } + public string TaskId; + public string Status; + public int Type; //1-Upload, 2-Download, 3-Preview + public string Name; + public string CoverImagePath; + public string UploadFilePath; + public string DownloadFilePath; - public override bool Equals(object obj) - { - if (obj is Modeling3dDTO) + public override string ToString() + { + return $"TaskId: {TaskId} Status: {Status} Type: {Type} Name: {Name}"; + } + + public override bool Equals(object obj) { - return TaskId == (obj as Modeling3dDTO).TaskId; + if (obj is Modeling3dDTO) + { + return TaskId == (obj as Modeling3dDTO).TaskId; + } + if (obj is string) + { + return TaskId == (string)obj; + } + return false; } - if (obj is string) + public override int GetHashCode() { - return TaskId == (string)obj; + return base.GetHashCode(); } - return false; - } - public override int GetHashCode() - { - return base.GetHashCode(); } } diff --git a/Assets/Huawei/Scripts/RemoteConfig/HMSRemoteConfigManager.cs b/Assets/Huawei/Scripts/RemoteConfig/HMSRemoteConfigManager.cs index 1a59e304..69378dbc 100644 --- a/Assets/Huawei/Scripts/RemoteConfig/HMSRemoteConfigManager.cs +++ b/Assets/Huawei/Scripts/RemoteConfig/HMSRemoteConfigManager.cs @@ -1,154 +1,157 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System; using UnityEngine; using HuaweiMobileServices.RemoteConfig; using HuaweiMobileServices.Base; using HuaweiMobileServices.Utils; -using HmsPlugin; -public class HMSRemoteConfigManager : HMSManagerSingleton + +namespace HmsPlugin { - const string TAG = "[HMS] RemoteConfigManager"; + public class HMSRemoteConfigManager : HMSManagerSingleton + { + const string TAG = "[HMS] RemoteConfigManager"; - public Action OnFetchSuccess { get; set; } - public Action OnFetchFailure { get; set; } + public Action OnFetchSuccess { get; set; } + public Action OnFetchFailure { get; set; } - IAGConnectConfig agc = null; + IAGConnectConfig agc = null; - public HMSRemoteConfigManager() - { - HMSManagerStart.Start(OnAwake, TAG); - } + public HMSRemoteConfigManager() + { + HMSManagerStart.Start(OnAwake, TAG); + } - private void OnAwake() - { - GetInstance(); - if (HMSRemoteConfigSettings.Instance != null) + private void OnAwake() { - SetDeveloperMode(HMSRemoteConfigSettings.Instance.Settings.GetBool(HMSRemoteConfigSettings.DeveloperMode)); - if (HMSRemoteConfigSettings.Instance.Settings.GetBool(HMSRemoteConfigSettings.ApplyDefaultValues)) + GetInstance(); + if (HMSRemoteConfigSettings.Instance != null) { - var values = HMSRemoteDefaultValueSettings.Instance.GetDefaultValues(); - if (values != null && values.Count > 0) + SetDeveloperMode(HMSRemoteConfigSettings.Instance.Settings.GetBool(HMSRemoteConfigSettings.DeveloperMode)); + if (HMSRemoteConfigSettings.Instance.Settings.GetBool(HMSRemoteConfigSettings.ApplyDefaultValues)) { - ApplyDefault(values); + var values = HMSRemoteDefaultValueSettings.Instance.GetDefaultValues(); + if (values != null && values.Count > 0) + { + ApplyDefault(values); + } } } + Debug.Log($"{TAG}: Start() "); } - Debug.Log($"{TAG}: Start() "); - } - //getInstance() Obtains an instance of AGConnectConfig. - public void GetInstance() - { - if (agc == null) agc = AGConnectConfig.GetInstance(); - Debug.Log($"{TAG}: GetInstance() {agc}"); - } + //getInstance() Obtains an instance of AGConnectConfig. + public void GetInstance() + { + if (agc == null) agc = AGConnectConfig.GetInstance(); + Debug.Log($"{TAG}: GetInstance() {agc}"); + } - //applyDefault(int resId) Sets a default value for a parameter. - public void ApplyDefault(Dictionary dictionary) - { - if (agc != null) agc.ApplyDefault(dictionary); - Debug.Log($"{TAG}: applyDefault with Dictionary"); - } + //applyDefault(int resId) Sets a default value for a parameter. + public void ApplyDefault(Dictionary dictionary) + { + if (agc != null) agc.ApplyDefault(dictionary); + Debug.Log($"{TAG}: applyDefault with Dictionary"); + } - //applyDefault(Map map) Sets a default value for a parameter. This path must be in Resources folder. - public void ApplyDefault(string xmlPath) - { - if (agc != null) agc.ApplyDefault(xmlPath); - Debug.Log($"{TAG}: applyDefault({xmlPath})"); - } + //applyDefault(Map map) Sets a default value for a parameter. This path must be in Resources folder. + public void ApplyDefault(string xmlPath) + { + if (agc != null) agc.ApplyDefault(xmlPath); + Debug.Log($"{TAG}: applyDefault({xmlPath})"); + } - //apply(ConfigValues values) Applies parameter values. - public void Apply(ConfigValues configValues) - { - if (agc != null) agc.Apply(configValues); - Debug.Log($"{TAG}: apply"); - } + //apply(ConfigValues values) Applies parameter values. + public void Apply(ConfigValues configValues) + { + if (agc != null) agc.Apply(configValues); + Debug.Log($"{TAG}: apply"); + } - //fetch() Fetches latest parameter values from Remote Configuration at the default - //interval of 12 hours. If the method is called within an interval, cached data is returned. - public void Fetch() - { - ITask x = agc.Fetch(); - x.AddOnSuccessListener((configValues) => + //fetch() Fetches latest parameter values from Remote Configuration at the default + //interval of 12 hours. If the method is called within an interval, cached data is returned. + public void Fetch() { - Debug.Log($"{TAG}: Fetch success."); - OnFetchSuccess?.Invoke(configValues); - }); - x.AddOnFailureListener((exception) => + ITask x = agc.Fetch(); + x.AddOnSuccessListener((configValues) => + { + Debug.Log($"{TAG}: Fetch success."); + OnFetchSuccess?.Invoke(configValues); + }); + x.AddOnFailureListener((exception) => + { + Debug.LogError($"{TAG}: Fetch failed. CauseMessage: " + exception.WrappedCauseMessage + ", ExceptionMessage: " + exception.WrappedExceptionMessage); + OnFetchFailure?.Invoke(exception); + }); + } + + //fetch(long intervalSeconds) Fetches latest parameter values from Remote Configuration at + //a customized interval. If the method is called within an interval, cached data is returned. + public void Fetch(long intervalSeconds) { - Debug.LogError($"{TAG}: Fetch failed. CauseMessage: " + exception.WrappedCauseMessage + ", ExceptionMessage: " + exception.WrappedExceptionMessage); - OnFetchFailure?.Invoke(exception); - }); - } + ITask x = agc.Fetch(intervalSeconds); + x.AddOnSuccessListener((configValues) => + { + OnFetchSuccess?.Invoke(configValues); + }); + x.AddOnFailureListener((exception) => + { + OnFetchFailure?.Invoke(exception); + }); + } - //fetch(long intervalSeconds) Fetches latest parameter values from Remote Configuration at - //a customized interval. If the method is called within an interval, cached data is returned. - public void Fetch(long intervalSeconds) - { - ITask x = agc.Fetch(intervalSeconds); - x.AddOnSuccessListener((configValues) => + //getMergedAll() Returns all values obtained after the combination of the default values and + //values in Remote Configuration. + public Dictionary GetMergedAll() { - OnFetchSuccess?.Invoke(configValues); - }); - x.AddOnFailureListener((exception) => + Dictionary dictionary = new Dictionary(); + if (agc != null) dictionary = agc.GetMergedAll(); + /*foreach(KeyValuePair kvp in values) + { + Debug.Log($"[Remote Config]: key:{kvp.Key} / value:{kvp.Value}"); + }*/ + return dictionary; + } + + //loadLastFetched() Obtains the cached data that is successfully fetched last time. + public ConfigValues LoadLastFetched() { - OnFetchFailure?.Invoke(exception); - }); - } + ConfigValues config = null; + if (agc != null) config = agc.LoadLastFetched(); + return config; + } - //getMergedAll() Returns all values obtained after the combination of the default values and - //values in Remote Configuration. - public Dictionary GetMergedAll() - { - Dictionary dictionary = new Dictionary(); - if (agc != null) dictionary = agc.GetMergedAll(); - /*foreach(KeyValuePair kvp in values) + //getSource(String key) Returns the source of a key. + public string GetSource(string key) { - Debug.Log($"[Remote Config]: key:{kvp.Key} / value:{kvp.Value}"); - }*/ - return dictionary; - } + string source = ""; + if (agc != null) source = agc.GetSource(key); + return source; + } - //loadLastFetched() Obtains the cached data that is successfully fetched last time. - public ConfigValues LoadLastFetched() - { - ConfigValues config = null; - if (agc != null) config = agc.LoadLastFetched(); - return config; - } + //clearAll() Clears all cached data, including the data fetched from Remote Configuration and + //the default values passed. + public void ClearAll() + { + if (agc != null) agc.ClearAll(); + Debug.Log($"{TAG}: clearAll()"); + } - //getSource(String key) Returns the source of a key. - public string GetSource(string key) - { - string source = ""; - if (agc != null) source = agc.GetSource(key); - return source; - } + //setDeveloperMode(boolean isDeveloperMode) Enables the developer mode, in which the number + //of times that the client obtains data from Remote Configuration is not limited, and traffic + //control is still performed over the cloud. + public void SetDeveloperMode(Boolean val) + { + if (agc != null) agc.DeveloperMode = val; + Debug.Log($"{TAG}: setDeveloperMode({val})"); + } - //clearAll() Clears all cached data, including the data fetched from Remote Configuration and - //the default values passed. - public void ClearAll() - { - if (agc != null) agc.ClearAll(); - Debug.Log($"{TAG}: clearAll()"); - } + //Returns the value for a key. + public bool GetValueAsBoolean(string paramString) => agc.GetValueAsBoolean(paramString); + public byte[] GetValueAsByteArray(string paramString) => agc.GetValueAsByteArray(paramString); + public double GetValueAsDouble(string paramString) => agc.GetValueAsDouble(paramString); + public long GetValueAsLong(string paramString) => agc.GetValueAsLong(paramString); + public string GetValueAsString(string paramString) => agc.GetValueAsString(paramString); - //setDeveloperMode(boolean isDeveloperMode) Enables the developer mode, in which the number - //of times that the client obtains data from Remote Configuration is not limited, and traffic - //control is still performed over the cloud. - public void SetDeveloperMode(Boolean val) - { - if (agc != null) agc.DeveloperMode = val; - Debug.Log($"{TAG}: setDeveloperMode({val})"); } - - //Returns the value for a key. - public bool GetValueAsBoolean(string paramString) => agc.GetValueAsBoolean(paramString); - public byte[] GetValueAsByteArray(string paramString) => agc.GetValueAsByteArray(paramString); - public double GetValueAsDouble(string paramString) => agc.GetValueAsDouble(paramString); - public long GetValueAsLong(string paramString) => agc.GetValueAsLong(paramString); - public string GetValueAsString(string paramString) => agc.GetValueAsString(paramString); - } diff --git a/Assets/Huawei/Scripts/Scan/HMSScanKitManager.cs b/Assets/Huawei/Scripts/Scan/HMSScanKitManager.cs index fcfafb53..6f936282 100644 --- a/Assets/Huawei/Scripts/Scan/HMSScanKitManager.cs +++ b/Assets/Huawei/Scripts/Scan/HMSScanKitManager.cs @@ -1,4 +1,3 @@ -using HmsPlugin; using HuaweiMobileServices.Scan; using HuaweiMobileServices.Utils; @@ -7,52 +6,55 @@ using UnityEngine; -public class HMSScanKitManager : HMSManagerSingleton +namespace HmsPlugin { - private readonly string TAG = "[HMS] HMSScanKitManager"; + public class HMSScanKitManager : HMSManagerSingleton + { + private readonly string TAG = "[HMS] HMSScanKitManager"; - public Action ScanSuccess { get; set; } - public Action ScanFailure { get; set; } + public Action ScanSuccess { get; set; } + public Action ScanFailure { get; set; } - private Dictionary permissionStates = new Dictionary(); + private Dictionary permissionStates = new Dictionary(); - private int _scanType; + private int _scanType; - private enum ScanKitPermission - { - READ_EXTERNAL_STORAGE = 1, - CAMERA = 2, - } + private enum ScanKitPermission + { + READ_EXTERNAL_STORAGE = 1, + CAMERA = 2, + } - public HMSScanKitManager() - { - HMSManagerStart.Start(OnAwake, TAG); - } + public HMSScanKitManager() + { + HMSManagerStart.Start(OnAwake, TAG); + } - private void OnAwake() - { - Debug.Log($"[{TAG}]: OnAwake() "); - } + private void OnAwake() + { + Debug.Log($"[{TAG}]: OnAwake() "); + } - #region Scan + #region Scan - public void Scan(int scanType) - { - _scanType = scanType; - StartScan(); - } + public void Scan(int scanType) + { + _scanType = scanType; + StartScan(); + } - public void StartScan() - { - Debug.Log($"[{TAG}]: StartScan "); + public void StartScan() + { + Debug.Log($"[{TAG}]: StartScan "); - var creator = new HmsScanAnalyzerOptions.Creator(); - var processedCreator = HmsScanAnalyzerOptions.Creator.SetHmsScanTypes(_scanType, creator); - var hmsScanAnalyzerOptions = processedCreator.Create(); + var creator = new HmsScanAnalyzerOptions.Creator(); + var processedCreator = HmsScanAnalyzerOptions.Creator.SetHmsScanTypes(_scanType, creator); + var hmsScanAnalyzerOptions = processedCreator.Create(); - ScanUtil.StartScan(ScanSuccess, ScanFailure, hmsScanAnalyzerOptions); - } + ScanUtil.StartScan(ScanSuccess, ScanFailure, hmsScanAnalyzerOptions); + } - #endregion + #endregion + } } diff --git a/Assets/Huawei/Scripts/Settings/HMSIAPProductListSettings.cs b/Assets/Huawei/Scripts/Settings/HMSIAPProductListSettings.cs index 42f565c7..4099570d 100644 --- a/Assets/Huawei/Scripts/Settings/HMSIAPProductListSettings.cs +++ b/Assets/Huawei/Scripts/Settings/HMSIAPProductListSettings.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using UnityEngine; namespace HmsPlugin { diff --git a/Assets/Huawei/Scripts/Utils/HMSSingleton.cs b/Assets/Huawei/Scripts/Utils/HMSSingleton.cs index 87a002f7..42a994de 100644 --- a/Assets/Huawei/Scripts/Utils/HMSSingleton.cs +++ b/Assets/Huawei/Scripts/Utils/HMSSingleton.cs @@ -1,53 +1,56 @@ -using System; +using System; using UnityEngine; -public class HMSSingleton : MonoBehaviour where T : MonoBehaviour +namespace HmsPlugin { - private static T instance; - public static T Instance + public class HMSSingleton : MonoBehaviour where T : MonoBehaviour { - get + private static T instance; + public static T Instance { + get + { + if (instance == null) + instance = FindObjectOfType(); + if (instance == null) + Debug.LogError("Singleton<" + typeof(T) + "> instance has been not found."); + return instance; + } + } + + public virtual void Awake() + { + DontDestroyOnLoad(this); if (instance == null) - instance = FindObjectOfType(); - if (instance == null) - Debug.LogError("Singleton<" + typeof(T) + "> instance has been not found."); - return instance; + instance = this as T; + else if (instance != this) + Destroy(this); } } - public virtual void Awake() + public class HMSEditorSingleton where T : new() { - DontDestroyOnLoad(this); - if (instance == null) - instance = this as T; - else if (instance != this) - Destroy(this); - } -} - -public class HMSEditorSingleton where T : new() -{ - protected static T _instance; - public static T Instance - { - get + protected static T _instance; + public static T Instance { - if (_instance == null) - _instance = new T(); + get + { + if (_instance == null) + _instance = new T(); - return _instance; + return _instance; + } } } -} - -public class HMSManagerSingleton where T : new() -{ - private static Lazy _instance = new Lazy(() => new T()); - public static T Instance + public class HMSManagerSingleton where T : new() { - get => _instance.Value; - set => _instance = new Lazy(() => value); + private static Lazy _instance = new Lazy(() => new T()); + + public static T Instance + { + get => _instance.Value; + set => _instance = new Lazy(() => value); + } } } diff --git a/Assets/Huawei/Scripts/Utils/ScriptableHelper.cs b/Assets/Huawei/Scripts/Utils/ScriptableHelper.cs index 801af24f..9bb333e8 100644 --- a/Assets/Huawei/Scripts/Utils/ScriptableHelper.cs +++ b/Assets/Huawei/Scripts/Utils/ScriptableHelper.cs @@ -1,53 +1,57 @@ -using System.IO; +using System.IO; using UnityEditor; using UnityEngine; -public static class ScriptableHelper +namespace HmsPlugin { - public static void Save(UnityEngine.Object scriptableObject) + + public static class ScriptableHelper { + public static void Save(UnityEngine.Object scriptableObject) + { #if UNITY_EDITOR - EditorUtility.SetDirty(scriptableObject); + EditorUtility.SetDirty(scriptableObject); // Note: we do not call AssetDatabase.SaveAssets() because it takes too long on bigger projects // And SetDirty should be enough to live between play mode changes & reopening Unity #endif - } - - // path should start with "Assets" - // filename should not contain file extension - public static T Load(string filename, string path) where T : ScriptableObject - { - var asset = Resources.Load(filename); + } - if (asset == null) + // path should start with "Assets" + // filename should not contain file extension + public static T Load(string filename, string path) where T : ScriptableObject { - asset = Create(filename, path); - } + var asset = Resources.Load(filename); - return asset; - } + if (asset == null) + { + asset = Create(filename, path); + } - // path should start with "Assets" - // filename should not contain file extension - public static T Create(string filename, string path) where T : ScriptableObject - { - var asset = ScriptableObject.CreateInstance(); + return asset; + } + + // path should start with "Assets" + // filename should not contain file extension + public static T Create(string filename, string path) where T : ScriptableObject + { + var asset = ScriptableObject.CreateInstance(); #if UNITY_EDITOR - Directory.CreateDirectory(path); - string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(Path.Combine(path, filename + ".asset")); + Directory.CreateDirectory(path); + string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(Path.Combine(path, filename + ".asset")); - AssetDatabase.CreateAsset(asset, assetPathAndName); + AssetDatabase.CreateAsset(asset, assetPathAndName); - // AssetDatabase.SaveAssets (); - // AssetDatabase.Refresh(); + // AssetDatabase.SaveAssets (); + // AssetDatabase.Refresh(); - return asset; + return asset; #else - Debug.LogError("Creating ScriptableObjects during runtime is not allowed!"); - return (T)null; + Debug.LogError("Creating ScriptableObjects during runtime is not allowed!"); + return (T)null; #endif + } } }