Decompiled source of ZetAspectsTranslator v1.0.1

plugins\NovaGC-ZetAspectsTranslator\ZetAspectsTranslator.dll

Decompiled 3 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using TPDespair.ZetAspects;
using ZetAspectsTranslator.Controllers;
using ZetAspectsTranslator.Models;
using ZetAspectsTranslator.Models.Exceptions;
using ZetAspectsTranslator.Models.Extends;
using ZetAspectsTranslator.Services;
using ZetAspectsTranslator.Services.TranslationProvider;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ZetAspectsTranslator")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+fe27d376d9184732a052fad8f6a516aa44f0bbb0")]
[assembly: AssemblyProduct("ZetAspectsTranslator")]
[assembly: AssemblyTitle("ZetAspectsTranslator")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ZetAspectsTranslator
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("NovaGC.ZetAspectsTranslator", "ZetAspectsTranslator", "1.0.0")]
	public class ZetAspectsTranslatorPlugin : BaseUnityPlugin
	{
		public const string Guid = "NovaGC.ZetAspectsTranslator";

		public const string Author = "NovaGC";

		public const string Name = "ZetAspectsTranslator";

		public const string Version = "1.0.0";

		public const string BasePath = "NovaGC-ZetAspectsTranslator";

		private readonly string[] _schemaFiles = new string[2] { "settings.schema.json", "tokens.schema.json" };

		public void Awake()
		{
			Log.Init(((BaseUnityPlugin)this).Logger);
			string text = Path.Combine(Paths.PluginPath, "NovaGC-ZetAspectsTranslator", "NovaGC-ZetAspectsTranslator", "translations");
			string text2 = Path.Combine(Paths.GameRootPath, "Risk of Rain 2_Data", "StreamingAssets", "LanguageOverrides", "ZetAspects");
			InitFoldersAndSchemas(text, text2);
			TranslationController translationController = new TranslationController();
			string[] array = new string[2] { text, text2 };
			string[] array2 = array;
			foreach (string path in array2)
			{
				List<TranslationFileProvider> translations = (from x in Directory.GetFiles(path, "*.json")
					select new FileInfo(x) into x
					where !_schemaFiles.Contains(x.Name)
					orderby x.Name descending
					select new TranslationFileProvider(path, x.FullName)).ToList();
				translationController.RegisterTranslations(translations);
			}
		}

		private void InitFoldersAndSchemas(string pathInPlugin, string pathInGame)
		{
			string[] source = new string[4]
			{
				pathInPlugin,
				pathInGame,
				Path.Combine(pathInPlugin, "tokens"),
				Path.Combine(pathInGame, "tokens")
			};
			foreach (string item in source.Where((string x) => !Directory.Exists(x)))
			{
				Directory.CreateDirectory(item);
			}
			IEnumerable<FileInfo> enumerable = from x in _schemaFiles
				select new FileInfo(Path.Combine(pathInPlugin, x)) into x
				where x.Exists
				select x;
			foreach (FileInfo item2 in enumerable)
			{
				item2.CopyTo(Path.Combine(pathInGame, item2.Name), overwrite: true);
			}
		}
	}
}
namespace ZetAspectsTranslator.Services
{
	internal static class Log
	{
		private static ManualLogSource _logSource;

		private static Action<object>[] _logMethods = Enumerable.Repeat<Action<object>>(delegate
		{
		}, 6).ToArray();

		internal static void Init(ManualLogSource logSource)
		{
			_logSource = logSource;
			_logMethods = new Action<object>[6] { _logSource.LogDebug, _logSource.LogError, _logSource.LogFatal, _logSource.LogInfo, _logSource.LogMessage, _logSource.LogWarning };
		}

		internal static void Debug(object data)
		{
			_logMethods[0](data);
		}

		internal static void Error(object data)
		{
			_logMethods[1](data);
		}

		internal static void Fatal(object data)
		{
			_logMethods[2](data);
		}

		internal static void Info(object data)
		{
			_logMethods[3](data);
		}

		internal static void Message(object data)
		{
			_logMethods[4](data);
		}

		internal static void Warning(object data)
		{
			_logMethods[5](data);
		}
	}
}
namespace ZetAspectsTranslator.Services.TranslationProvider
{
	public interface ITranslationProvider
	{
		string Language { get; }

		Dictionary<string, string> Tokens { get; }
	}
	public class TranslationFileProvider : ITranslationProvider
	{
		private readonly string _baseTranslationsPath;

		private readonly HashSet<string> _processedFiles;

		public string Language { get; private set; }

		public Dictionary<string, string> Tokens { get; }

		public TranslationFileProvider(string baseTranslationsPath, string translationFileName)
		{
			_baseTranslationsPath = baseTranslationsPath;
			_processedFiles = new HashSet<string>();
			Language = null;
			Tokens = new Dictionary<string, string>();
			LoadTranslations(translationFileName);
		}

		private void LoadTranslations(string path)
		{
			if (!File.Exists(path))
			{
				throw new FileNotFoundException(path);
			}
			Stack<ExtendsSetting> stack = new Stack<ExtendsSetting>(new ExtendsSetting[1]
			{
				new ExtendsSetting
				{
					Path = path,
					Type = ExtendsType.Setting
				}
			});
			while (stack.Any())
			{
				try
				{
					ExtendsSetting extendsSetting = stack.Pop();
					extendsSetting.Path = GetFullPath(extendsSetting.Path);
					ExtendsSetting[] source = ProcessSetting(extendsSetting);
					foreach (ExtendsSetting item in source.Reverse())
					{
						stack.Push(item);
					}
					_processedFiles.Add(new FileInfo(extendsSetting.Path).FullName);
				}
				catch (Exception data)
				{
					Log.Error(data);
				}
			}
		}

		private ExtendsSetting[] ProcessSetting(ExtendsSetting setting)
		{
			if (!File.Exists(setting.Path))
			{
				throw new FileNotFoundException(setting.Path);
			}
			if (_processedFiles.Contains(setting.Path))
			{
				throw new CyclicalDependenceException(setting.Path);
			}
			if (setting.Type == ExtendsType.Tokens)
			{
				Dictionary<string, string> tokens = ParseJsonFile<Dictionary<string, string>>(setting.Path);
				MergeTokens(tokens);
				return Array.Empty<ExtendsSetting>();
			}
			TranslationSetting translationSetting = ParseJsonFile<TranslationSetting>(setting.Path);
			Language = (string.IsNullOrEmpty(Language) ? translationSetting.Language : Language);
			MergeTokens(translationSetting.Tokens);
			return translationSetting.Extends;
		}

		private T ParseJsonFile<T>(string path)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			using FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
			using StreamReader streamReader = new StreamReader(stream);
			JsonTextReader val = new JsonTextReader((TextReader)streamReader);
			try
			{
				JsonSerializer val2 = new JsonSerializer();
				return val2.Deserialize<T>((JsonReader)(object)val);
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		private void MergeTokens(Dictionary<string, string> tokens)
		{
			if (!tokens.Any())
			{
				return;
			}
			IEnumerable<KeyValuePair<string, string>> enumerable = from token in tokens
				where token.Key != "$schema"
				where !Tokens.ContainsKey(token.Key)
				select token;
			foreach (KeyValuePair<string, string> item in enumerable)
			{
				Tokens.Add(item.Key, item.Value);
			}
		}

		private string GetFullPath(string path)
		{
			return new FileInfo(Path.IsPathFullyQualified(path) ? path : Path.Combine(_baseTranslationsPath, path)).FullName;
		}
	}
}
namespace ZetAspectsTranslator.Models
{
	public class TranslationSetting
	{
		[JsonProperty("language")]
		public string Language { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Dictionary<string, string> Tokens { get; set; } = new Dictionary<string, string>();


		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public ExtendsSetting[] Extends { get; set; } = Array.Empty<ExtendsSetting>();

	}
}
namespace ZetAspectsTranslator.Models.Extends
{
	public class ExtendsSetting
	{
		[JsonProperty("path")]
		public string Path { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		[JsonConverter(typeof(StringEnumConverter), new object[] { typeof(CamelCaseNamingStrategy) })]
		public ExtendsType Type { get; set; } = ExtendsType.Tokens;

	}
	public enum ExtendsType
	{
		Setting,
		Tokens
	}
}
namespace ZetAspectsTranslator.Models.Exceptions
{
	public class CyclicalDependenceException : Exception
	{
		public string Path { get; }

		public override string Message => "A cyclical relationship has been discovered. The file \"" + Path + "\"it has already been processed.";

		public CyclicalDependenceException(string path)
		{
			Path = path;
			base..ctor();
		}
	}
	public class EmptyTokensException : Exception
	{
		private readonly string _language;

		public override string Message => "The " + _language + " translation does not contain tokens";

		public EmptyTokensException(string language)
		{
			_language = language;
		}
	}
}
namespace ZetAspectsTranslator.Controllers
{
	public class TranslationController
	{
		public void RegisterTranslations(IEnumerable<ITranslationProvider> translations)
		{
			foreach (ITranslationProvider translation in translations)
			{
				RegisterTranslation(translation);
			}
		}

		public void RegisterTranslation(ITranslationProvider translation)
		{
			try
			{
				RegisterTokens(translation.Language, translation.Tokens);
				Log.Info($"Registered {translation.Language} translation ({translation.Tokens.Count} tokens)");
			}
			catch (Exception data)
			{
				Log.Error(data);
			}
		}

		private void RegisterTokens(string language, Dictionary<string, string> tokens)
		{
			if (!tokens.Any())
			{
				throw new EmptyTokensException(language);
			}
			string targetLanguage = Language.targetLanguage;
			Language.targetLanguage = language;
			foreach (KeyValuePair<string, string> token in tokens)
			{
				Language.RegisterFragment(token.Key, token.Value);
			}
			Language.targetLanguage = targetLanguage;
		}
	}
}