Decompiled source of ItemRoulettePatcher v2.0.0

ItemRoulettePatcher.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using ItemRoulettePatcher.Patches;
using Microsoft.CodeAnalysis;
using RoR2;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ItemRoulettePatcher")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0")]
[assembly: AssemblyProduct("ItemRoulettePatcher")]
[assembly: AssemblyTitle("ItemRoulettePatcher")]
[assembly: AssemblyVersion("2.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ItemRoulettePatcher
{
	internal static class ItemRouletteBridge
	{
		public const string PluginGuid = "com.user.itemroulette";

		public const string TestedVersion = "1.5.0";

		private static Assembly _assembly;

		private static PropertyInfo _isRussianProperty;

		public static bool Init()
		{
			if (Chainloader.PluginInfos.TryGetValue("com.user.itemroulette", out var value) && (Object)(object)value.Instance != (Object)null)
			{
				_assembly = ((object)value.Instance).GetType().Assembly;
				string text = value.Metadata.Version.ToString();
				if (text != "1.5.0")
				{
					Plugin.Log.LogWarning((object)("ItemRoulette " + text + " is installed but these patches were written against 1.5.0. Each patch checks that its target still exists and is skipped (with a warning) if not."));
				}
				return true;
			}
			return false;
		}

		public static Type FindType(string fullName)
		{
			Type? obj = _assembly?.GetType(fullName, throwOnError: false);
			if (obj == null)
			{
				Plugin.Log.LogWarning((object)("ItemRoulette type not found: " + fullName));
			}
			return obj;
		}

		public static bool IsRussian()
		{
			try
			{
				if (_isRussianProperty == null)
				{
					_isRussianProperty = AccessTools.Property(FindType("ItemRoulette.Core.Localization"), "IsRussian");
				}
				if (_isRussianProperty != null)
				{
					return (bool)_isRussianProperty.GetValue(null);
				}
			}
			catch (Exception)
			{
			}
			if (Language.currentLanguageName != null)
			{
				return Language.currentLanguageName.StartsWith("ru", StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}
	}
	[BepInPlugin("com.itemroulettepatcher.fixes", "ItemRoulettePatcher", "2.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "com.itemroulettepatcher.fixes";

		public const string Name = "ItemRoulettePatcher";

		public const string Version = "2.0.0";

		internal static ManualLogSource Log;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			if (!ItemRouletteBridge.Init())
			{
				Log.LogError((object)"ItemRoulette is not loaded; the patcher has nothing to patch and will stay idle.");
				((Behaviour)this).enabled = false;
				return;
			}
			PluginConfig.Bind(((BaseUnityPlugin)this).Config);
			_harmony = new Harmony("com.itemroulettepatcher.fixes");
			try
			{
				RussianTextPatch.Apply(_harmony);
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Patch 'Russian text fallback' failed and was skipped: " + ex));
			}
			Log.LogInfo((object)"ItemRoulettePatcher 2.0.0 loaded (patching ItemRoulette 1.5.0).");
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal static class PluginConfig
	{
		public static ConfigEntry<bool> TranslateRussianFallbackText;

		public static ConfigEntry<bool> LogUntranslatedRussian;

		public static void Bind(ConfigFile config)
		{
			TranslateRussianFallbackText = config.Bind<bool>("Localization", "TranslateRussianFallbackText", true, "ItemRoulette 1.5.0 still shows a few Russian-only messages when its Language setting resolves to English (some chaos-event results, companion/drone subtitles). When true, those are translated to English.");
			LogUntranslatedRussian = config.Bind<bool>("Localization", "LogUntranslatedRussian", true, "Log a warning (once per distinct text) when Russian text is shown while ItemRoulette is set to a non-Russian language and the patcher has no translation for it. Useful for reporting leftovers to the ItemRoulette author.");
		}
	}
}
namespace ItemRoulettePatcher.Patches
{
	internal static class RussianTextPatch
	{
		public static void Apply(Harmony harmony)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Expected O, but got Unknown
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Expected O, but got Unknown
			Type type = ItemRouletteBridge.FindType("ItemRoulette.Core.ChaosEventDefinition");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.PropertyGetter(type, "Description"));
			if (methodInfo != null)
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(RussianTextPatch), "TranslateResult", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			ConstructorInfo constructorInfo = ItemRouletteBridge.FindType("ItemRoulette.Core.NotificationEntry")?.GetConstructors().FirstOrDefault((ConstructorInfo c) => c.GetParameters().Length == 6);
			if (constructorInfo != null)
			{
				harmony.Patch((MethodBase)constructorInfo, new HarmonyMethod(typeof(RussianTextPatch), "TranslateNotification", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo2 = AccessTools.Method(typeof(CharacterBody), "GetSubtitle", (Type[])null, (Type[])null);
			if (methodInfo2 != null)
			{
				harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(RussianTextPatch), "TranslateSubtitle", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private static bool ShouldTranslate()
		{
			if (PluginConfig.TranslateRussianFallbackText.Value)
			{
				return !ItemRouletteBridge.IsRussian();
			}
			return false;
		}

		private static void TranslateNotification(ref string message)
		{
			if (ShouldTranslate())
			{
				message = RussianTextTranslator.Translate(message, "notification");
			}
		}

		private static void TranslateResult(ref string __result)
		{
			if (ShouldTranslate())
			{
				__result = RussianTextTranslator.Translate(__result, "chaos event");
			}
		}

		private static void TranslateSubtitle(ref string __result)
		{
			if (ShouldTranslate())
			{
				__result = RussianTextTranslator.TranslateSubtitle(__result);
			}
		}
	}
	internal static class RussianTextTranslator
	{
		private static readonly Regex Cyrillic = new Regex("[Ѐ-ӿ]", RegexOptions.Compiled);

		private static readonly (Regex pattern, string replacement)[] Patterns = new(Regex, string)[1] { (new Regex("Возврат \\$(\\d+) \\(x(\\d+) за ([^)]*)\\)!", RegexOptions.Compiled), "Refund $$$1 (x$2 for $3)!") };

		private static readonly (string ru, string en)[] Literals = new(string, string)[11]
		{
			("Получена вторая копия: ", "Received a second copy: "),
			("Получено +10 временных копий: ", "Received +10 temporary copies: "),
			(" (на 60 сек)!", " (for 60 sec)!"),
			("Получено +5 спектральных копий: ", "Received +5 spectral copies: "),
			(" (до конца этапа)!", " (until the end of the stage)!"),
			("Баланс золота удвоен (+$", "Gold balance doubled (+$"),
			("Скопирован предмет того же тира у напарника!", "Copied an item of the same tier from a teammate!"),
			("Скопирован предмет: ", "Copied item: "),
			("Получен элементальный аспект!", "Received an elemental aspect!"),
			("Элементальный Аспект", "Elemental Aspect"),
			("Призваны союзные дроны поддержки!", "Summoned allied support drones!")
		}.OrderByDescending(((string, string) e) => e.Item1.Length).ToArray();

		private static readonly (string ru, string en)[] SubtitleLiterals = new(string, string)[3]
		{
			("Спутник ", "Companion of "),
			("Дрон ", "Drone of "),
			("игрока", "player")
		};

		private static readonly HashSet<string> AlreadyReported = new HashSet<string>();

		private const int MaxReports = 64;

		public static bool ContainsCyrillic(string text)
		{
			if (!string.IsNullOrEmpty(text))
			{
				return Cyrillic.IsMatch(text);
			}
			return false;
		}

		public static string Translate(string text, string source)
		{
			if (!ContainsCyrillic(text))
			{
				return text;
			}
			string text2 = text;
			(Regex, string)[] patterns = Patterns;
			for (int i = 0; i < patterns.Length; i++)
			{
				(Regex, string) tuple = patterns[i];
				Regex item = tuple.Item1;
				string item2 = tuple.Item2;
				text2 = item.Replace(text2, item2);
			}
			(string, string)[] literals = Literals;
			for (int i = 0; i < literals.Length; i++)
			{
				var (text3, newValue) = literals[i];
				if (text2.Contains(text3))
				{
					text2 = text2.Replace(text3, newValue);
				}
			}
			ReportIfStillRussian(text2, source);
			return text2;
		}

		public static string TranslateSubtitle(string text)
		{
			if (!ContainsCyrillic(text))
			{
				return text;
			}
			string text2 = text;
			(string, string)[] subtitleLiterals = SubtitleLiterals;
			for (int i = 0; i < subtitleLiterals.Length; i++)
			{
				(string, string) tuple = subtitleLiterals[i];
				string item = tuple.Item1;
				string item2 = tuple.Item2;
				text2 = text2.Replace(item, item2);
			}
			ReportIfStillRussian(text2, "subtitle");
			return text2;
		}

		private static void ReportIfStillRussian(string text, string source)
		{
			if (!PluginConfig.LogUntranslatedRussian.Value || !ContainsCyrillic(text))
			{
				return;
			}
			lock (AlreadyReported)
			{
				if (AlreadyReported.Count >= 64 || !AlreadyReported.Add(text))
				{
					return;
				}
			}
			Plugin.Log.LogWarning((object)("Untranslated Russian text (" + source + ") shown while ItemRoulette language is not Russian: \"" + text + "\""));
		}
	}
}