Silksong.I18N.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using TeamCherry.Localization;
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("Silksong.I18N")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1+7b33beff1ebb86b901dd78a1aebf3c8cc3c3c007")]
[assembly: AssemblyProduct("Silksong.I18N")]
[assembly: AssemblyTitle("I18N")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/silksong-modding/Silksong.I18N")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 BepInEx
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	internal sealed class BepInAutoPluginAttribute : Attribute
	{
		public BepInAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace BepInEx.Preloader.Core.Patching
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	internal sealed class PatcherAutoPluginAttribute : Attribute
	{
		public PatcherAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace Silksong.I18N
{
	[BepInPlugin("org.silksong-modding.i18n", "I18N", "1.0.1")]
	internal sealed class I18NPlugin : BaseUnityPlugin
	{
		private static I18NPlugin? _instance;

		public const string Id = "org.silksong-modding.i18n";

		private static I18NPlugin? Instance
		{
			get
			{
				if (!Object.op_Implicit((Object)(object)_instance))
				{
					return null;
				}
				return _instance;
			}
		}

		public static string Name => "I18N";

		public static string Version => "1.0.1";

		private void Start()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			_instance = this;
			new Harmony("org.silksong-modding.i18n").PatchAll(typeof(I18NPlugin));
			LoadAllModSheets();
		}

		[HarmonyPatch(typeof(Language), "DoSwitch")]
		[HarmonyPostfix]
		private static void OnLanguageSwitched()
		{
			Instance?.LoadAllModSheets();
		}

		private void LoadAllModSheets()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			LanguageCode currentLanguage = Language._currentLanguage;
			foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
			{
				pluginInfo.Deconstruct(out var key, out var value);
				string text = key;
				BaseUnityPlugin instance = value.Instance;
				if (!Object.op_Implicit((Object)(object)instance))
				{
					continue;
				}
				Assembly assembly = ((object)instance).GetType().Assembly;
				if (Utility.IsNullOrWhiteSpace(assembly.Location))
				{
					((BaseUnityPlugin)this).Logger.LogDebug((object)("mod " + text + " assembly has no location, if you are using ScriptEngine, please enable DumpedAssemblies of ScriptEngine and place the languages folder in BepInEx\\ScriptEngineDumpedAssemblies"));
					continue;
				}
				string directoryName = Path.GetDirectoryName(assembly.Location);
				if (!Directory.Exists(directoryName))
				{
					continue;
				}
				if (string.Equals(Path.GetFullPath(directoryName).TrimEnd(Path.DirectorySeparatorChar), Path.GetFullPath(Paths.PluginPath).TrimEnd(Path.DirectorySeparatorChar), StringComparison.InvariantCultureIgnoreCase))
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)("mod " + text + " installed directly in plugins dir, not loading languages"));
					continue;
				}
				Dictionary<string, string> dictionary = null;
				NeutralResourcesLanguageAttribute customAttribute = assembly.GetCustomAttribute<NeutralResourcesLanguageAttribute>();
				if (customAttribute != null)
				{
					string text2 = customAttribute.CultureName.ToUpper();
					dictionary = LoadModSheet(directoryName, text2.ToLower());
					if (dictionary != null)
					{
						((BaseUnityPlugin)this).Logger.LogDebug((object)("loaded fallback sheet in language " + text2 + " for mod " + text));
					}
				}
				Dictionary<string, string> dictionary2 = LoadModSheet(directoryName, ((object)(LanguageCode)(ref currentLanguage)).ToString().ToLower(), dictionary);
				if (dictionary2 != null)
				{
					Language._currentEntrySheets["Mods." + text] = dictionary2;
					((BaseUnityPlugin)this).Logger.LogDebug((object)$"loaded sheet in language {currentLanguage} for mod {text}");
				}
			}
		}

		private Dictionary<string, string>? LoadModSheet(string modDir, string lang, Dictionary<string, string>? fallback = null)
		{
			string lang2 = lang;
			EnumerationOptions opts = new EnumerationOptions();
			opts.MatchCasing = MatchCasing.CaseInsensitive;
			bool flag = false;
			Dictionary<string, string> dictionary = fallback ?? new Dictionary<string, string>();
			try
			{
				foreach (Dictionary<string, string> item in (from p in Directory.EnumerateDirectories(modDir, "languages", opts).SelectMany((string dir) => Directory.EnumerateFiles(dir, lang2 + ".json", opts))
					orderby p
					select p).Select(ReadSheetFile).OfType<Dictionary<string, string>>())
				{
					if (flag)
					{
						((BaseUnityPlugin)this).Logger.LogWarning((object)("multiple casings found for language " + lang2.ToUpper() + " in: " + modDir));
					}
					flag = true;
					foreach (KeyValuePair<string, string> item2 in item)
					{
						item2.Deconstruct(out var key, out var value);
						string key2 = key;
						string value2 = value;
						dictionary[key2] = value2;
					}
				}
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"unable to load mod sheets: {modDir}\n{arg}");
				return null;
			}
			if (flag || fallback != null)
			{
				return dictionary;
			}
			return null;
		}

		private Dictionary<string, string>? ReadSheetFile(string path)
		{
			try
			{
				using StreamReader streamReader = new StreamReader(File.OpenRead(path), Encoding.UTF8, detectEncodingFromByteOrderMarks: false);
				return JsonConvert.DeserializeObject<Dictionary<string, string>>(streamReader.ReadToEnd());
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"unable to read language file: {path}\n{arg}");
				return null;
			}
		}

		[HarmonyPatch(typeof(Language), "Get", new Type[]
		{
			typeof(string),
			typeof(string)
		})]
		[HarmonyPostfix]
		private static void OnGetLocalizedText(string? key, string? sheetTitle)
		{
			Instance?.WarnIfModKeyMissing(sheetTitle, key);
		}

		[HarmonyPatch(typeof(LocalisedString), "ToString", new Type[] { typeof(bool) })]
		[HarmonyPostfix]
		private static void OnGetLocalizedString(LocalisedString __instance, bool allowBlankText)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			Instance?.WarnIfModKeyMissing(__instance.Sheet, __instance.Key, allowBlankText);
		}

		private void WarnIfModKeyMissing(string? sheet, string? key, bool allowBlankText = true)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			if (!string.IsNullOrEmpty(sheet) && !string.IsNullOrEmpty(key) && sheet.StartsWith("Mods."))
			{
				if (!Language.Has(key, sheet))
				{
					LanguageCode val = Language.CurrentLanguage();
					string arg = sheet.Substring("Mods.".Length);
					((BaseUnityPlugin)this).Logger.LogWarning((object)$"language {val} for mod {arg} missing: {key}");
				}
				else if (!allowBlankText && string.IsNullOrWhiteSpace(LocalisedString.ReplaceTags(Language.Get(key, sheet))))
				{
					LanguageCode val2 = Language.CurrentLanguage();
					string arg2 = sheet.Substring("Mods.".Length);
					((BaseUnityPlugin)this).Logger.LogWarning((object)$"language {val2} for mod {arg2} is blank at: {key}");
				}
			}
		}
	}
}