private static List <string> ReadGradleFile(string prefix, string path) { try { if (File.Exists(path)) { return(new List <string>(File.ReadAllLines(path))); } } catch (Exception e) { Debug.LogException(e); } var message = "A successful build requires do modifications to " + prefix + " template. " + "But the template is not activated now."; Utils.DialogOrCancelBuild(message + "\nClick Сontinue to activate.", BuildTarget.NoTarget); try { if (TryEnableGradleTemplate(path) && File.Exists(path)) { return(new List <string>(File.ReadAllLines(path))); } } catch (Exception e) { Debug.LogException(e); } Utils.StopBuildWithMessage(message, BuildTarget.NoTarget); return(null); }
protected override void OnHeaderGUI() { EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); GUILayout.Label("CleverAdsSolutions", HelpStyles.largeTitleStyle); GUILayout.Label(platform.ToString(), HelpStyles.largeTitleStyle, GUILayout.ExpandWidth(false)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); Utils.OnHeaderGUI(Utils.gitUnityRepo, allowedPackageUpdate, MobileAds.wrapperVersion, ref newCASVersion); }
private static void ConfigureIOS() { #if (UNITY_IOS || CASDeveloper) && !UNITY_2019_3_OR_NEWER if (!PlayerSettings.iOS.targetOSVersionString.StartsWith("1")) { Utils.DialogOrCancelBuild("CAS required a higher minimum deployment target. Set iOS 10.0 and continue?", BuildTarget.NoTarget); PlayerSettings.iOS.targetOSVersionString = "10.0"; } #endif }
public void DisableDependencies(BuildTarget platform, DependencyManager mediation) { var destination = Utils.GetDependencyPath(name, platform); if (File.Exists(destination)) { AssetDatabase.DeleteAsset(destination); installedVersion = ""; mediation.Init(platform); } }
public static DependencyManager Create(BuildTarget platform, Audience audience, bool deepInit) { string listPath = Utils.GetTemplatePath("CAS" + platform.ToString() + "Mediation.list"); if (listPath == null) { return(null); } var mediation = JsonUtility.FromJson <DependencyManager>(File.ReadAllText(listPath)); mediation.Init(platform, deepInit); mediation.SetAudience(audience); return(mediation); }
internal void Init(DependencyManager mediation, BuildTarget platform, bool updateContaines) { var path = Utils.GetDependencyPath(name, platform); if (File.Exists(path)) { var dependency = File.ReadAllText(path); const string line = "version=\""; var beginIndex = dependency.IndexOf(line, 45); if (beginIndex > 0) { beginIndex += line.Length; installedVersion = dependency.Substring(beginIndex, dependency.IndexOf('\"', beginIndex) - beginIndex); try { //var currVer = new Version( installedVersion ); //var targetVer = new Version( version ); //isNewer = currVer < targetVer; isNewer = installedVersion != version; } catch { isNewer = true; } mediation.installedAny = true; } if (updateContaines) { for (int i = 0; i < contains.Length; i++) { var item = mediation.Find(contains[i]); if (item != null) { item.locked = true; } } var requiredItem = mediation.Find(require); if (requiredItem != null) { requiredItem.isRequired = true; } } } }
private void OnEnable() { SetSettingsPlatform(); InitMainProperties(serializedObject); InitEditorSettingsProperties(); allowedPackageUpdate = Utils.IsPackageExist(Utils.packageName); dependencyManager = DependencyManager.Create(platform, ( Audience )audienceTaggedProp.enumValueIndex, true); HandleDeprecatedComponents(); InitEDM4U(); InitEnvironmentDetails(); EditorApplication.delayCall += () => { newCASVersion = Utils.GetNewVersionOrNull(Utils.gitUnityRepo, MobileAds.wrapperVersion, false); }; }
private void InitEDM4U() { edmVersion = Utils.GetEDM4UVersion(platform); if (edmVersion != null) { edmRequiredNewer = edmVersion < Utils.minEDM4UVersion; } try { if (platform == BuildTarget.iOS) { edmIOSStaticLinkProp = Type.GetType("Google.IOSResolver, Google.IOSResolver", true) .GetProperty("PodfileStaticLinkFrameworks", BindingFlags.Public | BindingFlags.Static); } } catch { edmIOSStaticLinkProp = null; } }
private void OnUserTrackingDesctiptionGUI() { if (platform != BuildTarget.iOS) { return; } HelpStyles.BeginBoxScope(); var enabled = userTrackingUsageDescriptionProp.arraySize > 0; EditorGUILayout.BeginHorizontal(); if (enabled != EditorGUILayout.ToggleLeft("Set User Tracking Usage description in Info.plist", enabled)) { enabled = !enabled; if (enabled) { var defDescr = Utils.DefaultUserTrackingUsageDescription(); userTrackingUsageDescriptionProp.arraySize = defDescr.Length; for (int i = 0; i < defDescr.Length; i++) { var pair = userTrackingUsageDescriptionProp.GetArrayElementAtIndex(i); pair.Next(true); pair.stringValue = defDescr[i].key; pair.Next(false); pair.stringValue = defDescr[i].value; } } else { userTrackingUsageDescriptionProp.ClearArray(); } } HelpStyles.HelpButton(Utils.gitUnityRepoURL + "/wiki/App-Tracking-Transparency"); EditorGUILayout.EndHorizontal(); if (enabled) { userTrackingList.DoLayoutList(); } HelpStyles.EndBoxScope(); }
private void HandleDeprecatedComponents() { deprecatedAssets = new string[] { Utils.GetDeprecateDependencyName(Utils.generalDeprecateDependency, platform), Utils.GetDeprecateDependencyName(Utils.teenDeprecateDependency, platform), Utils.GetDeprecateDependencyName(Utils.promoDeprecateDependency, platform), Utils.GetDependencyName("Additional", platform) }; for (int i = 0; i < deprecatedAssets.Length; i++) { if (deprecateDependenciesExist |= AssetDatabase.FindAssets(deprecatedAssets[i]).Length > 0) { break; } } // Remove deprecated CAS settings raw data if (File.Exists(Utils.androidResSettingsPath + ".json")) { AssetDatabase.MoveAssetToTrash(Utils.androidResSettingsPath + ".json"); } }
private static void ConfigureAndroid(CASInitSettings settings, CASEditorSettings editorSettings, string admobAppId) { #if UNITY_ANDROID || CASDeveloper EditorUtility.DisplayProgressBar(casTitle, "Validate CAS Android Build Settings", 0.8f); const string deprecatedPluginPath = "Assets/Plugins/CAS"; if (AssetDatabase.IsValidFolder(deprecatedPluginPath)) { AssetDatabase.DeleteAsset(deprecatedPluginPath); Debug.Log("Removed deprecated plugin: " + deprecatedPluginPath); } HashSet <string> promoAlias = new HashSet <string>(); if (editorSettings.generateAndroidQuerriesForPromo) { for (int i = 0; i < settings.managersCount; i++) { Utils.GetCrossPromoAlias(BuildTarget.Android, settings.GetManagerId(i), promoAlias); } } UpdateAndroidPluginManifest(admobAppId, promoAlias, editorSettings); CASPreprocessGradle.Configure(editorSettings); #if !UNITY_2021_2_OR_NEWER // 19 - AndroidSdkVersions.AndroidApiLevel19 // Deprecated in Unity 2021.2 if (PlayerSettings.Android.minSdkVersion < ( AndroidSdkVersions )19) { Utils.DialogOrCancelBuild("CAS required a higher minimum SDK API level. Set SDK level 19 (KitKat) and continue?", BuildTarget.NoTarget); PlayerSettings.Android.minSdkVersion = ( AndroidSdkVersions )19; } #endif #endif }
public void ActivateDependencies(BuildTarget platform, DependencyManager mediation) { if (dependencies.Length == 0 && depsSDK.Count == 0) { Debug.LogError(Utils.logTag + name + " have no dependencies. Please try reimport CAS package."); return; } if (locked) { return; } string depTagName = platform == BuildTarget.Android ? "androidPackage" : "iosPod"; var destination = Utils.GetDependencyPathOrDefault(name, platform); EditorUtility.DisplayProgressBar("Create dependency", destination, 0.2f); try { var builder = new StringBuilder(); builder.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>") .AppendLine("<dependencies>") .Append(" <").Append(depTagName).Append("s>").AppendLine(); for (int i = 0; i < dependencies.Length; i++) { AppendDependency(mediation, new SDK(dependencies[i], version), platform, builder); } // EDM4U have a bug. // Dependencies that will be added For All Targets must be at the end of the list of dependencies. // Otherwise, those dependencies that should not be for all targets will be tagged for all targets. AppendSDK(platform, mediation, builder, false); AppendSDK(platform, mediation, builder, true); builder.Append(" </").Append(depTagName).Append("s>").AppendLine() .AppendLine("</dependencies>"); var replace = File.Exists(destination); if (!replace) { var destDir = Path.GetDirectoryName(destination); if (!Directory.Exists(destDir)) { Directory.CreateDirectory(destDir); } } File.WriteAllText(destination, builder.ToString()); if (!replace) { AssetDatabase.ImportAsset(destination); } Init(mediation, platform, true); } finally { EditorUtility.ClearProgressBar(); } var requireItem = mediation.Find(require); if (requireItem != null) { requireItem.isRequired = true; if (!requireItem.IsInstalled()) { requireItem.ActivateDependencies(platform, mediation); } } }
private static string UpdateRemoteSettingsAndGetAppId(CASInitSettings settings, BuildTarget platform, DependencyManager deps) { string appId = null; string updateSettingsError = ""; for (int i = 0; i < settings.managersCount; i++) { var managerId = settings.GetManagerId(i); if (managerId == null || managerId.Length < 5) { continue; } try { string newAppId = DownloadRemoteSettings(managerId, platform, settings, deps); if (!string.IsNullOrEmpty(appId) || string.IsNullOrEmpty(newAppId)) { continue; } if (newAppId.Contains('~')) { appId = newAppId; continue; } if (i == 0) { Debug.LogError(Utils.logTag + "CAS id [" + managerId + "] has an error in server settings. Please contact support!"); } } catch (Exception e) { updateSettingsError = e.Message; } } if (!string.IsNullOrEmpty(appId) || settings.IsTestAdMode()) { return(appId); } const string title = "Update CAS remote settings"; int dialogResponse = 0; var targetId = settings.GetManagerId(0); var message = updateSettingsError + "\nPlease try using a real identifier in the first place else contact support." + "\n- Warning! -" + "\n1. Continue build the app for release with current settings can reduce monetization revenue." + "\n2. When build to testing your app, make sure you use Test Ads mode rather than live ads. " + "Failure to do so can lead to suspension of your account."; Debug.LogError(Utils.logTag + message); if (!Application.isBatchMode) { dialogResponse = EditorUtility.DisplayDialogComplex(title, message, "Continue", "Cancel Build", "Select settings file"); } if (dialogResponse == 0) { var cachePath = Utils.GetNativeSettingsPath(platform, targetId); if (File.Exists(cachePath)) { return(Utils.GetAdmobAppIdFromJson(File.ReadAllText(cachePath))); } return(null); } if (dialogResponse == 1) { Utils.StopBuildWithMessage("Build canceled", BuildTarget.NoTarget); return(null); } return(Utils.SelectSettingsFileAndGetAppId(targetId, platform)); }
private void OnEDMAreaGUI() { if (edmVersion == null) { HelpStyles.BeginBoxScope(); EditorGUILayout.HelpBox("In order to properly include third party dependencies in your project, " + "an External Dependency Manager is required.", MessageType.Error); EditorGUILayout.BeginHorizontal(); GUILayout.Label("1. Download latest EDM4U.unitypackage", GUILayout.ExpandWidth(false)); if (GUILayout.Button("here", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { Application.OpenURL(Utils.latestEMD4uURL); } EditorGUILayout.EndHorizontal(); GUILayout.Label("2. Import the EDM4U.unitypackage into your project."); HelpStyles.EndBoxScope(); return; } if (edmRequiredNewer) { if (HelpStyles.WarningWithButton("To properly include third-party dependencies in your project, " + "you need an External Dependency Manager version " + Utils.minEDM4UVersion + " or later.", "Download")) { Application.OpenURL(Utils.latestEMD4uURL); } } if (platform == BuildTarget.Android) { #if UNITY_2019_3_OR_NEWER OnGradleTemplateDisabledGUI("Base Gradle", Utils.projectGradlePath); OnGradleTemplateDisabledGUI("Launcher Gradle", Utils.launcherGradlePath); OnGradleTemplateDisabledGUI("Gradle Properties", Utils.propertiesGradlePath); #else OnGradleTemplateDisabledGUI("Gradle", Utils.mainGradlePath); #endif if (HelpStyles.WarningWithButton("Changing dependencies will change the project settings. " + "Please use Android Resolver after the change complete.", "Resolve", MessageType.Info)) { if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android) { var succses = Utils.TryResolveAndroidDependencies(); EditorUtility.DisplayDialog("Android Dependencies", succses ? "Resolution Succeeded" : "Resolution Failed. See the log for details.", "OK"); } else { EditorUtility.DisplayDialog("Android Dependencies", "Android resolver not enabled. Unity Android platform target must be selected.", "OK"); } } return; } if (platform == BuildTarget.iOS) { if (edmIOSStaticLinkProp != null && !( bool )edmIOSStaticLinkProp.GetValue(null, null)) { OnWarningGUI("Link frameworks statically disabled", "Please enable 'Add use_frameworks!' and 'Link frameworks statically' found under " + "'Assets -> External Dependency Manager -> iOS Resolver -> Settings' menu.\n" + "Failing to do this step may result in undefined behavior of the plugin and doubled import of frameworks.", MessageType.Warning); } if (PlayerSettings.muteOtherAudioSources) { OnWarningGUI("Mute Other AudioSources enabled in PlayerSettings", "Known issue with muted all sounds in Unity Game after closing interstitial ads. " + "We recommend not using 'Mute Other AudioSources'.", MessageType.Warning); } } }
internal static string DownloadRemoteSettings(string managerID, BuildTarget platform, CASInitSettings settings, DependencyManager deps) { const string title = "Update CAS remote settings"; var editorSettings = CASEditorSettings.Load(); #region Create request URL #region Hash var managerIdBytes = new UTF8Encoding().GetBytes(managerID); var suffix = new byte[] { 48, 77, 101, 68, 105, 65, 116, 73, 111, 78, 104, 65, 115, 72 }; if (platform == BuildTarget.iOS) { suffix[0] = 49; } var sourceBytes = new byte[managerID.Length + suffix.Length]; Array.Copy(managerIdBytes, 0, sourceBytes, 0, managerIdBytes.Length); Array.Copy(suffix, 0, sourceBytes, managerIdBytes.Length, suffix.Length); var hashBytes = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(sourceBytes); StringBuilder hashBuilder = new StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) { hashBuilder.Append(Convert.ToString(hashBytes[i], 16).PadLeft(2, '0')); } var hash = hashBuilder.ToString().PadLeft(32, '0'); #endregion var urlBuilder = new StringBuilder("https://psvpromo.psvgamestudio.com/Scr/cas.php?platform=") .Append(platform == BuildTarget.Android ? 0 : 1) .Append("&bundle=").Append(UnityWebRequest.EscapeURL(managerID)) .Append("&hash=").Append(hash) .Append("&lang=").Append(SystemLanguage.English) .Append("&appDev=2") .Append("&appV=").Append(PlayerSettings.bundleVersion) .Append("&coppa=").Append(( int )settings.defaultAudienceTagged) .Append("&adTypes=").Append(( int )settings.allowedAdFlags) .Append("&nets=").Append(DependencyManager.GetActiveMediationPattern(deps)) .Append("&orient=").Append(Utils.GetOrientationId()) .Append("&framework=Unity_").Append(Application.unityVersion); if (deps != null) { var buildCode = deps.GetInstalledBuildCode(); if (buildCode > 0) { urlBuilder.Append("&sdk=").Append(buildCode); } } if (string.IsNullOrEmpty(editorSettings.mostPopularCountryOfUsers)) { urlBuilder.Append("&country=").Append("US"); } else { urlBuilder.Append("&country=").Append(editorSettings.mostPopularCountryOfUsers); } if (platform == BuildTarget.Android) { urlBuilder.Append("&appVC=").Append(PlayerSettings.Android.bundleVersionCode); } #endregion using (var loader = UnityWebRequest.Get(urlBuilder.ToString())) { try { loader.SendWebRequest(); while (!loader.isDone) { if (EditorUtility.DisplayCancelableProgressBar(title, managerID, Mathf.Repeat(( float )EditorApplication.timeSinceStartup * 0.2f, 1.0f))) { loader.Dispose(); throw new Exception("Update CAS Settings canceled"); } } if (string.IsNullOrEmpty(loader.error)) { var content = loader.downloadHandler.text.Trim(); if (string.IsNullOrEmpty(content)) { throw new Exception("ManagerID [" + managerID + "] is not registered in CAS."); } EditorUtility.DisplayProgressBar(title, "Write CAS settings", 0.7f); var data = JsonUtility.FromJson <AdmobAppIdData>(content); Utils.WriteToFile(content, Utils.GetNativeSettingsPath(platform, managerID)); return(data.admob_app_id); } throw new Exception("Server response " + loader.responseCode + ": " + loader.error); } finally { EditorUtility.ClearProgressBar(); } } }
private static void StopBuildIDNotFound(BuildTarget target) { Utils.StopBuildWithMessage("Settings not found manager ids for " + target.ToString() + " platform. For a successful build, you need to specify at least one ID" + " that you use in the project. To test integration, you can use test mode with 'demo' manager id.", target); }
public static void ConfigureProject(BuildTarget target, CASEditorSettings editorSettings) { if (target != BuildTarget.Android && target != BuildTarget.iOS) { return; } var settings = Utils.GetSettingsAsset(target, false); if (!settings) { Utils.StopBuildWithMessage("Settings asset not found. Please use menu Assets > CleverAdsSolutions > Settings " + "to create and set settings for build.", target); } var deps = DependencyManager.Create(target, Audience.Mixed, true); if (!Application.isBatchMode) { var newCASVersion = Utils.GetNewVersionOrNull(Utils.gitUnityRepo, MobileAds.wrapperVersion, false); if (newCASVersion != null) { Utils.DialogOrCancelBuild("There is a new version " + newCASVersion + " of the CAS Unity available for update.", target); } if (deps != null) { if (!deps.installedAny) { Utils.StopBuildWithMessage("Dependencies of native SDK were not found. " + "Please use 'Assets > CleverAdsSolutions > Settings' menu to integrate solutions or any SDK separately.", target); } if (deps.IsNewerVersionFound()) { Utils.DialogOrCancelBuild("There is a new versions of the native dependencies available for update." + "Please use 'Assets > CleverAdsSolutions >Settings' menu to update.", target); } } } if (settings.managersCount == 0 || string.IsNullOrEmpty(settings.GetManagerId(0))) { StopBuildIDNotFound(target); } string admobAppId = UpdateRemoteSettingsAndGetAppId(settings, target, deps); if (target == BuildTarget.Android) { ConfigureAndroid(settings, editorSettings, admobAppId); } else if (target == BuildTarget.iOS) { ConfigureIOS(); } #pragma warning disable CS0618 // Type or member is obsolete // Use directrly property to avoid Debug build if (settings.testAdMode && !EditorUserBuildSettings.development) { Debug.LogWarning(Utils.logTag + "Test Ads Mode enabled! Make sure the build is for testing purposes only!\n" + "Use 'Assets > CleverAdsSolutions > Settings' menu to disable Test Ad Mode."); } else { Debug.Log(Utils.logTag + "Project configuration completed"); } #pragma warning restore CS0618 // Type or member is obsolete }
internal static void Configure(CASEditorSettings settings) { bool baseGradleChanged = false; List <string> baseGradle = null; List <string> launcherGradle = null; #if UNITY_2019_3_OR_NEWER const string baseGradlePath = Utils.projectGradlePath; const string launcherGradlePath = Utils.launcherGradlePath; baseGradle = ReadGradleFile("Base Gradle", baseGradlePath); if (settings.multiDexEnabled || settings.exoPlayerIncluded) { launcherGradle = ReadGradleFile("Launcher Gradle", launcherGradlePath); } #else const string baseGradlePath = Utils.mainGradlePath; const string launcherGradlePath = Utils.mainGradlePath; baseGradle = ReadGradleFile("Gradle", baseGradlePath); launcherGradle = baseGradle; #endif if (settings.updateGradlePluginVersion && UpdateGradlePluginVersion(baseGradle, baseGradlePath)) { baseGradleChanged = true; } #if ReplaceJCenterToMavenCentral if (UpdateBaseGradleRepositories(baseGradle, baseGradlePath)) { baseGradleChanged = true; } #endif // Enabled by default Dexing artifact transform causes issues for ExoPlayer with Gradle plugin 3.5.0+ var dexingArtifactProp = new GradleProperty( "android.enableDexingArtifactTransform", "false", !settings.exoPlayerIncluded); GradleProperty[] gradleProps = null; if (Utils.GetAndroidResolverSetting <bool>("UseJetifier")) { gradleProps = new[] { dexingArtifactProp }; } else { gradleProps = new[] { dexingArtifactProp, new GradleProperty("android.useAndroidX", "true"), new GradleProperty("android.enableJetifier", "true") }; } #if UNITY_2019_3_OR_NEWER List <string> propsFile = ReadGradleFile("Gradle Properties", Utils.propertiesGradlePath); if (UpdateGradlePropertiesFile(propsFile, gradleProps)) { File.WriteAllLines(Utils.propertiesGradlePath, propsFile.ToArray()); } #else // Unity below version 2019.3 does not have a Gradle Properties file // and changes are applied to the base Gradle file. if (UpdateGradlePropertiesInMainFile(baseGradle, gradleProps, baseGradlePath)) { baseGradleChanged = true; } if (FixGradleCompatibilityUnity2018(baseGradle, baseGradlePath)) { baseGradleChanged = true; } #endif if (launcherGradle != null) { if (UpdateLauncherGradleFile(launcherGradle, settings, launcherGradlePath)) { #if UNITY_2019_3_OR_NEWER File.WriteAllLines(launcherGradlePath, launcherGradle.ToArray()); AssetDatabase.ImportAsset(launcherGradlePath); #else // Unity below version 2019.3 does not have a Gradle Launcher file // and changes are applied to the base Gradle file. baseGradleChanged = true; #endif } } if (baseGradleChanged) { File.WriteAllLines(baseGradlePath, baseGradle.ToArray()); AssetDatabase.ImportAsset(baseGradlePath); } }