Beispiel #1
0
    protected override bool ReceiveData(byte[] byteFromServer, int dataLength)
    {
        if (byteFromServer == null || byteFromServer.Length < 1 || fileStream == null)
        {
            return(false);
        }

        try
        {
            //Write the current data to the file
            fileStream.Write(byteFromServer, 0, dataLength);
        }
        catch (Exception exception)
        {
            fileStream.Close();
            fileStream = null;
            MaxSdkLogger.UserError(string.Format("Failed to download file{0}", exception.Message));
        }

        return(true);
    }
Beispiel #2
0
        /// <summary>
        /// Adds the necessary AppLovin Quality Service dependency and maven repo lines to the provided root build.gradle file.
        /// </summary>
        /// <param name="rootGradleBuildFile">The root build.gradle file path</param>
        /// <returns><c>true</c> if the build script lines were applied correctly.</returns>
        protected bool AddQualityServiceBuildScriptLines(string rootGradleBuildFile)
        {
            var lines       = File.ReadAllLines(rootGradleBuildFile).ToList();
            var outputLines = GenerateUpdatedBuildFileLines(lines, null, true);

            // outputLines will be null if we couldn't add the build script lines.
            if (outputLines == null)
            {
                return(false);
            }

            try
            {
                File.WriteAllText(rootGradleBuildFile, string.Join("\n", outputLines.ToArray()) + "\n");
            }
            catch (Exception exception)
            {
                MaxSdkLogger.UserError("Failed to install AppLovin Quality Service plugin. Root Gradle file write failed.");
                Console.WriteLine(exception);
                return(false);
            }

            return(true);
        }
    private AppLovinIntegrationManager()
    {
        // Add asset import callbacks.
        AssetDatabase.importPackageCompleted += packageName =>
        {
            if (!IsImportingNetwork(packageName))
            {
                return;
            }

            CallImportPackageCompletedCallback(importingNetwork);
            importingNetwork = null;
        };

        AssetDatabase.importPackageCancelled += packageName =>
        {
            if (!IsImportingNetwork(packageName))
            {
                return;
            }

            MaxSdkLogger.UserDebug("Package import cancelled.");
            importingNetwork = null;
        };

        AssetDatabase.importPackageFailed += (packageName, errorMessage) =>
        {
            if (!IsImportingNetwork(packageName))
            {
                return;
            }

            MaxSdkLogger.UserError(errorMessage);
            importingNetwork = null;
        };
    }
Beispiel #4
0
        private static List <string> GenerateUpdatedBuildFileLines(List <string> lines, string apiKey, bool addBuildScriptLines)
        {
            var addPlugin = !string.IsNullOrEmpty(apiKey);
            // A sample of the template file.
            // ...
            // allprojects {
            //     repositories {**ARTIFACTORYREPOSITORY**
            //         google()
            //         jcenter()
            //         flatDir {
            //             dirs 'libs'
            //         }
            //     }
            // }
            //
            // apply plugin: 'com.android.application'
            //     **APPLY_PLUGINS**
            //
            // dependencies {
            //     implementation fileTree(dir: 'libs', include: ['*.jar'])
            //     **DEPS**}
            // ...
            var outputLines = new List <string>();
            // Check if the plugin exists, if so, update the SDK Key.
            var pluginExists = lines.Any(line => TokenAppLovinPlugin.IsMatch(line));

            if (pluginExists)
            {
                var pluginMatched         = false;
                var insideAppLovinClosure = false;
                var updatedApiKey         = false;
                var mavenRepoUpdated      = false;
                foreach (var line in lines)
                {
                    // Bintray maven repo is no longer being used. Update to s3 maven repo.
                    if (!mavenRepoUpdated && line.Contains(QualityServiceBintrayMavenRepo))
                    {
                        outputLines.Add(GetFormattedBuildScriptLine(QualityServiceMavenRepo));
                        mavenRepoUpdated = true;
                        continue;
                    }

                    if (!pluginMatched && line.Contains(QualityServicePlugin))
                    {
                        insideAppLovinClosure = true;
                        pluginMatched         = true;
                    }

                    if (insideAppLovinClosure && line.Contains("}"))
                    {
                        insideAppLovinClosure = false;
                    }

                    // Update the API key.
                    if (insideAppLovinClosure && !updatedApiKey && TokenApiKey.IsMatch(line))
                    {
                        outputLines.Add(string.Format(QualityServiceApiKey, apiKey));
                        updatedApiKey = true;
                    }
                    // Keep adding the line until we find and update the plugin.
                    else
                    {
                        outputLines.Add(line);
                    }
                }
            }
            // Plugin hasn't been added yet, add it.
            else
            {
                var buildScriptClosureDepth                = 0;
                var insideBuildScriptClosure               = false;
                var buildScriptMatched                     = false;
                var qualityServiceRepositoryAdded          = false;
                var qualityServiceDependencyClassPathAdded = false;
                var qualityServicePluginAdded              = false;
                foreach (var line in lines)
                {
                    // Add the line to the output lines.
                    outputLines.Add(line);

                    // Check if we need to add the build script lines and add them.
                    if (addBuildScriptLines)
                    {
                        if (!buildScriptMatched && line.Contains(BuildScriptMatcher))
                        {
                            buildScriptMatched       = true;
                            insideBuildScriptClosure = true;
                        }

                        // Match the parenthesis to track if we are still inside the buildscript closure.
                        if (insideBuildScriptClosure)
                        {
                            if (line.Contains("{"))
                            {
                                buildScriptClosureDepth++;
                            }

                            if (line.Contains("}"))
                            {
                                buildScriptClosureDepth--;
                            }

                            if (buildScriptClosureDepth == 0)
                            {
                                insideBuildScriptClosure = false;

                                // There may be multiple buildscript closures and we need to keep looking until we added both the repository and classpath.
                                buildScriptMatched = qualityServiceRepositoryAdded && qualityServiceDependencyClassPathAdded;
                            }
                        }

                        if (insideBuildScriptClosure)
                        {
                            // Add the build script dependency repositories.
                            if (!qualityServiceRepositoryAdded && TokenBuildScriptRepositories.IsMatch(line))
                            {
                                outputLines.Add(GetFormattedBuildScriptLine(QualityServiceMavenRepo));
                                qualityServiceRepositoryAdded = true;
                            }
                            // Add the build script dependencies.
                            else if (!qualityServiceDependencyClassPathAdded && TokenBuildScriptDependencies.IsMatch(line))
                            {
                                outputLines.Add(GetFormattedBuildScriptLine(QualityServiceDependencyClassPath));
                                qualityServiceDependencyClassPathAdded = true;
                            }
                        }
                    }

                    // Check if we need to add the plugin and add it.
                    if (addPlugin)
                    {
                        // Add the plugin.
                        if (!qualityServicePluginAdded && TokenApplicationPlugin.IsMatch(line))
                        {
                            outputLines.Add(QualityServiceApplyPlugin);
                            outputLines.AddRange(GenerateAppLovinPluginClosure(apiKey));
                            qualityServicePluginAdded = true;
                        }
                    }
                }

                if ((addBuildScriptLines && (!qualityServiceRepositoryAdded || !qualityServiceDependencyClassPathAdded)) || (addPlugin && !qualityServicePluginAdded))
                {
                    MaxSdkLogger.UserError("Failed to add AppLovin Quality Service plugin. Quality Service Plugin Added?: " + qualityServicePluginAdded + ", Quality Service Repo added?: " + qualityServiceRepositoryAdded + ", Quality Service dependency added?: " + qualityServiceDependencyClassPathAdded);
                    return(null);
                }
            }

            return(outputLines);
        }
        [PostProcessBuild(int.MaxValue)] // We want to run Quality Service script last.
        public static void OnPostProcessBuild(BuildTarget buildTarget, string buildPath)
        {
            if (!AppLovinSettings.Instance.QualityServiceEnabled)
            {
                return;
            }

            var sdkKey = AppLovinSettings.Instance.SdkKey;

            if (string.IsNullOrEmpty(sdkKey))
            {
                MaxSdkLogger.UserError("Failed to install AppLovin Quality Service plugin. SDK Key is empty. Please enter the AppLovin SDK Key in the Integration Manager.");
                return;
            }

            var outputFilePath = Path.Combine(buildPath, OutputFileName);

            // Check if Quality Service is already installed.
            if (File.Exists(outputFilePath) && Directory.Exists(Path.Combine(buildPath, "AppLovinQualityService")))
            {
                // TODO: Check if there is a way to validate if the SDK key matches the script. Else the pub can't use append when/if they change the SDK Key.
                return;
            }

            // Download the ruby script needed to install Quality Service
#if UNITY_2017_2_OR_NEWER
            var downloadHandler = new DownloadHandlerFile(outputFilePath);
#else
            var downloadHandler = new AppLovinDownloadHandler(path);
#endif
            var postJson      = string.Format("{{\"sdk_key\" : \"{0}\"}}", sdkKey);
            var bodyRaw       = Encoding.UTF8.GetBytes(postJson);
            var uploadHandler = new UploadHandlerRaw(bodyRaw);
            uploadHandler.contentType = "application/json";

            var unityWebRequest = new UnityWebRequest("https://api2.safedk.com/v1/build/ios_setup2")
            {
                method          = UnityWebRequest.kHttpVerbPOST,
                downloadHandler = downloadHandler,
                uploadHandler   = uploadHandler
            };

#if UNITY_2017_2_OR_NEWER
            var operation = unityWebRequest.SendWebRequest();
#else
            var operation = webRequest.Send();
#endif

            // Wait for the download to complete or the request to timeout.
            while (!operation.isDone)
            {
            }

#if UNITY_2020_1_OR_NEWER
            if (unityWebRequest.result != UnityWebRequest.Result.Success)
#elif UNITY_2017_2_OR_NEWER
            if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
#else
            if (webRequest.isError)
#endif
            {
                MaxSdkLogger.UserError("AppLovin Quality Service installation failed. Failed to download script with error: " + unityWebRequest.error);
                return;
            }

            // Check if Ruby is installed
            var rubyVersion = AppLovinCommandLine.Run("ruby", "--version", buildPath);
            if (rubyVersion.ExitCode != 0)
            {
                MaxSdkLogger.UserError("AppLovin Quality Service installation requires Ruby. Please install Ruby, export it to your system PATH and re-export the project.");
                return;
            }

            // Ruby is installed, run `ruby AppLovinQualityServiceSetup.rb`
            var result = AppLovinCommandLine.Run("ruby", OutputFileName, buildPath);

            // Check if we have an error.
            if (result.ExitCode != 0)
            {
                MaxSdkLogger.UserError("Failed to set up AppLovin Quality Service");
            }

            MaxSdkLogger.UserDebug(result.Message);
        }
        static MaxInitialize()
        {
#if UNITY_IOS
            // Check that the publisher is targeting iOS 9.0+
            if (!PlayerSettings.iOS.targetOSVersionString.StartsWith("9.") && !PlayerSettings.iOS.targetOSVersionString.StartsWith("1"))
            {
                MaxSdkLogger.UserError("Detected iOS project version less than iOS 9 - The AppLovin MAX SDK WILL NOT WORK ON < iOS9!!!");
            }
#endif

            var pluginParentDir          = AppLovinIntegrationManager.PluginParentDirectory;
            var isPluginOutsideAssetsDir = AppLovinIntegrationManager.IsPluginOutsideAssetsDirectory;
            var changesMade = AppLovinIntegrationManager.MovePluginFilesIfNeeded(pluginParentDir, isPluginOutsideAssetsDir);
            if (isPluginOutsideAssetsDir)
            {
                // If the plugin is not under the assets folder, delete the MaxSdk/Mediation folder in the plugin, so that the adapters are not imported at that location and imported to the default location.
                var mediationDir = Path.Combine(pluginParentDir, "MaxSdk/Mediation");
                if (Directory.Exists(mediationDir))
                {
                    FileUtil.DeleteFileOrDirectory(mediationDir);
                    FileUtil.DeleteFileOrDirectory(mediationDir + ".meta");
                    changesMade = true;
                }
            }

            AppLovinIntegrationManager.AddLabelsToAssetsIfNeeded(pluginParentDir, isPluginOutsideAssetsDir);

            // Check if we have legacy adapter CHANGELOGs.
            foreach (var network in Networks)
            {
                var mediationAdapterDir = Path.Combine(pluginParentDir, "MaxSdk/Mediation/" + network);

                // If new directory exists
                if (CheckExistence(mediationAdapterDir))
                {
                    var androidChangelogFile = Path.Combine(mediationAdapterDir, AndroidChangelog);
                    if (CheckExistence(androidChangelogFile))
                    {
                        FileUtil.DeleteFileOrDirectory(androidChangelogFile);
                        changesMade = true;
                    }

                    var iosChangelogFile = Path.Combine(mediationAdapterDir, IosChangelog);
                    if (CheckExistence(iosChangelogFile))
                    {
                        FileUtil.DeleteFileOrDirectory(iosChangelogFile);
                        changesMade = true;
                    }
                }
            }

            // Check if any obsolete networks are installed
            foreach (var obsoleteNetwork in ObsoleteNetworks)
            {
                var networkDir = Path.Combine(pluginParentDir, "MaxSdk/Mediation/" + obsoleteNetwork);
                if (CheckExistence(networkDir))
                {
                    MaxSdkLogger.UserDebug("Deleting obsolete network " + obsoleteNetwork + " from path " + networkDir + "...");
                    FileUtil.DeleteFileOrDirectory(networkDir);
                    changesMade = true;
                }
            }

            // Refresh UI
            if (changesMade)
            {
                AssetDatabase.Refresh();
                MaxSdkLogger.UserDebug("AppLovin MAX Migration completed");
            }

            AppLovinAutoUpdater.Update();
        }