using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using UnityEditor; using UnityEditor.AddressableAssets; using UnityEngine; public class ChannelBuildTool { private const string ChannelConfigRoot = "../ChannelConfigs/Android"; private const string TysdkPlugins = "Packages/tysdk/Plugins/Android"; private const string TysdkFiles = "Packages/tysdk/Files"; private const string AssetsPlugins = "Assets/Plugins/Android"; private const string AddressablesContentState = "AddressableAssetsData/Android/addressables_content_state.bin"; private const string AndroidAddressablesContentState = "Assets/AddressableAssetsData/Android/addressables_content_state.bin"; private const string DefaultProductName = "Fishing Travel"; private const string EnjoyPayProductName = "Fishing Travel: Hook & Explore"; private const string ChannelManifestLib = "channel_manifest_lib"; private const string ChannelGradle = "channel_gradle"; private const string ChannelMetaName = "com.arkgame.ft.channel"; private const string EmptyManifest = "\n\n"; private static readonly XNamespace AndroidNamespace = "http://schemas.android.com/apk/res/android"; private static readonly XNamespace ToolsNamespace = "http://schemas.android.com/tools"; // ==================== Channel Switching ==================== public static void SwitchChannel(string channel) { channel = NormalizeChannelName(channel); var cfgDir = Path.Combine(ChannelConfigRoot, channel.ToLowerInvariant()); Debug.Log($"[ChannelSwitch] Switching to {channel}..."); CleanChannelManifestLibBuildArtifacts(); // 1. Sync root Android config files SyncRootAndroidConfigFiles(channel, cfgDir); // 2. Sync channel SDK adapter Java files to tysdk package SyncChannelAdapterFiles(cfgDir); // 3. Sync google-services.json SyncGoogleServices(cfgDir); // 4. Sync channel plugin files (.aar, .jar, etc.) to tysdk package SyncChannelPluginFiles(cfgDir); // 5. Set Bundle Identifier per channel var bundleId = GetBundleId(channel); PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android, bundleId); Debug.Log($"[ChannelSwitch] Bundle Identifier -> {bundleId}"); var productName = channel == "EnjoyPay" ? EnjoyPayProductName : DefaultProductName; PlayerSettings.productName = productName; Debug.Log($"[ChannelSwitch] Product Name -> {productName}"); // 6. Set runtime channel tysdk.ChannelConfig.SetChannel(channel); // 7. Set Addressables profile and optional channel content state SetAddressablesProfile(channel); SyncAddressablesContentState(channel, cfgDir); AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); Debug.Log($"[ChannelSwitch] Done. Channel: {channel}"); } // ==================== Menu ==================== [MenuItem("Tools/Channel/Switch Channel/GooglePlay", false, 10000)] public static void Switch_GooglePlay() => SwitchChannelTo("GooglePlay"); [MenuItem("Tools/Channel/Switch Channel/Flexion", false, 10001)] public static void Switch_Flexion() => SwitchChannelTo("Flexion"); [MenuItem("Tools/Channel/Switch Channel/Rustore", false, 10002)] public static void Switch_Rustore() => SwitchChannelTo("Rustore"); [MenuItem("Tools/Channel/Switch Channel/EnjoyPay", false, 10003)] public static void Switch_EnjoyPay() => SwitchChannelTo("EnjoyPay"); private static void SwitchChannelTo(string channel) { RestoreChannelWorkspace(skipOnCi: true); SwitchChannel(channel); } // ==================== Build ==================== private static void BuildAndroidForChannel(string channel, bool debug) { try { RestoreChannelWorkspace(skipOnCi: true); CleanChannelManifestLibBuildArtifacts(); SwitchChannel(channel); var fileName = debug ? $"tysdkTest_{channel}_debug.apk" : $"tysdkTest_{channel}.apk"; var outPath = $"../Bin/{fileName}"; var buildOptions = debug ? BuildOptions.Development | BuildOptions.AllowDebugging | BuildOptions.WaitForPlayerConnection : BuildOptions.None; var buildPlayerOptions = new BuildPlayerOptions { scenes = EditorBuildSettings.scenes.Select(x => x.path).ToArray(), locationPathName = outPath, target = BuildTarget.Android, options = buildOptions, }; Debug.Log($"[ChannelBuild] Building {channel} -> {outPath}"); var buildReport = BuildPipeline.BuildPlayer(buildPlayerOptions); if (buildReport?.summary.result == UnityEditor.Build.Reporting.BuildResult.Succeeded) { Debug.Log($"[ChannelBuild] Success: {Path.GetFullPath(outPath)}"); AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); } else { Debug.LogError($"[ChannelBuild] Failed: {buildReport?.summary}"); } } finally { RestoreChannelWorkspace(skipOnCi: true); AssetDatabase.SaveAssets(); } } [MenuItem("Tools/Channel/Build Android (Channel)/GooglePlay", false, 10100)] public static void Build_GooglePlay() => BuildAndroidForChannel("GooglePlay", false); [MenuItem("Tools/Channel/Build Android (Channel)/GooglePlay Debug", false, 10101)] public static void Build_GooglePlay_Debug() => BuildAndroidForChannel("GooglePlay", true); [MenuItem("Tools/Channel/Build Android (Channel)/Rustore", false, 10102)] public static void Build_Rustore() => BuildAndroidForChannel("Rustore", false); [MenuItem("Tools/Channel/Build Android (Channel)/Rustore Debug", false, 10103)] public static void Build_Rustore_Debug() => BuildAndroidForChannel("Rustore", true); [MenuItem("Tools/Channel/Build Android (Channel)/Flexion", false, 10104)] public static void Build_Flexion() => BuildAndroidForChannel("Flexion", false); [MenuItem("Tools/Channel/Build Android (Channel)/Flexion Debug", false, 10105)] public static void Build_Flexion_Debug() => BuildAndroidForChannel("Flexion", true); [MenuItem("Tools/Channel/Build Android (Channel)/EnjoyPay", false, 10106)] public static void Build_EnjoyPay() => BuildAndroidForChannel("EnjoyPay", false); [MenuItem("Tools/Channel/Build Android (Channel)/EnjoyPay Debug", false, 10107)] public static void Build_EnjoyPay_Debug() => BuildAndroidForChannel("EnjoyPay", true); [MenuItem("Tools/Channel/Restore Workspace (Git Checkout)", false, 10200)] public static void RestoreChannelWorkspaceWithGitCheckoutMenu() { RestoreChannelWorkspace(skipOnCi: false); } private static string NormalizeChannelName(string channel) { if (string.IsNullOrEmpty(channel)) return channel; switch (channel.Trim().ToLowerInvariant()) { case "googleplay": return "GooglePlay"; case "flexion": return "Flexion"; case "enjoypay": return "EnjoyPay"; case "rustore": return "Rustore"; default: return channel.Trim(); } } private static string GetBundleId(string channel) { return channel switch { "Flexion" => "com.arkgame.ft.flexion", "EnjoyPay" => "com.arkgame.ft.ep", _ => "com.arkgame.ft" }; } private static void RestoreChannelWorkspace(bool skipOnCi) { if (skipOnCi && IsCiBuild()) { Debug.Log("[ChannelSwitch] Skip git checkout restore on CI."); return; } RunCommand("git", "checkout -- ."); RunCommand("git", "clean -fd -- ."); AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); Debug.Log("[ChannelSwitch] Workspace restored from git index."); } private static bool IsCiBuild() { return !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("JENKINS_URL")) || !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("JENKINS_HOME")) || !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("BUILD_NUMBER")); } private static void RunCommand(string fileName, string arguments) { var startInfo = new System.Diagnostics.ProcessStartInfo { FileName = fileName, Arguments = arguments, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true }; using (var process = System.Diagnostics.Process.Start(startInfo)) { var output = process.StandardOutput.ReadToEnd(); var error = process.StandardError.ReadToEnd(); process.WaitForExit(); if (process.ExitCode != 0) { throw new System.InvalidOperationException($"{fileName} {arguments} failed.\n{output}\n{error}"); } } } private static void SyncRootAndroidConfigFiles(string channel, string cfgDir) { SyncChannelGradleFiles(channel, cfgDir); SetMainManifestChannel(channel); SyncChannelManifestLib(channel, cfgDir); } private static void SyncChannelAdapterFiles(string cfgDir) { // ChannelAdapterManager, ChannelAdapterBase, ConfigManager and SDKManager // are fixed platform files and are not copied per channel. foreach (var oldJava in Directory.GetFiles(TysdkPlugins, "*Adapter.java")) { File.Delete(oldJava); } if (!Directory.Exists(cfgDir)) { return; } foreach (var javaFile in Directory.GetFiles(cfgDir, "*Adapter.java")) { var fileName = Path.GetFileName(javaFile); var dest = Path.Combine(TysdkPlugins, fileName); File.Copy(javaFile, dest, true); Debug.Log($"[ChannelSwitch] Adapter: {javaFile} -> {dest}"); } } private static void SyncGoogleServices(string cfgDir) { var dest = Path.Combine(TysdkFiles, "google-services.json"); var src = Path.Combine(cfgDir, "Files", "google-services.json"); if (!File.Exists(src)) { Debug.Log($"[ChannelSwitch] google-services.json not copied. Checked={src}"); return; } var destDir = Path.GetDirectoryName(dest); if (!Directory.Exists(destDir)) Directory.CreateDirectory(destDir); File.Copy(src, dest, true); Debug.Log($"[ChannelSwitch] google-services.json -> {dest}"); } private static void SyncChannelPluginFiles(string cfgDir) { var pluginsSrcDir = Path.Combine(cfgDir, "Plugins", "Android"); if (!Directory.Exists(pluginsSrcDir)) { Debug.Log($"[ChannelSwitch] Plugin directory not found. Checked={pluginsSrcDir}"); return; } foreach (var oldPlugin in Directory.GetFiles(TysdkPlugins, "tuyoosdk_*.aar")) { File.Delete(oldPlugin); } foreach (var pluginFile in Directory.GetFiles(pluginsSrcDir)) { if (pluginFile.EndsWith(".meta")) continue; var fileName = Path.GetFileName(pluginFile); var dest = Path.Combine(TysdkPlugins, fileName); File.Copy(pluginFile, dest, true); Debug.Log($"[ChannelSwitch] Plugin: {pluginFile} -> {dest}"); } } private static void SyncChannelManifestLib(string channel, string cfgDir) { var dest = Path.Combine(AssetsPlugins, ChannelManifestLib, "src"); if (channel == "GooglePlay" || !Directory.Exists(cfgDir)) { WriteEmptyChannelManifestLib(dest); Debug.Log($"[ChannelSwitch] Manifest lib reset to empty default. Channel={channel}"); return; } var srcManifest = Path.Combine(cfgDir, "AndroidManifest.xml"); if (!File.Exists(srcManifest)) { throw new FileNotFoundException($"[ChannelSwitch] Channel manifest not found: {srcManifest}"); } WriteChannelManifestLib(srcManifest, Path.Combine(cfgDir, "res"), dest); Debug.Log($"[ChannelSwitch] Manifest: {srcManifest} -> {Path.Combine(dest, "main", "AndroidManifest.xml")}"); } private static void SyncChannelGradleFiles(string channel, string cfgDir) { var src = Path.Combine(cfgDir, "Plugins", "Android", "gradle"); var dest = Path.Combine(AssetsPlugins, ChannelGradle); if (Directory.Exists(dest)) { Directory.Delete(dest, true); } var destMeta = dest + ".meta"; if (File.Exists(destMeta)) { File.Delete(destMeta); } if (!Directory.Exists(src)) { Debug.Log($"[ChannelSwitch] Gradle increment reset to empty default. Channel={channel}"); return; } CopyDirectoryClean(src, dest); Debug.Log($"[ChannelSwitch] Gradle increment: {src} -> {dest}"); } private static void SetMainManifestChannel(string channel) { var manifestPath = Path.Combine(AssetsPlugins, "AndroidManifest.xml"); if (!File.Exists(manifestPath)) { throw new FileNotFoundException($"[ChannelSwitch] Main AndroidManifest not found: {manifestPath}"); } var doc = XDocument.Load(manifestPath); var root = doc.Root; var application = root?.Elements().FirstOrDefault(x => x.Name.LocalName == "application"); if (application == null) { throw new InvalidDataException($"[ChannelSwitch] Main AndroidManifest application node not found: {manifestPath}"); } root.SetAttributeValue("package", GetBundleId(channel)); SetMainManifestChannelMeta(application, channel); SetMainManifestBackupRules(application, channel); doc.Save(manifestPath); AssetDatabase.ImportAsset(manifestPath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate); Debug.Log($"[ChannelSwitch] Main manifest channel -> {channel}"); } private static void SetMainManifestChannelMeta(XElement application, string channel) { var channelMeta = application.Elements() .FirstOrDefault(x => x.Name.LocalName == "meta-data" && (string)x.Attribute(AndroidNamespace + "name") == ChannelMetaName); if (channelMeta == null) { channelMeta = new XElement("meta-data", new XAttribute(AndroidNamespace + "name", ChannelMetaName)); application.Add(channelMeta); } channelMeta.SetAttributeValue(AndroidNamespace + "name", ChannelMetaName); channelMeta.SetAttributeValue(AndroidNamespace + "value", channel); } private static void SetMainManifestBackupRules(XElement application, string channel) { const string fullBackupContent = "android:fullBackupContent"; var replaceAttr = application.Attribute(ToolsNamespace + "replace"); var replaceItems = replaceAttr?.Value .Split(',') .Select(x => x.Trim()) .Where(x => !string.IsNullOrEmpty(x)) .ToList() ?? new List(); if (channel == "Flexion") { application.SetAttributeValue(AndroidNamespace + "fullBackupContent", "@xml/flexion_backup_rules"); if (!replaceItems.Contains(fullBackupContent)) { replaceItems.Add(fullBackupContent); } } else { application.SetAttributeValue(AndroidNamespace + "fullBackupContent", null); replaceItems.RemoveAll(x => x == fullBackupContent); } application.SetAttributeValue(ToolsNamespace + "replace", replaceItems.Count > 0 ? string.Join(",", replaceItems) : null); } private static void WriteEmptyChannelManifestLib(string dest) { if (Directory.Exists(dest)) { Directory.Delete(dest, true); } var manifestDir = Path.Combine(dest, "main"); Directory.CreateDirectory(manifestDir); File.WriteAllText(Path.Combine(manifestDir, "AndroidManifest.xml"), EmptyManifest); } private static void CleanChannelManifestLibBuildArtifacts() { var buildDir = Path.Combine(AssetsPlugins, ChannelManifestLib, "build"); if (Directory.Exists(buildDir)) { Directory.Delete(buildDir, true); } var buildMeta = buildDir + ".meta"; if (File.Exists(buildMeta)) { File.Delete(buildMeta); } } private static void WriteChannelManifestLib(string srcManifest, string srcResDir, string dest) { if (Directory.Exists(dest)) { Directory.Delete(dest, true); } var manifestDir = Path.Combine(dest, "main"); Directory.CreateDirectory(manifestDir); File.Copy(srcManifest, Path.Combine(manifestDir, "AndroidManifest.xml"), true); if (Directory.Exists(srcResDir)) { CopyDirectoryClean(srcResDir, Path.Combine(manifestDir, "res")); } } private static void CopyDirectoryClean(string src, string dest) { if (Directory.Exists(dest)) { Directory.Delete(dest, true); } Directory.CreateDirectory(dest); foreach (var srcFile in Directory.GetFiles(src, "*", SearchOption.AllDirectories)) { if (srcFile.EndsWith(".meta")) continue; var relativePath = srcFile.Substring(src.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); var destFile = Path.Combine(dest, relativePath); var destDir = Path.GetDirectoryName(destFile); if (!Directory.Exists(destDir)) Directory.CreateDirectory(destDir); File.Copy(srcFile, destFile, true); } } private static void SetAddressablesProfile(string channel) { var settings = AddressableAssetSettingsDefaultObject.Settings; if (settings == null) { Debug.LogWarning("[ChannelSwitch] Addressables settings not found."); return; } var profileName = UsesRustoreAddressablesProfile(channel) ? "arksgameru" : "arksgamecos"; var profileId = settings.profileSettings.GetProfileId(profileName); if (string.IsNullOrEmpty(profileId)) { Debug.LogError($"[ChannelSwitch] Addressables profile not found: {profileName}"); return; } settings.activeProfileId = profileId; var remoteLoadPath = settings.RemoteCatalogLoadPath.GetValue(settings); var remoteBuildPath = settings.RemoteCatalogBuildPath.GetValue(settings); Debug.Log($"[ChannelSwitch] Addressables profile -> {profileName}, profileId={profileId}, Remote.LoadPath={remoteLoadPath}, Remote.BuildPath={remoteBuildPath}"); } private static void SyncAddressablesContentState(string channel, string cfgDir) { var src = Path.Combine(cfgDir, AddressablesContentState); if (!File.Exists(src) && UsesRustoreAddressablesContentState(channel)) { Debug.Log($"[ChannelSwitch] Channel content state not found, try legacy Rustore content state path. Channel={channel}, checked={src}"); src = Path.Combine("../ChannelConfigs", AddressablesContentState); } if (!File.Exists(src)) { ClearAddressablesContentState(channel); Debug.Log($"[ChannelSwitch] Addressables content state not copied. Channel={channel}, checked={src}"); return; } var destDir = Path.GetDirectoryName(AndroidAddressablesContentState); if (!Directory.Exists(destDir)) Directory.CreateDirectory(destDir); File.Copy(src, AndroidAddressablesContentState, true); Debug.Log($"[ChannelSwitch] Addressables content state: {src} -> {AndroidAddressablesContentState}"); } private static void ClearAddressablesContentState(string channel) { if (File.Exists(AndroidAddressablesContentState)) { File.Delete(AndroidAddressablesContentState); } var meta = AndroidAddressablesContentState + ".meta"; if (File.Exists(meta)) { File.Delete(meta); } var dir = Path.GetDirectoryName(AndroidAddressablesContentState); if (Directory.Exists(dir) && !Directory.EnumerateFileSystemEntries(dir).Any()) { Directory.Delete(dir); } var dirMeta = dir + ".meta"; if (File.Exists(dirMeta) && !Directory.Exists(dir)) { File.Delete(dirMeta); } Debug.Log($"[ChannelSwitch] Addressables content state cleared. Channel={channel}"); } private static bool UsesRustoreAddressablesContentState(string channel) { return channel == "Rustore" || channel == "EnjoyPay"; } private static bool UsesRustoreAddressablesProfile(string channel) { return channel == "Rustore" || channel == "EnjoyPay"; } }