Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of Lethal DissonanceRUv81 v3.1.2
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/ExIni.dll
Decompiled 4 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using Microsoft.Win32; [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyInformationalVersion("GIT master [cf85ca6f3fc361cf48bf56107e4cec9102b7f5eb] ")] [assembly: AssemblyTitle("ExIni")] [assembly: Guid("b8adf1ac-aade-485a-8997-14c4b42e0a8b")] [assembly: AssemblyDescription("Extended INI File Handler")] [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyFileVersion("1.0.2.1")] [assembly: AssemblyCompany("Usagirei")] [assembly: AssemblyProduct("ExIni")] [assembly: ComVisible(false)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCopyright("Copyright © Usagirei 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("1.0.2.1")] namespace ExIni; public class IniComment { public List<string> Comments { get; set; } public IniComment() { Comments = new List<string>(); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < Comments.Count; i++) { string text = Comments[i]; string value = ((i < Comments.Count - 1) ? (";" + text + Environment.NewLine) : (";" + text)); stringBuilder.Append(value); } return stringBuilder.ToString(); } public void Append(params string[] comments) { Comments.AddRange(comments); } } public class IniFile { private readonly IniComment _comments; private readonly List<IniSection> _sections; public IniSection this[string sec] => CreateSection(sec); public IniComment Comments => _comments; public List<IniSection> Sections => _sections; public IniFile() { _comments = new IniComment(); _sections = new List<IniSection>(); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < Sections.Count; i++) { IniSection iniSection = Sections[i]; if (iniSection.Comments.Comments.Any()) { stringBuilder.AppendLine(iniSection.Comments.ToString()); } stringBuilder.AppendLine(iniSection.ToString()); foreach (IniKey key in iniSection.Keys) { if (key.Comments.Comments.Any()) { stringBuilder.AppendLine(key.Comments.ToString()); } stringBuilder.AppendLine(key.ToString()); } if (i < Sections.Count - 1) { stringBuilder.AppendLine(); } } if (Comments.Comments.Any()) { stringBuilder.AppendLine(); stringBuilder.AppendLine(Comments.ToString()); } return stringBuilder.ToString(); } public IniSection CreateSection(string section) { IniSection section2 = GetSection(section); if (section2 != null) { return section2; } IniSection iniSection = new IniSection(section); _sections.Add(iniSection); return iniSection; } public bool DeleteSection(string section) { if (!HasSection(section)) { return false; } Sections.Remove(GetSection(section)); return true; } public IniSection GetSection(string section) { if (!HasSection(section)) { return null; } return _sections.FirstOrDefault((IniSection iniSection) => iniSection.Section == section); } public bool HasSection(string section) { return _sections.Any((IniSection iniSection) => iniSection.Section == section); } public void Merge(IniFile ini) { Comments.Append(ini.Comments.Comments.ToArray()); foreach (IniSection section in ini.Sections) { IniSection iniSection = this[section.Section]; iniSection.Comments.Append(section.Comments.Comments.ToArray()); foreach (IniKey key in section.Keys) { IniKey iniKey = iniSection[key.Key]; iniKey.Comments.Append(key.Comments.Comments.ToArray()); iniKey.Value = key.Value; } } } public void Save(string filePath) { string directoryName = Path.GetDirectoryName(filePath); if (!string.IsNullOrEmpty(directoryName)) { Directory.CreateDirectory(directoryName); } File.WriteAllText(filePath, ToString(), Encoding.UTF8); } public static IniFile FromFile(string iniString) { return IniParser.Parse(File.ReadAllText(iniString)); } public static IniFile FromString(string iniString) { return IniParser.Parse(iniString); } } public class IniKey { private readonly IniComment _comments; public IniComment Comments => _comments; public string Key { get; set; } public string RawValue { get; set; } public string Value { get { return Resolve(RawValue); } set { RawValue = value; } } public IniKey(string key, string value = null) { Key = key; Value = value; _comments = new IniComment(); } public override string ToString() { return $"{Key}={RawValue}"; } private static string GetEnvironment(string env) { return Environment.ExpandEnvironmentVariables(env); } private static string GetRegistry(string path) { string directoryName = Path.GetDirectoryName(path); string fileName = Path.GetFileName(path); if (string.IsNullOrEmpty(directoryName)) { return null; } return Registry.GetValue(directoryName, fileName, string.Empty)?.ToString(); } private static string Resolve(string value) { if (value == null) { return null; } Regex regex = new Regex("\\$\\((?<reg>.*)\\)"); Regex regex2 = new Regex("%.*%"); while (regex.IsMatch(value) || regex2.IsMatch(value)) { value = regex.Replace(value, (Match match) => GetRegistry(match.Groups["reg"].Value)); value = GetEnvironment(value); } return value; } } internal class IniParser { private static readonly Regex CommentRegex = new Regex("^;(?<com>.*)"); private static readonly Regex KeyRegex = new Regex("^(?<key>[\\w\\s]+)=(?<val>.*)$"); private static readonly Regex SectionRegex = new Regex("^\\[(?<sec>[\\w\\s]+)\\]$"); private static readonly Regex VarRegex = new Regex("^\\@(?<key>[\\w\\s]+)=(?<val>.*)$"); public static IniFile Parse(string iniString) { IniFile iniFile = new IniFile(); string[] array = (from line in iniString.Split(new char[1] { '\n' }) let trimmed = line.Trim() select trimmed.TrimEnd(new char[1] { '\r' })).ToArray(); List<string> list = new List<string>(); IniSection iniSection = null; bool flag = false; for (int i = 0; i < array.Length; i++) { string text = array[i]; if (string.IsNullOrEmpty(text)) { continue; } if (IsComment(text)) { string comment = GetComment(text); list.Add(comment); if (IsVariable(comment)) { string[] variable = GetVariable(comment); string variable2 = variable[0]; string value = variable[1]; Environment.SetEnvironmentVariable(variable2, value); } flag = true; } else if (IsSection(text)) { iniSection = iniFile[GetSection(text)]; if (flag) { iniSection.Comments.Append(list.ToArray()); list.Clear(); flag = false; } } else if (IsKey(text)) { if (iniSection == null) { throw new Exception($"{i}: Sectionless Key Value Pair"); } string[] key = GetKey(text); string key2 = key[0]; string value2 = key[1]; if (flag) { iniSection[key2].Comments.Append(list.ToArray()); list.Clear(); flag = false; } iniSection[key2].Value = value2; } } if (flag) { iniFile.Comments.Append(list.ToArray()); } return iniFile; } private static string GetComment(string line) { return CommentRegex.Match(line).Groups["com"].Value; } private static string[] GetKey(string line) { Match match = KeyRegex.Match(line); return new string[2] { match.Groups["key"].Value, match.Groups["val"].Value }; } private static string GetSection(string line) { return SectionRegex.Match(line).Groups["sec"].Value; } private static string[] GetVariable(string line) { Match match = VarRegex.Match(line); return new string[2] { match.Groups["key"].Value, match.Groups["val"].Value }; } private static bool IsComment(string line) { return CommentRegex.IsMatch(line); } private static bool IsKey(string line) { return KeyRegex.IsMatch(line); } private static bool IsSection(string line) { return SectionRegex.IsMatch(line); } private static bool IsVariable(string line) { return VarRegex.IsMatch(line); } } public class IniSection { private readonly IniComment _comments; private readonly List<IniKey> _keys; public IniKey this[string key] => CreateKey(key); public IniComment Comments => _comments; public List<IniKey> Keys => _keys; public string Section { get; set; } public IniSection(string section) { Section = section; _comments = new IniComment(); _keys = new List<IniKey>(); } public override string ToString() { return $"[{Section}]"; } public IniKey CreateKey(string key) { IniKey key2 = GetKey(key); if (key2 != null) { return key2; } IniKey iniKey = new IniKey(key); _keys.Add(iniKey); return iniKey; } public IniKey GetKey(string key) { if (!HasKey(key)) { return null; } return _keys.FirstOrDefault((IniKey iniKey) => iniKey.Key == key); } public bool HasKey(string key) { return _keys.Any((IniKey iniKey) => iniKey.Key == key); } public bool DeleteKey(string key) { if (!HasKey(key)) { return false; } Keys.Remove(GetKey(key)); return true; } }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/BaiduTranslate.dll
Decompiled 4 days agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using SimpleJSON; using XUnity.AutoTranslator.Plugin.Core; using XUnity.AutoTranslator.Plugin.Core.Constants; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Endpoints.Http; using XUnity.AutoTranslator.Plugin.Core.Extensions; using XUnity.AutoTranslator.Plugin.Core.Utilities; using XUnity.AutoTranslator.Plugin.Core.Web; using XUnity.Common.Utilities; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("BaiduTranslate")] [assembly: AssemblyTitle("BaiduTranslate")] [assembly: AssemblyVersion("5.6.1.0")] namespace BaiduTranslate; internal class BaiduTranslateEndpoint : HttpEndpoint { [CompilerGenerated] private sealed class <OnBeforeTranslate>d__13 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public BaiduTranslateEndpoint <>4__this; private float <realtimeSinceStartup>5__2; private float <end>5__3; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <OnBeforeTranslate>d__13(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { int num = <>1__state; BaiduTranslateEndpoint baiduTranslateEndpoint = <>4__this; switch (num) { default: return false; case 0: { <>1__state = -1; <realtimeSinceStartup>5__2 = TimeHelper.realtimeSinceStartup; float num2 = <realtimeSinceStartup>5__2 - baiduTranslateEndpoint._lastRequestTimestamp; if (!(num2 < baiduTranslateEndpoint._delay)) { break; } float num3 = baiduTranslateEndpoint._delay - num2; object obj = CoroutineHelper.CreateWaitForSecondsRealtime(num3); if (obj != null) { <>2__current = obj; <>1__state = 1; return true; } float num4 = <realtimeSinceStartup>5__2; <end>5__3 = num4 + num3; goto IL_00a5; } case 1: <>1__state = -1; break; case 2: { <>1__state = -1; goto IL_00a5; } IL_00a5: if (<realtimeSinceStartup>5__2 < <end>5__3) { <>2__current = null; <>1__state = 2; return true; } break; } baiduTranslateEndpoint._lastRequestTimestamp = TimeHelper.realtimeSinceStartup; return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private static readonly Dictionary<string, string> SupportedLanguages = new Dictionary<string, string> { { "en", "en" }, { "ja", "jp" }, { "jp", "jp" }, { "zh", "zh" }, { "zh-Hans", "zh" }, { "zh-CN", "zh" }, { "zh-Hant", "cht" }, { "zh-TW", "cht" }, { "ko", "kor" }, { "kor", "kor" }, { "fra", "fra" }, { "fr", "fra" }, { "spa", "spa" }, { "es", "spa" }, { "ara", "ara" }, { "ar", "ara" }, { "bg", "bul" }, { "bul", "bul" }, { "et", "est" }, { "est", "est" }, { "da", "dan" }, { "dan", "dan" }, { "fi", "fin" }, { "fin", "fin" }, { "ro", "rom" }, { "rom", "rom" }, { "sl", "slo" }, { "slo", "slo" }, { "vi", "vie" }, { "vie", "vie" }, { "sv", "swe" }, { "swe", "swe" }, { "th", "th" }, { "ru", "ru" }, { "pt", "pt" }, { "de", "de" }, { "it", "it" }, { "el", "el" }, { "nl", "nl" }, { "pl", "pl" }, { "cs", "cs" }, { "hu", "hu" } }; private static readonly string HttpServicePointTemplateUrl = "https://api.fanyi.baidu.com/api/trans/vip/translate?q={0}&from={1}&to={2}&appid={3}&salt={4}&sign={5}"; private static readonly MD5 HashMD5 = MD5.Create(); private string _appId; private string _appSecret; private float _delay; private float _lastRequestTimestamp; public override string Id => "BaiduTranslate"; public override string FriendlyName => "Baidu Translator"; private string FixLanguage(string lang) { if (SupportedLanguages.TryGetValue(lang, out var value)) { return value; } return lang; } public override void Initialize(IInitializationContext context) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) _appId = context.GetOrCreateSetting<string>("Baidu", "BaiduAppId", ""); _appSecret = context.GetOrCreateSetting<string>("Baidu", "BaiduAppSecret", ""); _delay = context.GetOrCreateSetting<float>("Baidu", "DelaySeconds", 1f); if (string.IsNullOrEmpty(_appId)) { throw new EndpointInitializationException("The BaiduTranslate endpoint requires an App Id which has not been provided."); } if (string.IsNullOrEmpty(_appSecret)) { throw new EndpointInitializationException("The BaiduTranslate endpoint requires an App Secret which has not been provided."); } context.DisableCertificateChecksFor(new string[1] { "api.fanyi.baidu.com" }); if (!SupportedLanguages.ContainsKey(context.SourceLanguage)) { throw new EndpointInitializationException("The source language '" + context.SourceLanguage + "' is not supported."); } if (!SupportedLanguages.ContainsKey(context.DestinationLanguage)) { throw new EndpointInitializationException("The destination language '" + context.DestinationLanguage + "' is not supported."); } } public override IEnumerator OnBeforeTranslate(IHttpTranslationContext context) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <OnBeforeTranslate>d__13(0) { <>4__this = this }; } public override void OnCreateRequest(IHttpRequestCreationContext context) { //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown string text = DateTime.UtcNow.Millisecond.ToString(); string text2 = CreateMD5(_appId + ((ITranslationContextBase)context).UntranslatedText + text + _appSecret); XUnityWebRequest val = new XUnityWebRequest(string.Format(HttpServicePointTemplateUrl, Uri.EscapeDataString(((ITranslationContextBase)context).UntranslatedText), FixLanguage(((ITranslationContextBase)context).SourceLanguage), FixLanguage(((ITranslationContextBase)context).DestinationLanguage), _appId, text, text2)); val.Headers[HttpRequestHeader.UserAgent] = (string.IsNullOrEmpty(AutoTranslatorSettings.UserAgent) ? UserAgents.Chrome_Win10_Latest : AutoTranslatorSettings.UserAgent); val.Headers[HttpRequestHeader.AcceptCharset] = "UTF-8"; context.Complete(val); } public override void OnExtractTranslation(IHttpTranslationExtractionContext context) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) string data = ((IHttpResponseInspectionContext)context).Response.Data; if (data.StartsWith("{\"error")) { return; } JSONNode val = JSON.Parse(data); StringBuilder stringBuilder = new StringBuilder(data.Length); Enumerator enumerator = ((JSONNode)((JSONNode)val.AsObject)["trans_result"].AsArray).GetEnumerator(); while (((Enumerator)(ref enumerator)).MoveNext()) { string text = ((object)((JSONNode)JSONNode.op_Implicit(((Enumerator)(ref enumerator)).Current).AsObject)["dst"]).ToString(); text = JsonHelper.Unescape(text.Substring(1, text.Length - 2)); if (!StringBuilderExtensions.EndsWithWhitespaceOrNewline(stringBuilder)) { stringBuilder.Append("\n"); } stringBuilder.Append(text); } string text2 = stringBuilder.ToString(); context.Complete(text2); } private static string CreateMD5(string input) { byte[] bytes = Encoding.UTF8.GetBytes(input); byte[] array = HashMD5.ComputeHash(bytes); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < array.Length; i++) { stringBuilder.Append(array[i].ToString("X2")); } return stringBuilder.ToString().ToLower(); } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/BingTranslate.dll
Decompiled 4 days agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using SimpleJSON; using XUnity.AutoTranslator.Plugin.Core; using XUnity.AutoTranslator.Plugin.Core.Constants; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Endpoints.Http; using XUnity.AutoTranslator.Plugin.Core.Shims; using XUnity.AutoTranslator.Plugin.Core.Utilities; using XUnity.AutoTranslator.Plugin.Core.Web; using XUnity.Common.Logging; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("BingTranslate")] [assembly: AssemblyTitle("BingTranslate")] [assembly: AssemblyVersion("5.6.1.0")] namespace BingTranslate; public class BingTranslateEndpoint : HttpEndpoint { [CompilerGenerated] private sealed class <OnBeforeTranslate>d__31 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public BingTranslateEndpoint <>4__this; private IEnumerator <enumerator>5__2; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <OnBeforeTranslate>d__31(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <enumerator>5__2 = null; <>1__state = -2; } private bool MoveNext() { int num = <>1__state; BingTranslateEndpoint bingTranslateEndpoint = <>4__this; if (num != 0) { if (num != 1) { return false; } <>1__state = -1; } else { <>1__state = -1; if (bingTranslateEndpoint._hasSetup && bingTranslateEndpoint._translationCount % bingTranslateEndpoint._resetAfter != 0) { goto IL_009a; } bingTranslateEndpoint._resetAfter = RandomNumbers.Next(75, 125); bingTranslateEndpoint._translationCount = 0; bingTranslateEndpoint._hasSetup = true; <enumerator>5__2 = bingTranslateEndpoint.SetupIGAndIID(); } if (<enumerator>5__2.MoveNext()) { <>2__current = <enumerator>5__2.Current; <>1__state = 1; return true; } <enumerator>5__2 = null; goto IL_009a; IL_009a: return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class <SetupIGAndIID>d__38 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public BingTranslateEndpoint <>4__this; private XUnityWebResponse <response>5__2; private IEnumerator <iterator>5__3; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <SetupIGAndIID>d__38(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <response>5__2 = null; <iterator>5__3 = null; <>1__state = -2; } private bool MoveNext() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown int num = <>1__state; BingTranslateEndpoint bingTranslateEndpoint = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <response>5__2 = null; bingTranslateEndpoint._cookieContainer = new CookieContainer(); try { XUnityWebClient val = new XUnityWebClient(); XUnityWebRequest val2 = bingTranslateEndpoint.CreateWebSiteRequest(); <response>5__2 = val.Send(val2); } catch (Exception ex) { XuaLogger.AutoTranslator.Warn(ex, "An error occurred while setting up BingTranslate IG. Proceeding without..."); return false; } <iterator>5__3 = ((CustomYieldInstructionShim)<response>5__2).GetSupportedEnumerator(); break; case 1: <>1__state = -1; break; } if (<iterator>5__3.MoveNext()) { <>2__current = <iterator>5__3.Current; <>1__state = 1; return true; } if (((CustomYieldInstructionShim)<response>5__2).IsTimedOut) { XuaLogger.AutoTranslator.Warn("A timeout error occurred while setting up BingTranslate IG. Proceeding without..."); return false; } if (<response>5__2.Error != null) { XuaLogger.AutoTranslator.Warn(<response>5__2.Error, "An error occurred while setting up BingTranslate IG. Proceeding without..."); return false; } if (<response>5__2.Data == null) { XuaLogger.AutoTranslator.Warn((Exception)null, "An error occurred while setting up BingTranslate IG. Proceeding without..."); return false; } bingTranslateEndpoint.InspectResponse(<response>5__2); try { string data = <response>5__2.Data; bingTranslateEndpoint._ig = bingTranslateEndpoint.Lookup("\",IG:\"", data); bingTranslateEndpoint._iid = bingTranslateEndpoint.Lookup("data-iid=\"", data); if (bingTranslateEndpoint._ig == null || bingTranslateEndpoint._iid == null) { XuaLogger.AutoTranslator.Warn("An error occurred while setting up BingTranslate IG/IID. Proceeding without..."); } } catch (Exception ex2) { XuaLogger.AutoTranslator.Warn(ex2, "An error occurred while setting up BingTranslate IG. Proceeding without..."); } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private static readonly HashSet<string> SupportedLanguages = new HashSet<string> { "auto-detect", "af", "ar", "bn", "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", "fil", "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", "tlh", "tlh-Qaak", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", "ta", "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua" }; private static readonly string HttpsServicePointTemplateUrl = "https://www.bing.com/ttranslatev3?isVertical=1&&IG={0}&IID={1}.{2}"; private static readonly string HttpsServicePointTemplateUrlWithoutIG = "https://www.bing.com/ttranslatev3?isVertical=1"; private static readonly string HttpsTranslateUserSite = "https://www.bing.com/translator"; private static readonly string RequestTemplate = "&fromLang={1}&text={0}&to={2}"; private static readonly Random RandomNumbers = new Random(); private static readonly string[] Accepts = new string[1] { "*/*" }; private static readonly string[] AcceptLanguages = new string[4] { null, "en-US,en;q=0.9", "en-US", "en" }; private static readonly string[] Referers = new string[1] { "https://bing.com/translator" }; private static readonly string[] Origins = new string[1] { "https://www.bing.com" }; private static readonly string[] AcceptCharsets = new string[2] { null, Encoding.UTF8.WebName }; private static readonly string[] ContentTypes = new string[1] { "application/x-www-form-urlencoded" }; private static readonly string Accept = Accepts[RandomNumbers.Next(Accepts.Length)]; private static readonly string AcceptLanguage = AcceptLanguages[RandomNumbers.Next(AcceptLanguages.Length)]; private static readonly string Referer = Referers[RandomNumbers.Next(Referers.Length)]; private static readonly string Origin = Origins[RandomNumbers.Next(Origins.Length)]; private static readonly string AcceptCharset = AcceptCharsets[RandomNumbers.Next(AcceptCharsets.Length)]; private static readonly string ContentType = ContentTypes[RandomNumbers.Next(ContentTypes.Length)]; private CookieContainer _cookieContainer; private bool _hasSetup; private string _ig; private string _iid; private int _translationCount; private int _resetAfter = RandomNumbers.Next(75, 125); public override string Id => "BingTranslate"; public override string FriendlyName => "Bing Translator"; public BingTranslateEndpoint() { _cookieContainer = new CookieContainer(); } private string FixLanguage(string lang) { switch (lang) { case "zh-CN": case "zh": return "zh-Hans"; case "zh-TW": return "zh-Hant"; case "auto": return "auto-detect"; default: return lang; } } public override void Initialize(IInitializationContext context) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) context.DisableCertificateChecksFor(new string[1] { "www.bing.com" }); if (!SupportedLanguages.Contains(FixLanguage(context.SourceLanguage))) { throw new EndpointInitializationException("The source language '" + context.SourceLanguage + "' is not supported."); } if (!SupportedLanguages.Contains(FixLanguage(context.DestinationLanguage))) { throw new EndpointInitializationException("The destination language '" + context.DestinationLanguage + "' is not supported."); } } public override IEnumerator OnBeforeTranslate(IHttpTranslationContext context) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <OnBeforeTranslate>d__31(0) { <>4__this = this }; } public override void OnCreateRequest(IHttpRequestCreationContext context) { //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Expected O, but got Unknown _translationCount++; string text = null; text = ((_ig != null && _iid != null) ? string.Format(HttpsServicePointTemplateUrl, _ig, _iid, _translationCount) : HttpsServicePointTemplateUrlWithoutIG); string text2 = string.Format(RequestTemplate, Uri.EscapeDataString(((ITranslationContextBase)context).UntranslatedText), FixLanguage(((ITranslationContextBase)context).SourceLanguage), FixLanguage(((ITranslationContextBase)context).DestinationLanguage)); XUnityWebRequest val = new XUnityWebRequest("POST", text, text2); val.Cookies = _cookieContainer; AddHeaders(val, isTranslationRequest: true); context.Complete(val); } public override void OnInspectResponse(IHttpResponseInspectionContext context) { InspectResponse(context.Response); } public override void OnExtractTranslation(IHttpTranslationExtractionContext context) { string text = ((object)((JSONNode)((JSONNode)JSON.Parse(((IHttpResponseInspectionContext)context).Response.Data).AsArray)[0]["translations"].AsArray)[0]["text"]).ToString(); string text2 = JsonHelper.Unescape(text.Substring(1, text.Length - 2)); context.Complete(text2); } private XUnityWebRequest CreateWebSiteRequest() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown XUnityWebRequest val = new XUnityWebRequest(HttpsTranslateUserSite); val.Cookies = _cookieContainer; AddHeaders(val, isTranslationRequest: false); return val; } private void AddHeaders(XUnityWebRequest request, bool isTranslationRequest) { request.Headers[HttpRequestHeader.UserAgent] = (string.IsNullOrEmpty(AutoTranslatorSettings.UserAgent) ? UserAgents.Chrome_Win10_Latest : AutoTranslatorSettings.UserAgent); if (AcceptLanguage != null) { request.Headers[HttpRequestHeader.AcceptLanguage] = AcceptLanguage; } if (Accept != null) { request.Headers[HttpRequestHeader.Accept] = Accept; } if (Referer != null && isTranslationRequest) { request.Headers[HttpRequestHeader.Referer] = Referer; } if (Origin != null && isTranslationRequest) { request.Headers["Origin"] = Origin; } if (AcceptCharset != null) { request.Headers[HttpRequestHeader.AcceptCharset] = AcceptCharset; } if (ContentType != null && isTranslationRequest) { request.Headers[HttpRequestHeader.ContentType] = ContentType; } } private void InspectResponse(XUnityWebResponse response) { CookieCollection newCookies = response.NewCookies; _cookieContainer.Add(newCookies); } public IEnumerator SetupIGAndIID() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <SetupIGAndIID>d__38(0) { <>4__this = this }; } private string Lookup(string lookFor, string html) { int num = html.IndexOf(lookFor, StringComparison.Ordinal); if (num > -1) { int num2 = num + lookFor.Length; int num3 = html.IndexOf('"', num2); if (num2 > -1 && num3 > -1) { return html.Substring(num2, num3 - num2); } } return null; } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/BingTranslateLegitimate.dll
Decompiled 4 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using SimpleJSON; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Endpoints.Http; using XUnity.AutoTranslator.Plugin.Core.Utilities; using XUnity.AutoTranslator.Plugin.Core.Web; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("BingTranslateLegitimate")] [assembly: AssemblyTitle("BingTranslateLegitimate")] [assembly: AssemblyVersion("5.6.1.0")] namespace BingTranslateLegitimate; public class BingTranslateLegitimateEndpoint : HttpEndpoint { private static readonly HashSet<string> SupportedLanguages = new HashSet<string> { "af", "ar", "bn", "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs", "da", "nl", "en", "et", "fj", "fil", "fi", "fr", "de", "el", "ht", "he", "hi", "mww", "hu", "is", "id", "it", "ja", "sw", "tlh", "tlh-Qaak", "ko", "lv", "lt", "mg", "ms", "mt", "nb", "fa", "pl", "pt", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk", "sl", "es", "sv", "ty", "ta", "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua" }; private static readonly string HttpsServicePointTemplateUrl = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from={0}&to={1}"; private static readonly Random RandomNumbers = new Random(); private static readonly string[] Accepts = new string[1] { "application/json" }; private static readonly string[] ContentTypes = new string[1] { "application/json" }; private static readonly string Accept = Accepts[RandomNumbers.Next(Accepts.Length)]; private static readonly string ContentType = ContentTypes[RandomNumbers.Next(ContentTypes.Length)]; private string _key; public override string Id => "BingTranslateLegitimate"; public override string FriendlyName => "Bing Translator (Authenticated)"; public override int MaxTranslationsPerRequest => 10; private string FixLanguage(string lang) { switch (lang) { case "zh-CN": case "zh": return "zh-Hans"; case "zh-TW": return "zh-Hant"; default: return lang; } } public override void Initialize(IInitializationContext context) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) _key = context.GetOrCreateSetting<string>("BingLegitimate", "OcpApimSubscriptionKey", ""); if (string.IsNullOrEmpty(_key)) { throw new EndpointInitializationException("The BingTranslateLegitimate endpoint requires an API key which has not been provided."); } context.DisableCertificateChecksFor(new string[1] { "api.cognitive.microsofttranslator.com" }); if (!SupportedLanguages.Contains(FixLanguage(context.SourceLanguage))) { throw new EndpointInitializationException("The source language '" + context.SourceLanguage + "' is not supported."); } if (!SupportedLanguages.Contains(FixLanguage(context.DestinationLanguage))) { throw new EndpointInitializationException("The destination language '" + context.DestinationLanguage + "' is not supported."); } } public override void OnCreateRequest(IHttpRequestCreationContext context) { //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("["); for (int i = 0; i < ((ITranslationContextBase)context).UntranslatedTexts.Length; i++) { string value = JsonHelper.Escape(((ITranslationContextBase)context).UntranslatedTexts[i]); stringBuilder.Append("{\"Text\":\""); stringBuilder.Append(value); stringBuilder.Append("\"}"); if (((ITranslationContextBase)context).UntranslatedTexts.Length - 1 != i) { stringBuilder.Append(","); } } stringBuilder.Append("]"); XUnityWebRequest val = new XUnityWebRequest("POST", string.Format(HttpsServicePointTemplateUrl, FixLanguage(((ITranslationContextBase)context).SourceLanguage), FixLanguage(((ITranslationContextBase)context).DestinationLanguage)), stringBuilder.ToString()); if (Accept != null) { val.Headers[HttpRequestHeader.Accept] = Accept; } if (ContentType != null) { val.Headers[HttpRequestHeader.ContentType] = ContentType; } val.Headers["Ocp-Apim-Subscription-Key"] = _key; context.Complete(val); } public override void OnExtractTranslation(IHttpTranslationExtractionContext context) { JSONArray asArray = JSON.Parse(((IHttpResponseInspectionContext)context).Response.Data).AsArray; List<string> list = new List<string>(); for (int i = 0; i < ((JSONNode)asArray).Count; i++) { JSONNode obj = ((JSONNode)((JSONNode)asArray)[i].AsObject)["translations"]; object obj2; if (obj == null) { obj2 = null; } else { JSONNode obj3 = ((JSONNode)obj.AsArray)[0]; obj2 = ((obj3 != null) ? ((object)((JSONNode)obj3.AsObject)["text"])?.ToString() : null); } string text = (string)obj2; string item = JsonHelper.Unescape(text.Substring(1, text.Length - 2)); list.Add(item); } context.Complete(list.ToArray()); } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/CustomTranslate.dll
Decompiled 4 days agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Endpoints.Http; using XUnity.AutoTranslator.Plugin.Core.Web; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("CustomTranslate")] [assembly: AssemblyTitle("CustomTranslate")] [assembly: AssemblyVersion("5.6.1.0")] namespace CustomTranslate; internal class CustomTranslateEndpoint : HttpEndpoint { private static readonly string ServicePointTemplateUrl = "{0}?from={1}&to={2}&text={3}"; private string _endpoint; private string _friendlyName; private bool _enableShortDelay; private bool _disableSpamChecks; public override string Id => "CustomTranslate"; public override string FriendlyName => _friendlyName; public CustomTranslateEndpoint() { _friendlyName = "Custom"; } public override void Initialize(IInitializationContext context) { //IL_005b: Unknown result type (might be due to invalid IL or missing references) _endpoint = context.GetOrCreateSetting<string>("Custom", "Url", ""); _enableShortDelay = context.GetOrCreateSetting<bool>("Custom", "EnableShortDelay", false); _disableSpamChecks = context.GetOrCreateSetting<bool>("Custom", "DisableSpamChecks", false); if (string.IsNullOrEmpty(_endpoint)) { throw new EndpointInitializationException("The custom endpoint requires a url which has not been provided."); } Uri uri = new Uri(_endpoint); context.DisableCertificateChecksFor(new string[1] { uri.Host }); _friendlyName = _friendlyName + " (" + uri.Host + ")"; if (_enableShortDelay) { context.SetTranslationDelay(0.1f); } if (_disableSpamChecks) { context.DisableSpamChecks(); } } public override void OnCreateRequest(IHttpRequestCreationContext context) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown XUnityWebRequest val = new XUnityWebRequest(string.Format(ServicePointTemplateUrl, _endpoint, ((ITranslationContextBase)context).SourceLanguage, ((ITranslationContextBase)context).DestinationLanguage, Uri.EscapeDataString(((ITranslationContextBase)context).UntranslatedText))); context.Complete(val); } public override void OnExtractTranslation(IHttpTranslationExtractionContext context) { context.Complete(((IHttpResponseInspectionContext)context).Response.Data); } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/DeepLTranslate.dll
Decompiled 4 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Endpoints.ExtProtocol; using XUnity.Common.Logging; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("DeepLTranslate")] [assembly: AssemblyTitle("DeepLTranslate")] [assembly: AssemblyVersion("5.6.1.0")] namespace DeepLTranslate; public class DeepLTranslate : ExtProtocolEndpoint { private const float MinimumMinDelaySeconds = 1f; private const float MinimumMaxDelaySeconds = 3f; private static readonly HashSet<string> SupportedLanguages = new HashSet<string> { "ar", "bg", "cs", "da", "de", "el", "en", "en-gb", "en-us", "es", "et", "fi", "fr", "hu", "id", "it", "ja", "ko", "lt", "lv", "nb", "nl", "pl", "pt", "pt-br", "pt-pt", "ro", "ru", "sk", "sl", "sv", "tr", "uk", "zh", "zh-hans", "zh-hant" }; public override string Id => "DeepLTranslate"; public override string FriendlyName => "DeepL Translator"; public override int MaxConcurrency => 1; public override int MaxTranslationsPerRequest => 25; protected override string ConfigurationSectionName => "DeepL"; private string FixLanguage(string lang) { if (lang == "zh-Hans" || lang == "zh-CN") { return "zh"; } return lang; } public override void Initialize(IInitializationContext context) { //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) ((ExtProtocolEndpoint)this).Initialize(context); ((ExtProtocolEndpoint)this).MinDelay = context.GetOrCreateSetting<float>("DeepL", "MinDelaySeconds", 2f); if (((ExtProtocolEndpoint)this).MinDelay < 1f) { XuaLogger.AutoTranslator.Warn($"[DeepL] Cannot set MinDelaySeconds below {1f} second(s). Setting MinDelaySeconds={1f}"); context.SetSetting<float>("DeepL", "MinDelaySeconds", 1f); } ((ExtProtocolEndpoint)this).MaxDelay = context.GetOrCreateSetting<float>("DeepL", "MaxDelaySeconds", 6f); if (((ExtProtocolEndpoint)this).MaxDelay < 3f) { XuaLogger.AutoTranslator.Warn($"[DeepL] Cannot set MaxDelaySeconds below {3f} second(s). Setting MaxDelaySeconds={3f}"); context.SetSetting<float>("DeepL", "MaxDelaySeconds", 3f); } if (!SupportedLanguages.Contains(FixLanguage(context.SourceLanguage))) { throw new EndpointInitializationException("The source language '" + context.SourceLanguage + "' is not supported."); } if (!SupportedLanguages.Contains(FixLanguage(context.DestinationLanguage))) { throw new EndpointInitializationException("The destination language '" + context.DestinationLanguage + "' is not supported."); } ((ExtProtocolEndpoint)this).Arguments = Convert.ToBase64String(Encoding.UTF8.GetBytes("DeepLTranslate.ExtProtocol.ExtDeepLTranslate, DeepLTranslate.ExtProtocol"), Base64FormattingOptions.None); } } public class DeepLTranslateLegitimate : ExtProtocolEndpoint { private static readonly HashSet<string> SupportedLanguages = new HashSet<string> { "auto", "ar", "bg", "cs", "da", "de", "el", "en", "en-gb", "en-us", "es", "et", "fi", "fr", "hu", "id", "it", "ja", "ko", "lt", "lv", "nb", "nl", "pl", "pt", "pt-br", "pt-pt", "ro", "ru", "sk", "sl", "sv", "tr", "uk", "zh", "zh-hans", "zh-hant" }; public override string Id => "DeepLTranslateLegitimate"; public override string FriendlyName => "DeepL Translator (Authenticated)"; public override int MaxConcurrency => 1; public override int MaxTranslationsPerRequest => 25; protected override string ConfigurationSectionName => "DeepLLegitimate"; private string FixLanguage(string lang) { if (lang == "zh-Hans" || lang == "zh-CN") { return "zh"; } return lang; } public override void Initialize(IInitializationContext context) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) ((ExtProtocolEndpoint)this).Initialize(context); if (!SupportedLanguages.Contains(FixLanguage(context.SourceLanguage))) { throw new EndpointInitializationException("The source language '" + context.SourceLanguage + "' is not supported."); } if (!SupportedLanguages.Contains(FixLanguage(context.DestinationLanguage))) { throw new EndpointInitializationException("The destination language '" + context.DestinationLanguage + "' is not supported."); } string orCreateSetting = context.GetOrCreateSetting<string>(((ExtProtocolEndpoint)this).ConfigurationSectionName, "ApiKey", ""); bool orCreateSetting2 = context.GetOrCreateSetting<bool>(((ExtProtocolEndpoint)this).ConfigurationSectionName, "Free", false); if (string.IsNullOrEmpty(orCreateSetting)) { throw new EndpointInitializationException("The endpoint requires an API key which has not been provided."); } ((ExtProtocolEndpoint)this).ConfigForExternalProcess = string.Join("\n", orCreateSetting, orCreateSetting2.ToString()); ((ExtProtocolEndpoint)this).Arguments = Convert.ToBase64String(Encoding.UTF8.GetBytes("DeepLTranslate.ExtProtocol.ExtDeepLTranslateLegitimate, DeepLTranslate.ExtProtocol"), Base64FormattingOptions.None); } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/ezTransXP.dll
Decompiled 4 days agousing System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using Microsoft.Win32; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Endpoints.ExtProtocol; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("ezTransXP")] [assembly: AssemblyTitle("ezTransXP")] [assembly: AssemblyVersion("5.6.1.0")] namespace ezTransXP; public class ezTransXPEndpoint : ExtProtocolEndpoint { public override string Id => "ezTransXP"; public override string FriendlyName => "ezTransXP"; public override int MaxConcurrency => 1; public override int MaxTranslationsPerRequest => 50; public override void Initialize(IInitializationContext context) { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) string defaultInstallationPath = GetDefaultInstallationPath(); string text = context.GetOrCreateSetting<string>("ezTrans", "InstallationPath", defaultInstallationPath); if (string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(defaultInstallationPath)) { context.SetSetting<string>("ezTrans", "InstallationPath", defaultInstallationPath); text = defaultInstallationPath; } context.DisableSpamChecks(); string text2 = Path.Combine(context.TranslatorDirectory, "FullNET\\ezTransXP.ExtProtocol.exe"); if (!File.Exists(text2)) { throw new EndpointInitializationException("Could not find any executable at '" + text2 + "'"); } ((ExtProtocolEndpoint)this).ExecutablePath = text2; ((ExtProtocolEndpoint)this).Arguments = Convert.ToBase64String(Encoding.UTF8.GetBytes(text)); if (context.SourceLanguage != "ja") { throw new EndpointInitializationException("Current implementation only supports japanese-to-korean."); } if (context.DestinationLanguage != "ko") { throw new EndpointInitializationException("Current implementation only supports japanese-to-korean."); } } public static string GetDefaultInstallationPath() { try { return (string)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\ChangShin\\ezTrans", "FilePath", null); } catch { return null; } } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/FullNET/Common.ExtProtocol.dll
Decompiled 4 days agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Text; using System.Threading.Tasks; using XUnity.AutoTranslator.Plugin.ExtProtocol; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = ".NET Framework 4.5")] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("Common.ExtProtocol")] [assembly: AssemblyTitle("Common.ExtProtocol")] [assembly: AssemblyVersion("5.6.1.0")] namespace SimpleJSON { public enum JSONNodeType { Array = 1, Object = 2, String = 3, Number = 4, NullValue = 5, Boolean = 6, None = 7, Custom = 255 } public enum JSONTextMode { Compact, Indent } public abstract class JSONNode { public struct Enumerator { private enum Type { None, Array, Object } private Type type; private Dictionary<string, JSONNode>.Enumerator m_Object; private List<JSONNode>.Enumerator m_Array; public bool IsValid => type != Type.None; public KeyValuePair<string, JSONNode> Current { get { if (type == Type.Array) { return new KeyValuePair<string, JSONNode>(string.Empty, m_Array.Current); } if (type == Type.Object) { return m_Object.Current; } return new KeyValuePair<string, JSONNode>(string.Empty, null); } } public Enumerator(List<JSONNode>.Enumerator aArrayEnum) { type = Type.Array; m_Object = default(Dictionary<string, JSONNode>.Enumerator); m_Array = aArrayEnum; } public Enumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum) { type = Type.Object; m_Object = aDictEnum; m_Array = default(List<JSONNode>.Enumerator); } public bool MoveNext() { if (type == Type.Array) { return m_Array.MoveNext(); } if (type == Type.Object) { return m_Object.MoveNext(); } return false; } } public struct ValueEnumerator { private Enumerator m_Enumerator; public JSONNode Current => m_Enumerator.Current.Value; public ValueEnumerator(List<JSONNode>.Enumerator aArrayEnum) : this(new Enumerator(aArrayEnum)) { } public ValueEnumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum) : this(new Enumerator(aDictEnum)) { } public ValueEnumerator(Enumerator aEnumerator) { m_Enumerator = aEnumerator; } public bool MoveNext() { return m_Enumerator.MoveNext(); } public ValueEnumerator GetEnumerator() { return this; } } public struct KeyEnumerator { private Enumerator m_Enumerator; public JSONNode Current => m_Enumerator.Current.Key; public KeyEnumerator(List<JSONNode>.Enumerator aArrayEnum) : this(new Enumerator(aArrayEnum)) { } public KeyEnumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum) : this(new Enumerator(aDictEnum)) { } public KeyEnumerator(Enumerator aEnumerator) { m_Enumerator = aEnumerator; } public bool MoveNext() { return m_Enumerator.MoveNext(); } public KeyEnumerator GetEnumerator() { return this; } } public class LinqEnumerator : IEnumerator<KeyValuePair<string, JSONNode>>, IDisposable, IEnumerator, IEnumerable<KeyValuePair<string, JSONNode>>, IEnumerable { private JSONNode m_Node; private Enumerator m_Enumerator; public KeyValuePair<string, JSONNode> Current => m_Enumerator.Current; object IEnumerator.Current => m_Enumerator.Current; internal LinqEnumerator(JSONNode aNode) { m_Node = aNode; if (m_Node != null) { m_Enumerator = m_Node.GetEnumerator(); } } public bool MoveNext() { return m_Enumerator.MoveNext(); } public void Dispose() { m_Node = null; m_Enumerator = default(Enumerator); } public IEnumerator<KeyValuePair<string, JSONNode>> GetEnumerator() { return new LinqEnumerator(m_Node); } public void Reset() { if (m_Node != null) { m_Enumerator = m_Node.GetEnumerator(); } } IEnumerator IEnumerable.GetEnumerator() { return new LinqEnumerator(m_Node); } } [CompilerGenerated] private sealed class <get_Children>d__39 : IEnumerable<JSONNode>, IEnumerable, IEnumerator<JSONNode>, IDisposable, IEnumerator { private int <>1__state; private JSONNode <>2__current; private int <>l__initialThreadId; JSONNode IEnumerator<JSONNode>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <get_Children>d__39(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { if (<>1__state != 0) { return false; } <>1__state = -1; return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<JSONNode> IEnumerable<JSONNode>.GetEnumerator() { if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; return this; } return new <get_Children>d__39(0); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<JSONNode>)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <get_DeepChildren>d__41 : IEnumerable<JSONNode>, IEnumerable, IEnumerator<JSONNode>, IDisposable, IEnumerator { private int <>1__state; private JSONNode <>2__current; private int <>l__initialThreadId; public JSONNode <>4__this; private IEnumerator<JSONNode> <>7__wrap1; private IEnumerator<JSONNode> <>7__wrap2; JSONNode IEnumerator<JSONNode>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <get_DeepChildren>d__41(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if ((uint)(num - -4) <= 1u || num == 1) { try { if (num == -4 || num == 1) { try { } finally { <>m__Finally2(); } } } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>7__wrap2 = null; <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; JSONNode jSONNode = <>4__this; if (num != 0) { if (num != 1) { return false; } <>1__state = -4; goto IL_008d; } <>1__state = -1; <>7__wrap1 = jSONNode.Children.GetEnumerator(); <>1__state = -3; goto IL_00a7; IL_008d: if (<>7__wrap2.MoveNext()) { JSONNode current = <>7__wrap2.Current; <>2__current = current; <>1__state = 1; return true; } <>m__Finally2(); <>7__wrap2 = null; goto IL_00a7; IL_00a7: if (<>7__wrap1.MoveNext()) { JSONNode current2 = <>7__wrap1.Current; <>7__wrap2 = current2.DeepChildren.GetEnumerator(); <>1__state = -4; goto IL_008d; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } private void <>m__Finally2() { <>1__state = -3; if (<>7__wrap2 != null) { <>7__wrap2.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<JSONNode> IEnumerable<JSONNode>.GetEnumerator() { <get_DeepChildren>d__41 result; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; result = this; } else { result = new <get_DeepChildren>d__41(0) { <>4__this = <>4__this }; } return result; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<JSONNode>)this).GetEnumerator(); } } public static bool forceASCII; [ThreadStatic] private static StringBuilder m_EscapeBuilder; public abstract JSONNodeType Tag { get; } public virtual JSONNode this[int aIndex] { get { return null; } set { } } public virtual JSONNode this[string aKey] { get { return null; } set { } } public virtual string Value { get { return ""; } set { } } public virtual int Count => 0; public virtual bool IsNumber => false; public virtual bool IsString => false; public virtual bool IsBoolean => false; public virtual bool IsNull => false; public virtual bool IsArray => false; public virtual bool IsObject => false; public virtual bool Inline { get { return false; } set { } } public virtual IEnumerable<JSONNode> Children { [IteratorStateMachine(typeof(<get_Children>d__39))] get { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <get_Children>d__39(-2); } } public IEnumerable<JSONNode> DeepChildren { [IteratorStateMachine(typeof(<get_DeepChildren>d__41))] get { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <get_DeepChildren>d__41(-2) { <>4__this = this }; } } public IEnumerable<KeyValuePair<string, JSONNode>> Linq => new LinqEnumerator(this); public KeyEnumerator Keys => new KeyEnumerator(GetEnumerator()); public ValueEnumerator Values => new ValueEnumerator(GetEnumerator()); public virtual double AsDouble { get { double result = 0.0; if (double.TryParse(Value, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out result)) { return result; } return 0.0; } set { Value = value.ToString(CultureInfo.InvariantCulture); } } public virtual int AsInt { get { return (int)AsDouble; } set { AsDouble = value; } } public virtual float AsFloat { get { return (float)AsDouble; } set { AsDouble = value; } } public virtual bool AsBool { get { bool result = false; if (bool.TryParse(Value, out result)) { return result; } return !string.IsNullOrEmpty(Value); } set { Value = (value ? "true" : "false"); } } public virtual JSONArray AsArray => this as JSONArray; public virtual JSONObject AsObject => this as JSONObject; internal static StringBuilder EscapeBuilder { get { if (m_EscapeBuilder == null) { m_EscapeBuilder = new StringBuilder(); } return m_EscapeBuilder; } } public virtual void Add(string aKey, JSONNode aItem) { } public virtual void Add(JSONNode aItem) { Add("", aItem); } public virtual JSONNode Remove(string aKey) { return null; } public virtual JSONNode Remove(int aIndex) { return null; } public virtual JSONNode Remove(JSONNode aNode) { return aNode; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); WriteToStringBuilder(stringBuilder, 0, 0, JSONTextMode.Compact); return stringBuilder.ToString(); } public virtual string ToString(int aIndent) { StringBuilder stringBuilder = new StringBuilder(); WriteToStringBuilder(stringBuilder, 0, aIndent, JSONTextMode.Indent); return stringBuilder.ToString(); } internal abstract void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode); public abstract Enumerator GetEnumerator(); public static implicit operator JSONNode(string s) { return new JSONString(s); } public static implicit operator string(JSONNode d) { if (!(d == null)) { return d.Value; } return null; } public static implicit operator JSONNode(double n) { return new JSONNumber(n); } public static implicit operator double(JSONNode d) { if (!(d == null)) { return d.AsDouble; } return 0.0; } public static implicit operator JSONNode(float n) { return new JSONNumber(n); } public static implicit operator float(JSONNode d) { if (!(d == null)) { return d.AsFloat; } return 0f; } public static implicit operator JSONNode(int n) { return new JSONNumber(n); } public static implicit operator int(JSONNode d) { if (!(d == null)) { return d.AsInt; } return 0; } public static implicit operator JSONNode(bool b) { return new JSONBool(b); } public static implicit operator bool(JSONNode d) { if (!(d == null)) { return d.AsBool; } return false; } public static implicit operator JSONNode(KeyValuePair<string, JSONNode> aKeyValue) { return aKeyValue.Value; } public static bool operator ==(JSONNode a, object b) { if ((object)a == b) { return true; } bool flag = a is JSONNull || (object)a == null || a is JSONLazyCreator; bool flag2 = b is JSONNull || b == null || b is JSONLazyCreator; if (flag && flag2) { return true; } if (!flag) { return a.Equals(b); } return false; } public static bool operator !=(JSONNode a, object b) { return !(a == b); } public override bool Equals(object obj) { return (object)this == obj; } public override int GetHashCode() { return base.GetHashCode(); } internal static string Escape(string aText) { StringBuilder escapeBuilder = EscapeBuilder; escapeBuilder.Length = 0; if (escapeBuilder.Capacity < aText.Length + aText.Length / 10) { escapeBuilder.Capacity = aText.Length + aText.Length / 10; } foreach (char c in aText) { switch (c) { case '\\': escapeBuilder.Append("\\\\"); continue; case '"': escapeBuilder.Append("\\\""); continue; case '\n': escapeBuilder.Append("\\n"); continue; case '\r': escapeBuilder.Append("\\r"); continue; case '\t': escapeBuilder.Append("\\t"); continue; case '\b': escapeBuilder.Append("\\b"); continue; case '\f': escapeBuilder.Append("\\f"); continue; } if (c < ' ' || (forceASCII && c > '\u007f')) { ushort num = c; escapeBuilder.Append("\\u").Append(num.ToString("X4")); } else { escapeBuilder.Append(c); } } string result = escapeBuilder.ToString(); escapeBuilder.Length = 0; return result; } private static void ParseElement(JSONNode ctx, string token, string tokenName, bool quoted) { if (quoted) { ctx.Add(tokenName, token); return; } string text = token.ToLower(); switch (text) { case "false": case "true": ctx.Add(tokenName, text == "true"); return; case "null": ctx.Add(tokenName, null); return; } if (double.TryParse(token, out var result)) { ctx.Add(tokenName, result); } else { ctx.Add(tokenName, token); } } public static JSONNode Parse(string aJSON) { Stack<JSONNode> stack = new Stack<JSONNode>(); JSONNode jSONNode = null; int i = 0; StringBuilder stringBuilder = new StringBuilder(); string text = ""; bool flag = false; bool flag2 = false; for (; i < aJSON.Length; i++) { switch (aJSON[i]) { case '{': if (flag) { stringBuilder.Append(aJSON[i]); break; } stack.Push(new JSONObject()); if (jSONNode != null) { jSONNode.Add(text, stack.Peek()); } text = ""; stringBuilder.Length = 0; jSONNode = stack.Peek(); break; case '[': if (flag) { stringBuilder.Append(aJSON[i]); break; } stack.Push(new JSONArray()); if (jSONNode != null) { jSONNode.Add(text, stack.Peek()); } text = ""; stringBuilder.Length = 0; jSONNode = stack.Peek(); break; case ']': case '}': if (flag) { stringBuilder.Append(aJSON[i]); break; } if (stack.Count == 0) { throw new Exception("JSON Parse: Too many closing brackets"); } stack.Pop(); if (stringBuilder.Length > 0 || flag2) { ParseElement(jSONNode, stringBuilder.ToString(), text, flag2); flag2 = false; } text = ""; stringBuilder.Length = 0; if (stack.Count > 0) { jSONNode = stack.Peek(); } break; case ':': if (flag) { stringBuilder.Append(aJSON[i]); break; } text = stringBuilder.ToString(); stringBuilder.Length = 0; flag2 = false; break; case '"': flag = !flag; flag2 = flag2 || flag; break; case ',': if (flag) { stringBuilder.Append(aJSON[i]); break; } if (stringBuilder.Length > 0 || flag2) { ParseElement(jSONNode, stringBuilder.ToString(), text, flag2); flag2 = false; } text = ""; stringBuilder.Length = 0; flag2 = false; break; case '\t': case ' ': if (flag) { stringBuilder.Append(aJSON[i]); } break; case '\\': i++; if (flag) { char c = aJSON[i]; switch (c) { case 't': stringBuilder.Append('\t'); break; case 'r': stringBuilder.Append('\r'); break; case 'n': stringBuilder.Append('\n'); break; case 'b': stringBuilder.Append('\b'); break; case 'f': stringBuilder.Append('\f'); break; case 'u': { string s = aJSON.Substring(i + 1, 4); stringBuilder.Append((char)int.Parse(s, NumberStyles.AllowHexSpecifier)); i += 4; break; } default: stringBuilder.Append(c); break; } } break; default: stringBuilder.Append(aJSON[i]); break; case '\n': case '\r': break; } } if (flag) { throw new Exception("JSON Parse: Quotation marks seems to be messed up."); } return jSONNode; } } public class JSONArray : JSONNode { [CompilerGenerated] private sealed class <get_Children>d__22 : IEnumerable<JSONNode>, IEnumerable, IEnumerator<JSONNode>, IDisposable, IEnumerator { private int <>1__state; private JSONNode <>2__current; private int <>l__initialThreadId; public JSONArray <>4__this; private List<JSONNode>.Enumerator <>7__wrap1; JSONNode IEnumerator<JSONNode>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <get_Children>d__22(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>7__wrap1 = default(List<JSONNode>.Enumerator); <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; JSONArray jSONArray = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = jSONArray.m_List.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (<>7__wrap1.MoveNext()) { JSONNode current = <>7__wrap1.Current; <>2__current = current; <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap1 = default(List<JSONNode>.Enumerator); return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; ((IDisposable)<>7__wrap1).Dispose(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<JSONNode> IEnumerable<JSONNode>.GetEnumerator() { <get_Children>d__22 result; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; result = this; } else { result = new <get_Children>d__22(0) { <>4__this = <>4__this }; } return result; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<JSONNode>)this).GetEnumerator(); } } private List<JSONNode> m_List = new List<JSONNode>(); private bool inline; public override bool Inline { get { return inline; } set { inline = value; } } public override JSONNodeType Tag => JSONNodeType.Array; public override bool IsArray => true; public override JSONNode this[int aIndex] { get { if (aIndex < 0 || aIndex >= m_List.Count) { return new JSONLazyCreator(this); } return m_List[aIndex]; } set { if (value == null) { value = JSONNull.CreateOrGet(); } if (aIndex < 0 || aIndex >= m_List.Count) { m_List.Add(value); } else { m_List[aIndex] = value; } } } public override JSONNode this[string aKey] { get { return new JSONLazyCreator(this); } set { if (value == null) { value = JSONNull.CreateOrGet(); } m_List.Add(value); } } public override int Count => m_List.Count; public override IEnumerable<JSONNode> Children { [IteratorStateMachine(typeof(<get_Children>d__22))] get { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <get_Children>d__22(-2) { <>4__this = this }; } } public override Enumerator GetEnumerator() { return new Enumerator(m_List.GetEnumerator()); } public override void Add(string aKey, JSONNode aItem) { if (aItem == null) { aItem = JSONNull.CreateOrGet(); } m_List.Add(aItem); } public override JSONNode Remove(int aIndex) { if (aIndex < 0 || aIndex >= m_List.Count) { return null; } JSONNode result = m_List[aIndex]; m_List.RemoveAt(aIndex); return result; } public override JSONNode Remove(JSONNode aNode) { m_List.Remove(aNode); return aNode; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append('['); int count = m_List.Count; if (inline) { aMode = JSONTextMode.Compact; } for (int i = 0; i < count; i++) { if (i > 0) { aSB.Append(','); } if (aMode == JSONTextMode.Indent) { aSB.AppendLine(); } if (aMode == JSONTextMode.Indent) { aSB.Append(' ', aIndent + aIndentInc); } m_List[i].WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode); } if (aMode == JSONTextMode.Indent) { aSB.AppendLine().Append(' ', aIndent); } aSB.Append(']'); } } public class JSONObject : JSONNode { [CompilerGenerated] private sealed class <get_Children>d__23 : IEnumerable<JSONNode>, IEnumerable, IEnumerator<JSONNode>, IDisposable, IEnumerator { private int <>1__state; private JSONNode <>2__current; private int <>l__initialThreadId; public JSONObject <>4__this; private Dictionary<string, JSONNode>.Enumerator <>7__wrap1; JSONNode IEnumerator<JSONNode>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <get_Children>d__23(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>7__wrap1 = default(Dictionary<string, JSONNode>.Enumerator); <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; JSONObject jSONObject = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = jSONObject.m_Dict.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (<>7__wrap1.MoveNext()) { <>2__current = <>7__wrap1.Current.Value; <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap1 = default(Dictionary<string, JSONNode>.Enumerator); return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; ((IDisposable)<>7__wrap1).Dispose(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<JSONNode> IEnumerable<JSONNode>.GetEnumerator() { <get_Children>d__23 result; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; result = this; } else { result = new <get_Children>d__23(0) { <>4__this = <>4__this }; } return result; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<JSONNode>)this).GetEnumerator(); } } private Dictionary<string, JSONNode> m_Dict = new Dictionary<string, JSONNode>(); private bool inline; public override bool Inline { get { return inline; } set { inline = value; } } public override JSONNodeType Tag => JSONNodeType.Object; public override bool IsObject => true; public override JSONNode this[string aKey] { get { if (m_Dict.ContainsKey(aKey)) { return m_Dict[aKey]; } return new JSONLazyCreator(this, aKey); } set { if (value == null) { value = JSONNull.CreateOrGet(); } if (m_Dict.ContainsKey(aKey)) { m_Dict[aKey] = value; } else { m_Dict.Add(aKey, value); } } } public override JSONNode this[int aIndex] { get { if (aIndex < 0 || aIndex >= m_Dict.Count) { return null; } return m_Dict.ElementAt(aIndex).Value; } set { if (value == null) { value = JSONNull.CreateOrGet(); } if (aIndex >= 0 && aIndex < m_Dict.Count) { string key = m_Dict.ElementAt(aIndex).Key; m_Dict[key] = value; } } } public override int Count => m_Dict.Count; public override IEnumerable<JSONNode> Children { [IteratorStateMachine(typeof(<get_Children>d__23))] get { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <get_Children>d__23(-2) { <>4__this = this }; } } public override Enumerator GetEnumerator() { return new Enumerator(m_Dict.GetEnumerator()); } public override void Add(string aKey, JSONNode aItem) { if (aItem == null) { aItem = JSONNull.CreateOrGet(); } if (!string.IsNullOrEmpty(aKey)) { if (m_Dict.ContainsKey(aKey)) { m_Dict[aKey] = aItem; } else { m_Dict.Add(aKey, aItem); } } else { m_Dict.Add(Guid.NewGuid().ToString(), aItem); } } public override JSONNode Remove(string aKey) { if (!m_Dict.ContainsKey(aKey)) { return null; } JSONNode result = m_Dict[aKey]; m_Dict.Remove(aKey); return result; } public override JSONNode Remove(int aIndex) { if (aIndex < 0 || aIndex >= m_Dict.Count) { return null; } KeyValuePair<string, JSONNode> keyValuePair = m_Dict.ElementAt(aIndex); m_Dict.Remove(keyValuePair.Key); return keyValuePair.Value; } public override JSONNode Remove(JSONNode aNode) { try { KeyValuePair<string, JSONNode> keyValuePair = m_Dict.Where((KeyValuePair<string, JSONNode> k) => k.Value == aNode).First(); m_Dict.Remove(keyValuePair.Key); return aNode; } catch { return null; } } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append('{'); bool flag = true; if (inline) { aMode = JSONTextMode.Compact; } foreach (KeyValuePair<string, JSONNode> item in m_Dict) { if (!flag) { aSB.Append(','); } flag = false; if (aMode == JSONTextMode.Indent) { aSB.AppendLine(); } if (aMode == JSONTextMode.Indent) { aSB.Append(' ', aIndent + aIndentInc); } aSB.Append('"').Append(JSONNode.Escape(item.Key)).Append('"'); if (aMode == JSONTextMode.Compact) { aSB.Append(':'); } else { aSB.Append(" : "); } item.Value.WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode); } if (aMode == JSONTextMode.Indent) { aSB.AppendLine().Append(' ', aIndent); } aSB.Append('}'); } } public class JSONString : JSONNode { private string m_Data; public override JSONNodeType Tag => JSONNodeType.String; public override bool IsString => true; public override string Value { get { return m_Data; } set { m_Data = value; } } public override Enumerator GetEnumerator() { return default(Enumerator); } public JSONString(string aData) { m_Data = aData; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append('"').Append(JSONNode.Escape(m_Data)).Append('"'); } public override bool Equals(object obj) { if (base.Equals(obj)) { return true; } if (obj is string text) { return m_Data == text; } JSONString jSONString = obj as JSONString; if (jSONString != null) { return m_Data == jSONString.m_Data; } return false; } public override int GetHashCode() { return m_Data.GetHashCode(); } } public class JSONNumber : JSONNode { private double m_Data; public override JSONNodeType Tag => JSONNodeType.Number; public override bool IsNumber => true; public override string Value { get { return m_Data.ToString(CultureInfo.InvariantCulture); } set { if (double.TryParse(value, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var result)) { m_Data = result; } } } public override double AsDouble { get { return m_Data; } set { m_Data = value; } } public override Enumerator GetEnumerator() { return default(Enumerator); } public JSONNumber(double aData) { m_Data = aData; } public JSONNumber(string aData) { Value = aData; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append(m_Data); } private static bool IsNumeric(object value) { if (!(value is int) && !(value is uint) && !(value is float) && !(value is double) && !(value is decimal) && !(value is long) && !(value is ulong) && !(value is short) && !(value is ushort) && !(value is sbyte)) { return value is byte; } return true; } public override bool Equals(object obj) { if (obj == null) { return false; } if (base.Equals(obj)) { return true; } JSONNumber jSONNumber = obj as JSONNumber; if (jSONNumber != null) { return m_Data == jSONNumber.m_Data; } if (IsNumeric(obj)) { return Convert.ToDouble(obj) == m_Data; } return false; } public override int GetHashCode() { return m_Data.GetHashCode(); } } public class JSONBool : JSONNode { private bool m_Data; public override JSONNodeType Tag => JSONNodeType.Boolean; public override bool IsBoolean => true; public override string Value { get { return m_Data.ToString(); } set { if (bool.TryParse(value, out var result)) { m_Data = result; } } } public override bool AsBool { get { return m_Data; } set { m_Data = value; } } public override Enumerator GetEnumerator() { return default(Enumerator); } public JSONBool(bool aData) { m_Data = aData; } public JSONBool(string aData) { Value = aData; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append(m_Data ? "true" : "false"); } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is bool) { return m_Data == (bool)obj; } return false; } public override int GetHashCode() { return m_Data.GetHashCode(); } } public class JSONNull : JSONNode { private static JSONNull m_StaticInstance = new JSONNull(); public static bool reuseSameInstance = true; public override JSONNodeType Tag => JSONNodeType.NullValue; public override bool IsNull => true; public override string Value { get { return "null"; } set { } } public override bool AsBool { get { return false; } set { } } public static JSONNull CreateOrGet() { if (reuseSameInstance) { return m_StaticInstance; } return new JSONNull(); } private JSONNull() { } public override Enumerator GetEnumerator() { return default(Enumerator); } public override bool Equals(object obj) { if ((object)this == obj) { return true; } return obj is JSONNull; } public override int GetHashCode() { return 0; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append("null"); } } internal class JSONLazyCreator : JSONNode { private JSONNode m_Node; private string m_Key; public override JSONNodeType Tag => JSONNodeType.None; public override JSONNode this[int aIndex] { get { return new JSONLazyCreator(this); } set { JSONArray jSONArray = new JSONArray(); jSONArray.Add(value); Set(jSONArray); } } public override JSONNode this[string aKey] { get { return new JSONLazyCreator(this, aKey); } set { JSONObject jSONObject = new JSONObject(); jSONObject.Add(aKey, value); Set(jSONObject); } } public override int AsInt { get { JSONNumber aVal = new JSONNumber(0.0); Set(aVal); return 0; } set { JSONNumber aVal = new JSONNumber(value); Set(aVal); } } public override float AsFloat { get { JSONNumber aVal = new JSONNumber(0.0); Set(aVal); return 0f; } set { JSONNumber aVal = new JSONNumber(value); Set(aVal); } } public override double AsDouble { get { JSONNumber aVal = new JSONNumber(0.0); Set(aVal); return 0.0; } set { JSONNumber aVal = new JSONNumber(value); Set(aVal); } } public override bool AsBool { get { JSONBool aVal = new JSONBool(aData: false); Set(aVal); return false; } set { JSONBool aVal = new JSONBool(value); Set(aVal); } } public override JSONArray AsArray { get { JSONArray jSONArray = new JSONArray(); Set(jSONArray); return jSONArray; } } public override JSONObject AsObject { get { JSONObject jSONObject = new JSONObject(); Set(jSONObject); return jSONObject; } } public override Enumerator GetEnumerator() { return default(Enumerator); } public JSONLazyCreator(JSONNode aNode) { m_Node = aNode; m_Key = null; } public JSONLazyCreator(JSONNode aNode, string aKey) { m_Node = aNode; m_Key = aKey; } private void Set(JSONNode aVal) { if (m_Key == null) { m_Node.Add(aVal); } else { m_Node.Add(m_Key, aVal); } m_Node = null; } public override void Add(JSONNode aItem) { JSONArray jSONArray = new JSONArray(); jSONArray.Add(aItem); Set(jSONArray); } public override void Add(string aKey, JSONNode aItem) { JSONObject jSONObject = new JSONObject(); jSONObject.Add(aKey, aItem); Set(jSONObject); } public static bool operator ==(JSONLazyCreator a, object b) { if (b == null) { return true; } return (object)a == b; } public static bool operator !=(JSONLazyCreator a, object b) { return !(a == b); } public override bool Equals(object obj) { if (obj == null) { return true; } return (object)this == obj; } public override int GetHashCode() { return 0; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append("null"); } } public static class JSON { public static JSONNode Parse(string aJSON) { return JSONNode.Parse(aJSON); } } } namespace Common.ExtProtocol { public interface IExtTranslateEndpoint { Task Translate(ITranslationContext context); void Initialize(string config); } public interface ITranslationContext : ITranslationContextBase { void Complete(string translatedText); void Complete(string[] translatedTexts); } public interface ITranslationContextBase { string UntranslatedText { get; } string[] UntranslatedTexts { get; } UntranslatedTextInfo UntranslatedTextInfo { get; } UntranslatedTextInfo[] UntranslatedTextInfos { get; } string SourceLanguage { get; } string DestinationLanguage { get; } object UserState { get; set; } void Fail(string reason, Exception exception); void Fail(string reason); } public class TranslationContext : ITranslationContext, ITranslationContextBase { private string[] _untranslatedTexts; public string UntranslatedText => UntranslatedTexts[0]; public string[] UntranslatedTexts => _untranslatedTexts ?? (_untranslatedTexts = UntranslatedTextInfos.Select((UntranslatedTextInfo x) => x.UntranslatedText).ToArray()); public UntranslatedTextInfo UntranslatedTextInfo => UntranslatedTextInfos[0]; public UntranslatedTextInfo[] UntranslatedTextInfos { get; } public string SourceLanguage { get; } public string DestinationLanguage { get; } internal bool IsDone { get; private set; } public string[] TranslatedTexts { get; private set; } public string ErrorMessage { get; private set; } public Exception Error { get; private set; } public object UserState { get; set; } public TranslationContext(TransmittableUntranslatedTextInfo[] untranslatedTexts, string sourceLanguage, string destinationLanguage) { UntranslatedTextInfos = untranslatedTexts.Select((TransmittableUntranslatedTextInfo x) => new UntranslatedTextInfo(x)).ToArray(); SourceLanguage = sourceLanguage; DestinationLanguage = destinationLanguage; } public void Complete(string translatedText) { Complete(new string[1] { translatedText }); } public void Complete(string[] translatedTexts) { if (IsDone) { return; } try { if (translatedTexts.Length == 0) { FailContext("Received empty translation from translator.", null); return; } for (int i = 0; i < translatedTexts.Length; i++) { if (string.IsNullOrEmpty(translatedTexts[0])) { FailContext("Received empty translation from translator.", null); return; } } CompleteContext(translatedTexts); } finally { IsDone = true; } } public void Fail(string reason, Exception exception) { if (IsDone) { return; } try { FailContext(reason, exception); throw new TranslationContextException(); } finally { IsDone = true; } } public void Fail(string reason) { if (IsDone) { return; } try { FailContext(reason, null); throw new TranslationContextException(); } finally { IsDone = true; } } public void FailWithoutThrowing(string reason, Exception exception) { if (IsDone) { return; } try { FailContext(reason, exception); } finally { IsDone = true; } } internal void FailIfNotCompleted() { if (!IsDone) { FailWithoutThrowing("The translation request was not completed before returning from translator.", null); } } public void FailContext(string reason, Exception exception) { ErrorMessage = reason; Error = exception; } public void CompleteContext(string[] translatedTexts) { TranslatedTexts = translatedTexts; } } [Serializable] internal class TranslationContextException : Exception { public TranslationContextException() { } public TranslationContextException(string message) : base(message) { } public TranslationContextException(string message, Exception inner) : base(message, inner) { } protected TranslationContextException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class UntranslatedTextInfo { public string[] ContextBefore { get; } public string UntranslatedText { get; } public string[] ContextAfter { get; } public UntranslatedTextInfo(TransmittableUntranslatedTextInfo untranslatedTextInfo) { ContextBefore = untranslatedTextInfo.ContextBefore; UntranslatedText = untranslatedTextInfo.UntranslatedText; ContextAfter = untranslatedTextInfo.ContextAfter; } public UntranslatedTextInfo(string[] contextBefore, string untranslatedText, string[] contextAfter) { ContextBefore = contextBefore; UntranslatedText = untranslatedText; ContextAfter = contextAfter; } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; } } namespace Common.ExtProtocol.Utilities { public static class JsonHelper { public static string Unescape(string str) { if (str == null) { return null; } StringBuilder stringBuilder = new StringBuilder(str); bool flag = false; for (int i = 0; i < stringBuilder.Length; i++) { char c = stringBuilder[i]; if (flag) { bool flag2 = true; char c2 = '\0'; switch (c) { case 'b': c2 = '\b'; break; case 'f': c2 = '\f'; break; case 'n': c2 = '\n'; break; case 'r': c2 = '\r'; break; case 't': c2 = '\t'; break; case '"': c2 = '"'; break; case '\\': c2 = '\\'; break; case 'u': c2 = 'u'; break; default: flag2 = false; break; } if (flag2) { if (c2 == 'u') { char value = (char)int.Parse(new string(new char[4] { stringBuilder[i + 1], stringBuilder[i + 2], stringBuilder[i + 3], stringBuilder[i + 4] }), NumberStyles.HexNumber); stringBuilder.Remove(--i, 6); stringBuilder.Insert(i, value); } else { stringBuilder.Remove(--i, 2); stringBuilder.Insert(i, c2); } } flag = false; } else if (c == '\\') { flag = true; } } return stringBuilder.ToString(); } public static string Escape(string str) { if (str == null || str.Length == 0) { return ""; } int length = str.Length; StringBuilder stringBuilder = new StringBuilder(length + 4); for (int i = 0; i < length; i++) { char c = str[i]; switch (c) { case '"': case '\\': stringBuilder.Append('\\'); stringBuilder.Append(c); break; case '\b': stringBuilder.Append("\\b"); break; case '\t': stringBuilder.Append("\\t"); break; case '\n': stringBuilder.Append("\\n"); break; case '\f': stringBuilder.Append("\\f"); break; case '\r': stringBuilder.Append("\\r"); break; case '\u0085': stringBuilder.Append("\\u0085"); break; case '\u2028': stringBuilder.Append("\\u2028"); break; case '\u2029': stringBuilder.Append("\\u2029"); break; default: stringBuilder.Append(c); break; } } return stringBuilder.ToString(); } } public static class StringBuilderExtensions { public static bool EndsWithWhitespaceOrNewline(this StringBuilder builder) { if (builder.Length == 0) { return true; } char c = builder[builder.Length - 1]; if (!char.IsWhiteSpace(c)) { return c == '\n'; } return true; } } }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/FullNET/DeepLTranslate.ExtProtocol.dll
Decompiled 4 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Common.ExtProtocol; using Common.ExtProtocol.Utilities; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using SimpleJSON; [assembly: AssemblyProduct("DeepLTranslate.ExtProtocol")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = ".NET Framework 4.5")] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: CompilationRelaxations(8)] [assembly: AssemblyTitle("DeepLTranslate.ExtProtocol")] [assembly: AssemblyVersion("5.6.1.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] [CompilerGenerated] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace DeepLTranslate.ExtProtocol { [Serializable] public class BlockedException : Exception { public BlockedException() { } public BlockedException(string message) : base(message) { } public BlockedException(string message, Exception inner) : base(message, inner) { } protected BlockedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public static class HttpResponseMessageExtensions { public static void ThrowIfBlocked(this HttpResponseMessage msg) { if (msg.StatusCode == HttpStatusCode.TooManyRequests) { throw new BlockedException("Too many requests!"); } } } public class ExtDeepLTranslate : IExtTranslateEndpoint { private class UntranslatedTextInfo { public string UntranslatedText { get; set; } public List<TranslationPart> TranslationParts { get; set; } } public class TranslationPart { public bool IsTranslatable { get; set; } public string Value { get; set; } } private static readonly Regex NewlineSplitter; private static readonly DateTime Epoch; private static readonly string HttpsServicePointTemplateUrl; private static readonly string HttpsTranslateUserSite; private static readonly string HttpsTranslateStateSetup; private static readonly Random RandomNumbers; private static readonly string[] Accepts; private static readonly string[] AcceptLanguages; private static readonly string[] Referers; private static readonly string[] Origins; private static readonly string Accept; private static readonly string AcceptLanguage; private static readonly string Referer; private static readonly string Origin; private SemaphoreSlim _sem; private HttpClient _client; private HttpClientHandler _handler; private bool _hasSetup; private int _translationCount; private int _resetAfter = RandomNumbers.Next(75, 125); private long _id; static ExtDeepLTranslate() { NewlineSplitter = new Regex("([\\s]*[\\r\\n]+[\\s]*)"); Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); HttpsServicePointTemplateUrl = "https://www2.deepl.com/jsonrpc"; HttpsTranslateUserSite = "https://www.deepl.com/translator"; HttpsTranslateStateSetup = "https://w.deepl.com/web?request_type=jsonrpc&il=en&method=getClientState"; RandomNumbers = new Random(); Accepts = new string[1] { "*/*" }; AcceptLanguages = new string[4] { null, "en-US,en;q=0.9", "en-US", "en" }; Referers = new string[1] { "https://www.deepl.com/translator" }; Origins = new string[1] { "https://www.deepl.com" }; Accept = Accepts[RandomNumbers.Next(Accepts.Length)]; AcceptLanguage = AcceptLanguages[RandomNumbers.Next(AcceptLanguages.Length)]; Referer = Referers[RandomNumbers.Next(Referers.Length)]; Origin = Origins[RandomNumbers.Next(Origins.Length)]; ServicePointManager.SecurityProtocol |= SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } public ExtDeepLTranslate() { _sem = new SemaphoreSlim(1, 1); } public void Initialize(string config) { } public void Reset() { _hasSetup = false; } private void CreateClientAndHandler() { if (_client != null) { _client.Dispose(); } _handler = new HttpClientHandler(); _handler.CookieContainer = new CookieContainer(); _handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; _client = new HttpClient(_handler, disposeHandler: true); _client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"); } private static string FixLanguage(string lang) { if (lang == "zh-Hans" || lang == "zh-CN") { return "zh"; } return lang; } public async Task EnsureSetupState() { if (!_hasSetup || _translationCount % _resetAfter == 0) { _resetAfter = RandomNumbers.Next(75, 125); _hasSetup = true; _id = 10000 * (long)(10000.0 * RandomNumbers.NextDouble()); CreateClientAndHandler(); await SetupState(); } } public async Task SetupState() { _translationCount = 0; await RequestWebsite(); await GetClientState(); } private void AddHeaders(HttpRequestMessage request, HttpContent content, bool isTranslationRequest) { if (AcceptLanguage != null) { request.Headers.TryAddWithoutValidation("Accept-Language", AcceptLanguage); } if (Accept != null) { request.Headers.TryAddWithoutValidation("Accept", Accept); } if (Referer != null && isTranslationRequest) { request.Headers.TryAddWithoutValidation("Referer", Referer); } if (Origin != null && isTranslationRequest) { request.Headers.TryAddWithoutValidation("Origin", Origin); } if (isTranslationRequest && content != null) { content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); } request.Headers.TryAddWithoutValidation("DNT", "1"); } public async Task Translate(ITranslationContext context) { _ = 3; try { await _sem.WaitAsync(); await EnsureSetupState(); _translationCount++; _id++; long num = (long)(DateTime.UtcNow - Epoch).TotalMilliseconds; long num2 = 1L; StringBuìlder stringBuìlder = new StringBuìlder(); stringBuìlder.Append("{\"jsonrpc\":\"2.0\",\"method\":\"LMT_handle_jobs\",\"params\":{\"jobs\":["); List<UntranslatedTextInfo> untranslatedTextInfos = new List<UntranslatedTextInfo>(); UntranslatedTextInfo[] untranslatedTextInfos2 = ((ITranslationContextBase)context).UntranslatedTextInfos; foreach (UntranslatedTextInfo val in untranslatedTextInfos2) { List<TranslationPart> list = (from x in NewlineSplitter.Split(val.UntranslatedText) select new TranslationPart { Value = x, IsTranslatable = !NewlineSplitter.IsMatch(x) }).ToList(); string[] array = (from x in list where x.IsTranslatable select x.Value).ToArray(); for (int j = 0; j < array.Length; j++) { string text = array[j]; stringBuìlder.Append("{\"kind\":\"default\",\"preferred_num_beams\":1,\"raw_en_sentence\":\""); stringBuìlder.Append(JsonHelper.Escape(text)); HashSet<string> hashSet = new HashSet<string>(); stringBuìlder.Append("\",\"raw_en_context_before\":["); bool flag = false; string[] contextBefore = val.ContextBefore; foreach (string text2 in contextBefore) { if (!hashSet.Contains(text2)) { stringBuìlder.Append("\""); stringBuìlder.Append(JsonHelper.Escape(text2)); stringBuìlder.Append("\""); stringBuìlder.Append(","); flag = true; } } for (int l = 0; l < j; l++) { if (!hashSet.Contains(array[l])) { stringBuìlder.Append("\""); stringBuìlder.Append(JsonHelper.Escape(array[l])); stringBuìlder.Append("\""); stringBuìlder.Append(","); flag = true; } } if (flag) { stringBuìlder.Remove(stringBuìlder.Length - 1, 1); } stringBuìlder.Append("],\"raw_en_context_after\":["); bool flag2 = false; for (int m = j + 1; m < array.Length; m++) { if (!hashSet.Contains(array[m])) { stringBuìlder.Append("\""); stringBuìlder.Append(JsonHelper.Escape(array[m])); stringBuìlder.Append("\""); stringBuìlder.Append(","); flag2 = true; } } contextBefore = val.ContextAfter; foreach (string text3 in contextBefore) { if (!hashSet.Contains(text3)) { stringBuìlder.Append("\""); stringBuìlder.Append(JsonHelper.Escape(text3)); stringBuìlder.Append("\""); stringBuìlder.Append(","); flag2 = true; } } if (flag2) { stringBuìlder.Remove(stringBuìlder.Length - 1, 1); } stringBuìlder.Append("]},"); num2 += text.Count((char c) => c == 'i'); } untranslatedTextInfos.Add(new UntranslatedTextInfo { TranslationParts = list, UntranslatedText = val.UntranslatedText }); } stringBuìlder.Remove(stringBuìlder.Length - 1, 1); long num3 = num + (num2 - num % num2); stringBuìlder.Append("],\"lang\":{\"user_preferred_langs\":[\""); stringBuìlder.Append(FixLanguage(((ITranslationContextBase)context).DestinationLanguage).ToUpperInvariant()); stringBuìlder.Append("\",\""); stringBuìlder.Append(FixLanguage(((ITranslationContextBase)context).SourceLanguage).ToUpperInvariant()); stringBuìlder.Append("\"],\"source_lang_user_selected\":\""); stringBuìlder.Append(FixLanguage(((ITranslationContextBase)context).SourceLanguage).ToUpperInvariant()); stringBuìlder.Append("\",\"target_lang\":\""); stringBuìlder.Append(FixLanguage(((ITranslationContextBase)context).DestinationLanguage).ToUpperInvariant()); stringBuìlder.Append("\"},\"priority\":-1,\"timestamp\":"); stringBuìlder.Append(num3.ToString(CultureInfo.InvariantCulture)); stringBuìlder.Append("},\"id\":"); stringBuìlder.Append(_id); stringBuìlder.Append("}"); StringContent content = new StringContent(stringBuìlder.ToString()); using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, HttpsServicePointTemplateUrl); AddHeaders(request, content, isTranslationRequest: true); using HttpResponseMessage response = await _client.PostAsync(HttpsServicePointTemplateUrl, content); response.ThrowIfBlocked(); response.EnsureSuccessStatusCode(); ExtractTranslation(await response.Content.ReadAsStringAsync(), untranslatedTextInfos, context); } catch (BlockedException innerException) { Reset(); throw new Exception("Request was blocked, and reset used", innerException); } finally { _sem.Release(); } } private void ExtractTranslation(string data, List<UntranslatedTextInfo> untranslatedTextInfos, ITranslationContext context) { JSONArray asArray = JSON.Parse(data)["result"]["translations"].AsArray; List<string> list = new List<string>(); int num = 0; for (int i = 0; i < untranslatedTextInfos.Count; i++) { List<TranslationPart> translationParts = untranslatedTextInfos[i].TranslationParts; StringBuilder stringBuilder = new StringBuilder(); foreach (TranslationPart item in translationParts) { if (item.IsTranslatable) { JSONArray asArray2 = ((JSONNode)asArray)[num++]["beams"].AsArray; if (((JSONNode)asArray2).Count > 0) { string text = ((object)((JSONNode)asArray2)[0]["postprocessed_sentence"]).ToString(); string value = JsonHelper.Unescape(text.Substring(1, text.Length - 2)); stringBuilder.Append(value); } } else { stringBuilder.Append(item.Value); } } string text2 = stringBuilder.ToString(); if (string.IsNullOrWhiteSpace(text2)) { throw new Exception("Found no valid translations in beam!"); } list.Add(text2); } context.Complete(list.ToArray()); } public async Task RequestWebsite() { using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, HttpsTranslateUserSite); AddHeaders(request, null, isTranslationRequest: false); using HttpResponseMessage response = await _client.SendAsync(request); response.ThrowIfBlocked(); response.EnsureSuccessStatusCode(); await response.Content.ReadAsStringAsync(); } public async Task GetClientState() { _id++; StringBuìlder stringBuìlder = new StringBuìlder(); stringBuìlder.Append("{\"jsonrpc\":\"2.0\",\"method\":\"getClientState\",\"params\":{\"v\":\"20180814\"},\"id\":"); stringBuìlder.Append(_id); stringBuìlder.Append("}"); StringContent content = new StringContent(stringBuìlder.ToString()); using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, HttpsTranslateStateSetup); AddHeaders(request, content, isTranslationRequest: true); using HttpResponseMessage response = await _client.PostAsync(HttpsTranslateStateSetup, content); response.ThrowIfBlocked(); response.EnsureSuccessStatusCode(); await response.Content.ReadAsStringAsync(); } public void Dispose() { _client?.Dispose(); } } public class ExtDeepLTranslateLegitimate : IExtTranslateEndpoint { private class UntranslatedTextInfo { public string UntranslatedText { get; set; } public List<TranslationPart> TranslationParts { get; set; } } public class TranslationPart { public bool IsTranslatable { get; set; } public string Value { get; set; } } private class TranslationResponse { public List<Translation> translations { get; set; } } private class Translation { public string detected_source_language { get; set; } public string text { get; set; } } private string _httpsServicePointTemplateUrl = "https://api.deepl.com/v2/translate"; private HttpClient _client; private HttpClientHandler _handler; private string _apiKey; static ExtDeepLTranslateLegitimate() { ServicePointManager.SecurityProtocol |= SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } public ExtDeepLTranslateLegitimate() { CreateClientAndHandler(); } public void Initialize(string config) { string[] array = config.Split(new char[1] { '\n' }, StringSplitOptions.None); _apiKey = array[0]; if (string.Equals(array[1], "true", StringComparison.OrdinalIgnoreCase)) { _httpsServicePointTemplateUrl = "https://api-free.deepl.com/v2/translate"; } else { _httpsServicePointTemplateUrl = "https://api.deepl.com/v2/translate"; } } private void CreateClientAndHandler() { if (_client != null) { _client.Dispose(); } _handler = new HttpClientHandler(); _handler.CookieContainer = new CookieContainer(); _handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; _client = new HttpClient(_handler, disposeHandler: true); _client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("XUnity", "5.6.1")); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*")); } private static string FixLanguage(string lang) { if (lang == "zh-Hans" || lang == "zh-CN") { return "zh"; } return lang; } public async Task Translate(ITranslationContext context) { List<UntranslatedTextInfo> untranslatedTextInfos = new List<UntranslatedTextInfo>(); List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>(); if (!string.Equals(((ITranslationContextBase)context).SourceLanguage, "auto", StringComparison.OrdinalIgnoreCase)) { list.Add(new KeyValuePair<string, string>("source_lang", FixLanguage(((ITranslationContextBase)context).SourceLanguage).ToUpperInvariant())); } list.Add(new KeyValuePair<string, string>("target_lang", FixLanguage(((ITranslationContextBase)context).DestinationLanguage).ToUpperInvariant())); list.Add(new KeyValuePair<string, string>("split_sentences", "1")); UntranslatedTextInfo[] untranslatedTextInfos2 = ((ITranslationContextBase)context).UntranslatedTextInfos; foreach (UntranslatedTextInfo val in untranslatedTextInfos2) { list.Add(new KeyValuePair<string, string>("text", val.UntranslatedText)); untranslatedTextInfos.Add(new UntranslatedTextInfo { TranslationParts = new List<TranslationPart> { new TranslationPart { IsTranslatable = true, Value = val.UntranslatedText } }, UntranslatedText = val.UntranslatedText }); } FormUrlEncodedContent content = new FormUrlEncodedContent(list); using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, _httpsServicePointTemplateUrl); request.Headers.Add("Authorization", "DeepL-Auth-Key " + _apiKey); request.Content = content; using HttpResponseMessage response = await _client.SendAsync(request); response.ThrowIfBlocked(); response.EnsureSuccessStatusCode(); ExtractTranslation(await response.Content.ReadAsStringAsync(), untranslatedTextInfos, context); } private void ExtractTranslation(string data, List<UntranslatedTextInfo> untranslatedTextInfos, ITranslationContext context) { TranslationResponse translationResponse = JsonConvert.DeserializeObject<TranslationResponse>(data); List<string> list = new List<string>(); int num = 0; for (int i = 0; i < untranslatedTextInfos.Count; i++) { List<TranslationPart> translationParts = untranslatedTextInfos[i].TranslationParts; StringBuilder stringBuilder = new StringBuilder(); foreach (TranslationPart item in translationParts) { if (item.IsTranslatable) { string text = translationResponse.translations[num++].text; stringBuilder.Append(text); } else { stringBuilder.Append(item.Value); } } string text2 = stringBuilder.ToString(); if (string.IsNullOrWhiteSpace(text2)) { throw new Exception("Found no valid translations in beam!"); } list.Add(text2); } context.Complete(list.ToArray()); } public void Dispose() { _client?.Dispose(); } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; } } namespace System.Text { internal class StringBuìlder { private StringBuilder _builder; private long _l; public int Length => _builder.Length; public StringBuìlder() { _builder = new StringBuilder(); } public StringBuìlder Append(string str) { _builder.Append(str); return this; } public StringBuìlder Append(char c) { _builder.Append(c); return this; } public StringBuìlder Append(int i) { _builder.Append(i); return this; } public StringBuìlder Append(long l) { _builder.Append(l); _l = l; return this; } public StringBuìlder Remove(int startIndex, int length) { _builder.Remove(startIndex, length); return this; } public override string ToString() { return _builder.ToString().Replace("hod\":\"", ((_l + 3) % 13 == 0L || (_l + 5) % 29 == 0L) ? "hod\" : \"" : "hod\": \""); } } }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/FullNET/GoogleTranslateCompat.ExtProtocol.dll
Decompiled 4 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading.Tasks; using Common.ExtProtocol; using Common.ExtProtocol.Utilities; using Http.ExtProtocol; using SimpleJSON; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = ".NET Framework 4.5")] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("GoogleTranslateCompat.ExtProtocol")] [assembly: AssemblyTitle("GoogleTranslateCompat.ExtProtocol")] [assembly: AssemblyVersion("5.6.1.0")] namespace GoogleTranslateCompat.ExtProtocol; internal class GoogleTranslateCompatTranslate : ExtHttpEndpoint { public static readonly string UserAgent_Chrome_Win10_Latest = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"; private static readonly string HttpsServicePointTranslateTemplateUrl = "https://translate.googleapis.com/translate_a/single?client=webapp&sl={0}&tl={1}&dt=t&tk={2}&q={3}"; private static readonly string HttpsTranslateUserSite = "https://translate.google.com"; private static readonly Random RandomNumbers = new Random(); private static readonly string[] Accepts = new string[3] { null, "*/*", "application/json" }; private static readonly string[] AcceptLanguages = new string[4] { null, "en-US,en;q=0.9", "en-US", "en" }; private static readonly string[] Referers = new string[2] { null, "https://translate.google.com/" }; private static readonly string[] AcceptCharsets = new string[2] { null, Encoding.UTF8.WebName }; private static readonly string Accept = Accepts[RandomNumbers.Next(Accepts.Length)]; private static readonly string AcceptLanguage = AcceptLanguages[RandomNumbers.Next(AcceptLanguages.Length)]; private static readonly string Referer = Referers[RandomNumbers.Next(Referers.Length)]; private static readonly string AcceptCharset = AcceptCharsets[RandomNumbers.Next(AcceptCharsets.Length)]; private CookieContainer _cookieContainer; private bool _hasSetup; private long m = 427761L; private long s = 1179739010L; private int _translationCount; private int _resetAfter = RandomNumbers.Next(75, 125); public GoogleTranslateCompatTranslate() { _cookieContainer = new CookieContainer(); } private string FixLanguage(string lang) { switch (lang) { case "zh-Hans": case "zh": return "zh-CN"; case "zh-Hant": return "zh-TW"; default: return lang; } } public override async Task OnBeforeTranslate(IHttpTranslationContext context) { if (!_hasSetup || _translationCount % _resetAfter == 0) { _resetAfter = RandomNumbers.Next(75, 125); _translationCount = 1; _hasSetup = true; await SetupTKK(); } } public override void OnCreateRequest(IHttpRequestCreationContext context) { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Expected O, but got Unknown _translationCount++; string text = string.Join("\n", ((ITranslationContextBase)context).UntranslatedTexts); XUnityWebRequest val = new XUnityWebRequest(string.Format(HttpsServicePointTranslateTemplateUrl, FixLanguage(((ITranslationContextBase)context).SourceLanguage), FixLanguage(((ITranslationContextBase)context).DestinationLanguage), Tk(text), Uri.EscapeDataString(text))); val.Cookies = _cookieContainer; AddHeaders(val, isTranslationRequest: true); context.Complete(val); } public override void OnInspectResponse(IHttpResponseInspectionContext context) { InspectResponse(context.Response); } public override void OnExtractTranslation(IHttpTranslationExtractionContext context) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) string data = ((IHttpResponseInspectionContext)context).Response.Data; JSONNode val = JSON.Parse(data); StringBuilder stringBuilder = new StringBuilder(data.Length); val = ((JSONNode)val.AsArray)[0]; if (val.IsNull) { context.Complete(((ITranslationContextBase)context).UntranslatedText); return; } Enumerator enumerator = ((JSONNode)val.AsArray).GetEnumerator(); while (((Enumerator)(ref enumerator)).MoveNext()) { string text = ((object)((JSONNode)JSONNode.op_Implicit(((Enumerator)(ref enumerator)).Current).AsArray)[0]).ToString(); text = JsonHelper.Unescape(text.Substring(1, text.Length - 2)); if (!StringBuilderExtensions.EndsWithWhitespaceOrNewline(stringBuilder)) { stringBuilder.Append('\n'); } stringBuilder.Append(text); } string text2 = stringBuilder.ToString(); if (((ITranslationContextBase)context).UntranslatedTexts.Length == 1) { context.Complete(text2); return; } string[] array = text2.Split(new char[1] { '\n' }); List<string> list = new List<string>(); int num = 0; string[] untranslatedTexts = ((ITranslationContextBase)context).UntranslatedTexts; for (int i = 0; i < untranslatedTexts.Length; i++) { int num2 = untranslatedTexts[i].Split(new char[1] { '\n' }).Length; string text3 = string.Empty; for (int j = 0; j < num2; j++) { if (num >= array.Length) { ((ITranslationContextBase)context).Fail("Batch operation received incorrect number of translations."); } string text4 = array[num++]; text3 += text4; if (j != num2 - 1) { text3 += "\n"; } } list.Add(text3); } if (num != array.Length) { ((ITranslationContextBase)context).Fail("Batch operation received incorrect number of translations."); } context.Complete(list.ToArray()); } private XUnityWebRequest CreateWebSiteRequest() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown XUnityWebRequest val = new XUnityWebRequest(HttpsTranslateUserSite); val.Cookies = _cookieContainer; AddHeaders(val, isTranslationRequest: false); return val; } private void AddHeaders(XUnityWebRequest request, bool isTranslationRequest) { request.Headers[HttpRequestHeader.UserAgent] = UserAgent_Chrome_Win10_Latest; if (AcceptLanguage != null) { request.Headers[HttpRequestHeader.AcceptLanguage] = AcceptLanguage; } if (Accept != null) { request.Headers[HttpRequestHeader.Accept] = Accept; } if (Referer != null && isTranslationRequest) { request.Headers[HttpRequestHeader.Referer] = Referer; } if (AcceptCharset != null) { request.Headers[HttpRequestHeader.AcceptCharset] = AcceptCharset; } } private void InspectResponse(XUnityWebResponse response) { CookieCollection newCookies = response.NewCookies; foreach (Cookie item in newCookies) { item.Domain = ".googleapis.com"; } _cookieContainer.Add(newCookies); } public async Task SetupTKK() { _cookieContainer = new CookieContainer(); XUnityWebResponse val3; try { XUnityWebClient val = new XUnityWebClient(); XUnityWebRequest val2 = CreateWebSiteRequest(); val3 = await val.SendAsync(val2); } catch (Exception) { return; } if (val3.Error != null || val3.Data == null) { return; } InspectResponse(val3); try { string data = val3.Data; string[] array = new string[2] { "tkk:'", "TKK='" }; foreach (string text in array) { int num = data.IndexOf(text, StringComparison.Ordinal); if (num > -1) { int num2 = num + text.Length; int num3 = data.IndexOf('\'', num2); string[] array2 = data.Substring(num2, num3 - num2).Split(new char[1] { '.' }); if (array2.Length == 2) { m = long.Parse(array2[0]); s = long.Parse(array2[1]); break; } } } } catch (Exception) { } } private long Vi(long r, string o) { for (int i = 0; i < o.Length; i += 3) { long num = o[i + 2]; num = ((num >= 97) ? (num - 87) : (num - 48)); num = (('+' == o[i + 1]) ? (r >> (int)num) : (r << (int)num)); r = (('+' == o[i]) ? ((r + num) & 0xFFFFFFFFu) : (r ^ num)); } return r; } private string Tk(string r) { List<long> list = new List<long>(); for (int i = 0; i < r.Length; i++) { long num = r[i]; if (128 > num) { list.Add(num); continue; } if (2048 > num) { list.Add((num >> 6) | 0xC0); } else if (55296 == (0xFC00 & num) && i + 1 < r.Length && 56320 == (0xFC00 & r[i + 1])) { num = 65536 + ((0x3FF & num) << 10) + (0x3FF & r[++i]); list.Add((num >> 18) | 0xF0); list.Add(((num >> 12) & 0x3F) | 0x80); } else { list.Add((num >> 12) | 0xE0); list.Add(((num >> 6) & 0x3F) | 0x80); } list.Add((0x3F & num) | 0x80); } long num2 = m; for (int j = 0; j < list.Count; j++) { num2 += list[j]; num2 = Vi(num2, "+-a^+6"); } num2 = Vi(num2, "+-3^+b+-f"); num2 ^= s; if (0 > num2) { num2 = (0x7FFFFFFF & num2) + 2147483648u; } num2 %= 1000000; return num2.ToString(CultureInfo.InvariantCulture) + "." + (num2 ^ m).ToString(CultureInfo.InvariantCulture); } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/FullNET/Http.ExtProtocol.dll
Decompiled 4 days agousing System; using System.Diagnostics; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading.Tasks; using Common.ExtProtocol; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = ".NET Framework 4.5")] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("Http.ExtProtocol")] [assembly: AssemblyTitle("Http.ExtProtocol")] [assembly: AssemblyVersion("5.6.1.0")] namespace Http.ExtProtocol; public abstract class ExtHttpEndpoint : IExtTranslateEndpoint { public virtual void Initialize(string config) { } public virtual Task OnBeforeTranslate(IHttpTranslationContext context) { return null; } public abstract void OnCreateRequest(IHttpRequestCreationContext context); public virtual void OnInspectResponse(IHttpResponseInspectionContext context) { } public abstract void OnExtractTranslation(IHttpTranslationExtractionContext context); public async Task Translate(ITranslationContext context) { HttpTranslationContext httpContext = new HttpTranslationContext(context); await OnBeforeTranslate(httpContext); OnCreateRequest(httpContext); if (httpContext.Request == null) { httpContext.Fail("No request object was provided by the translator."); } XUnityWebResponse xUnityWebResponse2 = (httpContext.Response = await new XUnityWebClient().SendAsync(httpContext.Request)); OnInspectResponse(httpContext); if (xUnityWebResponse2.Error != null) { httpContext.Fail("Error occurred while retrieving translation.", xUnityWebResponse2.Error); } if (xUnityWebResponse2.Data == null) { httpContext.Fail("Error occurred while retrieving translation. Nothing was returned."); } OnExtractTranslation(httpContext); } } internal class HttpTranslationContext : IHttpTranslationContext, ITranslationContextBase, IHttpRequestCreationContext, IHttpResponseInspectionContext, IHttpTranslationExtractionContext { private readonly ITranslationContext _context; public string UntranslatedText => ((ITranslationContextBase)_context).UntranslatedText; public string[] UntranslatedTexts => ((ITranslationContextBase)_context).UntranslatedTexts; public UntranslatedTextInfo UntranslatedTextInfo => ((ITranslationContextBase)_context).UntranslatedTextInfo; public UntranslatedTextInfo[] UntranslatedTextInfos => ((ITranslationContextBase)_context).UntranslatedTextInfos; public string SourceLanguage => ((ITranslationContextBase)_context).SourceLanguage; public string DestinationLanguage => ((ITranslationContextBase)_context).DestinationLanguage; public XUnityWebResponse Response { get; internal set; } public XUnityWebRequest Request { get; internal set; } public object UserState { get { return ((ITranslationContextBase)_context).UserState; } set { ((ITranslationContextBase)_context).UserState = value; } } internal HttpTranslationContext(ITranslationContext context) { _context = context; } public void Fail(string reason, Exception exception) { ((ITranslationContextBase)_context).Fail(reason, exception); } public void Fail(string reason) { ((ITranslationContextBase)_context).Fail(reason); } void IHttpRequestCreationContext.Complete(XUnityWebRequest request) { Request = request; } void IHttpTranslationExtractionContext.Complete(string translatedText) { _context.Complete(translatedText); } void IHttpTranslationExtractionContext.Complete(string[] translatedTexts) { _context.Complete(translatedTexts); } } public interface IHttpRequestCreationContext : IHttpTranslationContext, ITranslationContextBase { void Complete(XUnityWebRequest request); } public interface IHttpResponseInspectionContext : IHttpTranslationContext, ITranslationContextBase { XUnityWebRequest Request { get; } XUnityWebResponse Response { get; } } public interface IHttpTranslationContext : ITranslationContextBase { } public interface IHttpTranslationExtractionContext : IHttpResponseInspectionContext, IHttpTranslationContext, ITranslationContextBase { void Complete(string translatedText); void Complete(string[] translatedTexts); } public static class UserAgents { public static readonly string Chrome_Win10_Latest = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"; public static readonly string Chrome_Win7_Latest = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"; public static readonly string Firefox_Win10_Latest = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0"; public static readonly string Edge_Win10_Latest = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763"; } public class XUnityWebClient : WebClient { private HttpStatusCode? _responseCode; private CookieCollection _responseCookies; private CookieContainer _requestCookies; private WebHeaderCollection _requestHeaders; public XUnityWebClient() { base.Encoding = System.Text.Encoding.UTF8; } protected override WebRequest GetWebRequest(Uri address) { WebRequest webRequest = base.GetWebRequest(address); SetRequestVariables(webRequest); return webRequest; } protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result) { WebResponse webResponse = base.GetWebResponse(request, result); SetResponseVariables(webResponse); return webResponse; } protected override WebResponse GetWebResponse(WebRequest request) { WebResponse webResponse = base.GetWebResponse(request); SetResponseVariables(webResponse); return webResponse; } private void SetRequestVariables(WebRequest r) { if (r is HttpWebRequest httpWebRequest) { if (_requestCookies != null) { httpWebRequest.CookieContainer = _requestCookies; } if (_requestHeaders != null) { base.Headers = _requestHeaders; } httpWebRequest.ReadWriteTimeout = 50000; httpWebRequest.Timeout = 55000; } } private void SetResponseVariables(WebResponse r) { if (r is HttpWebResponse httpWebResponse) { _responseCode = httpWebResponse.StatusCode; _responseCookies = httpWebResponse.Cookies; } } public async Task<XUnityWebResponse> SendAsync(XUnityWebRequest request) { XUnityWebResponse response = new XUnityWebResponse(); _requestCookies = request.Cookies; _requestHeaders = request.Headers; if (request.Data == null) { Exception error2 = null; string result2 = null; try { result2 = await DownloadStringTaskAsync(request.Address); } catch (Exception ex) { error2 = ex; } response.SetCompleted(_responseCode.Value, result2, base.ResponseHeaders, _responseCookies, error2); } else { Exception error2 = null; string result2 = null; try { result2 = await UploadStringTaskAsync(request.Address, request.Method, request.Data); } catch (Exception ex2) { error2 = ex2; } response.SetCompleted(_responseCode.Value, result2, base.ResponseHeaders, _responseCookies, error2); } return response; } } public class XUnityWebRequest { private WebHeaderCollection _headers; public string Method { get; private set; } public Uri Address { get; private set; } public string Data { get; private set; } public CookieContainer Cookies { get; set; } public WebHeaderCollection Headers { get { if (_headers == null) { _headers = new WebHeaderCollection(); } return _headers; } set { _headers = value; } } public XUnityWebRequest(string method, string address, string data) { Method = method; Address = new Uri(address); Data = data; } public XUnityWebRequest(string method, string address) { Method = method; Address = new Uri(address); Data = string.Empty; } public XUnityWebRequest(string address) { Method = "GET"; Address = new Uri(address); } } public class XUnityWebResponse { public HttpStatusCode Code { get; private set; } public string Data { get; private set; } public WebHeaderCollection Headers { get; private set; } public CookieCollection NewCookies { get; private set; } public Exception Error { get; private set; } internal bool IsCompleted { get; private set; } internal void SetCompleted(HttpStatusCode code, string data, WebHeaderCollection headers, CookieCollection newCookies, Exception error) { IsCompleted = true; Code = code; Data = data; Headers = headers; NewCookies = newCookies; Error = error; } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/FullNET/Newtonsoft.Json.dll
Decompiled 4 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Newtonsoft.Json.Bson; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq.JsonPath; using Newtonsoft.Json.Schema; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AllowPartiallyTrustedCallers] [assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("9ca358aa-317b-4925-8ada-4a29e943a363")] [assembly: CLSCompliant(true)] [assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = ".NET Framework 4.5")] [assembly: AssemblyCompany("Newtonsoft")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © James Newton-King 2008")] [assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")] [assembly: AssemblyFileVersion("13.0.1.25517")] [assembly: AssemblyInformationalVersion("13.0.1+ae9fe44e1323e91bcbd185ca1a14099fba7c021f")] [assembly: AssemblyProduct("Json.NET")] [assembly: AssemblyTitle("Json.NET")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/JamesNK/Newtonsoft.Json")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("13.0.0.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [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; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } } namespace Newtonsoft.Json { public enum ConstructorHandling { Default, AllowNonPublicDefaultConstructor } public enum DateFormatHandling { IsoDateFormat, MicrosoftDateFormat } public enum DateParseHandling { None, DateTime, DateTimeOffset } public enum DateTimeZoneHandling { Local, Utc, Unspecified, RoundtripKind } public class DefaultJsonNameTable : JsonNameTable { private class Entry { internal readonly string Value; internal readonly int HashCode; internal Entry Next; internal Entry(string value, int hashCode, Entry next) { Value = value; HashCode = hashCode; Next = next; } } private static readonly int HashCodeRandomizer; private int _count; private Entry[] _entries; private int _mask = 31; static DefaultJsonNameTable() { HashCodeRandomizer = Environment.TickCount; } public DefaultJsonNameTable() { _entries = new Entry[_mask + 1]; } public override string? Get(char[] key, int start, int length) { if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; num += (num << 7) ^ key[start]; int num2 = start + length; for (int i = start + 1; i < num2; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; int num3 = num & _mask; for (Entry entry = _entries[num3]; entry != null; entry = entry.Next) { if (entry.HashCode == num && TextEquals(entry.Value, key, start, length)) { return entry.Value; } } return null; } public string Add(string key) { if (key == null) { throw new ArgumentNullException("key"); } int length = key.Length; if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; for (int i = 0; i < key.Length; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; for (Entry entry = _entries[num & _mask]; entry != null; entry = entry.Next) { if (entry.HashCode == num && entry.Value.Equals(key, StringComparison.Ordinal)) { return entry.Value; } } return AddEntry(key, num); } private string AddEntry(string str, int hashCode) { int num = hashCode & _mask; Entry entry = new Entry(str, hashCode, _entries[num]); _entries[num] = entry; if (_count++ == _mask) { Grow(); } return entry.Value; } private void Grow() { Entry[] entries = _entries; int num = _mask * 2 + 1; Entry[] array = new Entry[num + 1]; for (int i = 0; i < entries.Length; i++) { Entry entry = entries[i]; while (entry != null) { int num2 = entry.HashCode & num; Entry next = entry.Next; entry.Next = array[num2]; array[num2] = entry; entry = next; } } _entries = array; _mask = num; } private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length) { if (str1.Length != str2Length) { return false; } for (int i = 0; i < str1.Length; i++) { if (str1[i] != str2[str2Start + i]) { return false; } } return true; } } [Flags] public enum DefaultValueHandling { Include = 0, Ignore = 1, Populate = 2, IgnoreAndPopulate = 3 } public enum FloatFormatHandling { String, Symbol, DefaultValue } public enum FloatParseHandling { Double, Decimal } public enum Formatting { None, Indented } public interface IArrayPool<T> { T[] Rent(int minimumLength); void Return(T[]? array); } public interface IJsonLineInfo { int LineNumber { get; } int LinePosition { get; } bool HasLineInfo(); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonArrayAttribute : JsonContainerAttribute { private bool _allowNullItems; public bool AllowNullItems { get { return _allowNullItems; } set { _allowNullItems = value; } } public JsonArrayAttribute() { } public JsonArrayAttribute(bool allowNullItems) { _allowNullItems = allowNullItems; } public JsonArrayAttribute(string id) : base(id) { } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)] public sealed class JsonConstructorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public abstract class JsonContainerAttribute : Attribute { internal bool? _isReference; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; private Type? _namingStrategyType; private object[]? _namingStrategyParameters; public string? Id { get; set; } public string? Title { get; set; } public string? Description { get; set; } public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get { return _namingStrategyType; } set { _namingStrategyType = value; NamingStrategyInstance = null; } } public object[]? NamingStrategyParameters { get { return _namingStrategyParameters; } set { _namingStrategyParameters = value; NamingStrategyInstance = null; } } internal NamingStrategy? NamingStrategyInstance { get; set; } public bool IsReference { get { return _isReference.GetValueOrDefault(); } set { _isReference = value; } } public bool ItemIsReference { get { return _itemIsReference.GetValueOrDefault(); } set { _itemIsReference = value; } } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } protected JsonContainerAttribute() { } protected JsonContainerAttribute(string id) { Id = id; } } public static class JsonConvert { public static readonly string True = "true"; public static readonly string False = "false"; public static readonly string Null = "null"; public static readonly string Undefined = "undefined"; public static readonly string PositiveInfinity = "Infinity"; public static readonly string NegativeInfinity = "-Infinity"; public static readonly string NaN = "NaN"; public static Func<JsonSerializerSettings>? DefaultSettings { get; set; } public static string ToString(DateTime value) { return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); } public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) { DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling); using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(DateTimeOffset value) { return ToString(value, DateFormatHandling.IsoDateFormat); } public static string ToString(DateTimeOffset value, DateFormatHandling format) { using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(bool value) { if (!value) { return False; } return True; } public static string ToString(char value) { return ToString(char.ToString(value)); } public static string ToString(Enum value) { return value.ToString("D"); } public static string ToString(int value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(short value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ushort value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(uint value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(long value) { return value.ToString(null, CultureInfo.InvariantCulture); } private static string ToStringInternal(BigInteger value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ulong value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(float value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value))) { return text; } if (floatFormatHandling == FloatFormatHandling.DefaultValue) { if (nullable) { return Null; } return "0.0"; } return quoteChar + text + quoteChar; } public static string ToString(double value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureDecimalPlace(double value, string text) { if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1) { return text; } return text + ".0"; } private static string EnsureDecimalPlace(string text) { if (text.IndexOf('.') != -1) { return text; } return text + ".0"; } public static string ToString(byte value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(sbyte value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(decimal value) { return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture)); } public static string ToString(Guid value) { return ToString(value, '"'); } internal static string ToString(Guid value, char quoteChar) { string text = value.ToString("D", CultureInfo.InvariantCulture); string text2 = quoteChar.ToString(CultureInfo.InvariantCulture); return text2 + text + text2; } public static string ToString(TimeSpan value) { return ToString(value, '"'); } internal static string ToString(TimeSpan value, char quoteChar) { return ToString(value.ToString(), quoteChar); } public static string ToString(Uri? value) { if (value == null) { return Null; } return ToString(value, '"'); } internal static string ToString(Uri value, char quoteChar) { return ToString(value.OriginalString, quoteChar); } public static string ToString(string? value) { return ToString(value, '"'); } public static string ToString(string? value, char delimiter) { return ToString(value, delimiter, StringEscapeHandling.Default); } public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling) { if (delimiter != '"' && delimiter != '\'') { throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter"); } return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling); } public static string ToString(object? value) { if (value == null) { return Null; } return ConvertUtils.GetTypeCode(value.GetType()) switch { PrimitiveTypeCode.String => ToString((string)value), PrimitiveTypeCode.Char => ToString((char)value), PrimitiveTypeCode.Boolean => ToString((bool)value), PrimitiveTypeCode.SByte => ToString((sbyte)value), PrimitiveTypeCode.Int16 => ToString((short)value), PrimitiveTypeCode.UInt16 => ToString((ushort)value), PrimitiveTypeCode.Int32 => ToString((int)value), PrimitiveTypeCode.Byte => ToString((byte)value), PrimitiveTypeCode.UInt32 => ToString((uint)value), PrimitiveTypeCode.Int64 => ToString((long)value), PrimitiveTypeCode.UInt64 => ToString((ulong)value), PrimitiveTypeCode.Single => ToString((float)value), PrimitiveTypeCode.Double => ToString((double)value), PrimitiveTypeCode.DateTime => ToString((DateTime)value), PrimitiveTypeCode.Decimal => ToString((decimal)value), PrimitiveTypeCode.DBNull => Null, PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), PrimitiveTypeCode.Guid => ToString((Guid)value), PrimitiveTypeCode.Uri => ToString((Uri)value), PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), PrimitiveTypeCode.BigInteger => ToStringInternal((BigInteger)value), _ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), }; } [DebuggerStepThrough] public static string SerializeObject(object? value) { return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting) { return SerializeObject(value, formatting, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, JsonSerializerSettings? settings) { return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); return SerializeObjectInternal(value, type, jsonSerializer); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings) { return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); jsonSerializer.Formatting = formatting; return SerializeObjectInternal(value, type, jsonSerializer); } private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer) { StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture); using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter)) { jsonTextWriter.Formatting = jsonSerializer.Formatting; jsonSerializer.Serialize(jsonTextWriter, value, type); } return stringWriter.ToString(); } [DebuggerStepThrough] public static object? DeserializeObject(string value) { return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static object? DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type) { return DeserializeObject(value, type, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value) { return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject) { return DeserializeObject<T>(value); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject<T>(value, settings); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, params JsonConverter[] converters) { return (T)DeserializeObject(value, typeof(T), converters); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings) { return (T)DeserializeObject(value, typeof(T), settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return DeserializeObject(value, type, settings); } public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings) { ValidationUtils.ArgumentNotNull(value, "value"); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); if (!jsonSerializer.IsCheckAdditionalContentSet()) { jsonSerializer.CheckAdditionalContent = true; } using JsonTextReader reader = new JsonTextReader(new StringReader(value)); return jsonSerializer.Deserialize(reader, type); } [DebuggerStepThrough] public static void PopulateObject(string value, object target) { PopulateObject(value, target, null); } public static void PopulateObject(string value, object target, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); using JsonReader jsonReader = new JsonTextReader(new StringReader(value)); jsonSerializer.Populate(jsonReader, target); if (settings == null || !settings.CheckAdditionalContent) { return; } while (jsonReader.Read()) { if (jsonReader.TokenType != JsonToken.Comment) { throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object."); } } } public static string SerializeXmlNode(XmlNode? node) { return SerializeXmlNode(node, Formatting.None); } public static string SerializeXmlNode(XmlNode? node, Formatting formatting) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); return SerializeObject(node, formatting, xmlNodeConverter); } public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } public static XmlDocument? DeserializeXmlNode(string value) { return DeserializeXmlNode(value, null); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute: false); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName; xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute; xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters; return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), xmlNodeConverter); } public static string SerializeXNode(XObject? node) { return SerializeXNode(node, Formatting.None); } public static string SerializeXNode(XObject? node, Formatting formatting) { return SerializeXNode(node, formatting, omitRootObject: false); } public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } public static XDocument? DeserializeXNode(string value) { return DeserializeXNode(value, null); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute: false); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName; xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute; xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters; return (XDocument)DeserializeObject(value, typeof(XDocument), xmlNodeConverter); } } public abstract class JsonConverter { public virtual bool CanRead => true; public virtual bool CanWrite => true; public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer); public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer); public abstract bool CanConvert(Type objectType); } public abstract class JsonConverter<T> : JsonConverter { public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (!((value != null) ? (value is T) : ReflectionUtils.IsNullable(typeof(T)))) { throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } WriteJson(writer, (T)value, serializer); } public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer); public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { bool flag = existingValue == null; if (!flag && !(existingValue is T)) { throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } return ReadJson(reader, objectType, flag ? default(T) : ((T)existingValue), !flag, serializer); } public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer); public sealed override bool CanConvert(Type objectType) { return typeof(T).IsAssignableFrom(objectType); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonConverterAttribute : Attribute { private readonly Type _converterType; public Type ConverterType => _converterType; public object[]? ConverterParameters { get; } public JsonConverterAttribute(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } _converterType = converterType; } public JsonConverterAttribute(Type converterType, params object[] converterParameters) : this(converterType) { ConverterParameters = converterParameters; } } public class JsonConverterCollection : Collection<JsonConverter> { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonDictionaryAttribute : JsonContainerAttribute { public JsonDictionaryAttribute() { } public JsonDictionaryAttribute(string id) : base(id) { } } [Serializable] public class JsonException : Exception { public JsonException() { } public JsonException(string message) : base(message) { } public JsonException(string message, Exception? innerException) : base(message, innerException) { } public JsonException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message) { message = JsonPosition.FormatMessage(lineInfo, path, message); return new JsonException(message); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class JsonExtensionDataAttribute : Attribute { public bool WriteData { get; set; } public bool ReadData { get; set; } public JsonExtensionDataAttribute() { WriteData = true; ReadData = true; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonIgnoreAttribute : Attribute { } public abstract class JsonNameTable { public abstract string? Get(char[] key, int start, int length); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonObjectAttribute : JsonContainerAttribute { private MemberSerialization _memberSerialization; internal MissingMemberHandling? _missingMemberHandling; internal Required? _itemRequired; internal NullValueHandling? _itemNullValueHandling; public MemberSerialization MemberSerialization { get { return _memberSerialization; } set { _memberSerialization = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public NullValueHandling ItemNullValueHandling { get { return _itemNullValueHandling.GetValueOrDefault(); } set { _itemNullValueHandling = value; } } public Required ItemRequired { get { return _itemRequired.GetValueOrDefault(); } set { _itemRequired = value; } } public JsonObjectAttribute() { } public JsonObjectAttribute(MemberSerialization memberSerialization) { MemberSerialization = memberSerialization; } public JsonObjectAttribute(string id) : base(id) { } } internal enum JsonContainerType { None, Object, Array, Constructor } internal struct JsonPosition { private static readonly char[] SpecialCharacters = new char[18] { '.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t', '\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029' }; internal JsonContainerType Type; internal int Position; internal string? PropertyName; internal bool HasIndex; public JsonPosition(JsonContainerType type) { Type = type; HasIndex = TypeHasIndex(type); Position = -1; PropertyName = null; } internal int CalculateLength() { switch (Type) { case JsonContainerType.Object: return PropertyName.Length + 5; case JsonContainerType.Array: case JsonContainerType.Constructor: return MathUtils.IntLength((ulong)Position) + 2; default: throw new ArgumentOutOfRangeException("Type"); } } internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer) { switch (Type) { case JsonContainerType.Object: { string propertyName = PropertyName; if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append("['"); if (writer == null) { writer = new StringWriter(sb); } JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', appendDelimiters: false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer); sb.Append("']"); } else { if (sb.Length > 0) { sb.Append('.'); } sb.Append(propertyName); } break; } case JsonContainerType.Array: case JsonContainerType.Constructor: sb.Append('['); sb.Append(Position); sb.Append(']'); break; } } internal static bool TypeHasIndex(JsonContainerType type) { if (type != JsonContainerType.Array) { return type == JsonContainerType.Constructor; } return true; } internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition) { int num = 0; if (positions != null) { for (int i = 0; i < positions.Count; i++) { num += positions[i].CalculateLength(); } } if (currentPosition.HasValue) { num += currentPosition.GetValueOrDefault().CalculateLength(); } StringBuilder stringBuilder = new StringBuilder(num); StringWriter writer = null; char[] buffer = null; if (positions != null) { foreach (JsonPosition position in positions) { position.WriteTo(stringBuilder, ref writer, ref buffer); } } currentPosition?.WriteTo(stringBuilder, ref writer, ref buffer); return stringBuilder.ToString(); } internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message) { if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { message = message.Trim(); if (!StringUtils.EndsWith(message, '.')) { message += "."; } message += " "; } message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path); if (lineInfo != null && lineInfo.HasLineInfo()) { message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition); } message += "."; return message; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonPropertyAttribute : Attribute { internal NullValueHandling? _nullValueHandling; internal DefaultValueHandling? _defaultValueHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal ObjectCreationHandling? _objectCreationHandling; internal TypeNameHandling? _typeNameHandling; internal bool? _isReference; internal int? _order; internal Required? _required; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get; set; } public object[]? NamingStrategyParameters { get; set; } public NullValueHandling NullValueHandling { get { return _nullValueHandling.GetValueOrDefault(); } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling.GetValueOrDefault(); } set { _defaultValueHandling = value; } } public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling.GetValueOrDefault(); } set { _referenceLoopHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling.GetValueOrDefault(); } set { _objectCreationHandling = value; } } public TypeNameHandling TypeNameHandling { get { return _typeNameHandling.GetValueOrDefault(); } set { _typeNameHandling = value; } } public bool IsReference { get { return _isReference.GetValueOrDefault(); } set { _isReference = value; } } public int Order { get { return _order.GetValueOrDefault(); } set { _order = value; } } public Required Required { get { return _required.GetValueOrDefault(); } set { _required = value; } } public string? PropertyName { get; set; } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } public bool ItemIsReference { get { return _itemIsReference.GetValueOrDefault(); } set { _itemIsReference = value; } } public JsonPropertyAttribute() { } public JsonPropertyAttribute(string propertyName) { PropertyName = propertyName; } } public abstract class JsonReader : IDisposable { protected internal enum State { Start, Complete, Property, ObjectStart, Object, ArrayStart, Array, Closed, PostValue, ConstructorStart, Constructor, Error, Finished } private JsonToken _tokenType; private object? _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; private CultureInfo? _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string? _dateFormatString; private List<JsonPosition>? _stack; protected State CurrentState => _currentState; public bool CloseInput { get; set; } public bool SupportMultipleContent { get; set; } public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException("value"); } _dateTimeZoneHandling = value; } } public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset) { throw new ArgumentOutOfRangeException("value"); } _dateParseHandling = value; } } public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal) { throw new ArgumentOutOfRangeException("value"); } _floatParseHandling = value; } } public string? DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; } } public virtual JsonToken TokenType => _tokenType; public virtual object? Value => _value; public virtual Type? ValueType => _value?.GetType(); public virtual int Depth { get { int num = _stack?.Count ?? 0; if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) { return num; } return num + 1; } } public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null); return JsonPosition.BuildPath(_stack, currentPosition); } } public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } public virtual Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<bool>() ?? Read().ToAsync(); } public async Task SkipAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (TokenType == JsonToken.PropertyName) { await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false) && depth < Depth) { } } } internal async Task ReaderReadAndAssertAsync(CancellationToken cancellationToken) { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { throw CreateUnexpectedEndException(); } } public virtual Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<bool?>() ?? Task.FromResult(ReadAsBoolean()); } public virtual Task<byte[]?> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<byte[]>() ?? Task.FromResult(ReadAsBytes()); } internal async Task<byte[]?> ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken) { List<byte> buffer = new List<byte>(); do { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { SetToken(JsonToken.None); } } while (!ReadArrayElementIntoByteArrayReportDone(buffer)); byte[] array = buffer.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } public virtual Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<DateTime?>() ?? Task.FromResult(ReadAsDateTime()); } public virtual Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<DateTimeOffset?>() ?? Task.FromResult(ReadAsDateTimeOffset()); } public virtual Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<decimal?>() ?? Task.FromResult(ReadAsDecimal()); } public virtual Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken)) { return Task.FromResult(ReadAsDouble()); } public virtual Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<int?>() ?? Task.FromResult(ReadAsInt32()); } public virtual Task<string?> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<string>() ?? Task.FromResult(ReadAsString()); } internal async Task<bool> ReadAndMoveToContentAsync(CancellationToken cancellationToken) { bool flag = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (flag) { flag = await MoveToContentAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } return flag; } internal Task<bool> MoveToContentAsync(CancellationToken cancellationToken) { JsonToken tokenType = TokenType; if (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { return MoveToContentFromNonContentAsync(cancellationToken); } return AsyncUtils.True; } private async Task<bool> MoveToContentFromNonContentAsync(CancellationToken cancellationToken) { JsonToken tokenType; do { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { return false; } tokenType = TokenType; } while (tokenType == JsonToken.None || tokenType == JsonToken.Comment); return true; } internal JsonPosition GetPosition(int depth) { if (_stack != null && depth < _stack.Count) { return _stack[depth]; } return _currentPosition; } protected JsonReader() { _currentState = State.Start; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; _maxDepth = 64; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); return; } if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); if (!_maxDepth.HasValue || !(Depth + 1 > _maxDepth) || _hasExceededMaxDepth) { return; } _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } private JsonContainerType Pop() { JsonPosition currentPosition; if (_stack != null && _stack.Count > 0) { currentPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { currentPosition = _currentPosition; _currentPosition = default(JsonPosition); } if (_maxDepth.HasValue && Depth <= _maxDepth) { _hasExceededMaxDepth = false; } return currentPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } public abstract bool Read(); public virtual int? ReadAsInt32() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is int) { return (int)value; } int num; if (value is BigInteger bigInteger) { num = (int)bigInteger; } else { try { num = Convert.ToInt32(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } } SetToken(JsonToken.Integer, num, updateIndex: false); return num; } case JsonToken.String: { string s = (string)Value; return ReadInt32String(s); } default: throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal int? ReadInt32String(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (int.TryParse(s, NumberStyles.Integer, Culture, out var result)) { SetToken(JsonToken.Integer, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual string? ReadAsString() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.String: return (string)Value; default: if (JsonTokenUtils.IsPrimitiveToken(contentToken)) { object value = Value; if (value != null) { string text = ((!(value is IFormattable formattable)) ? ((value is Uri uri) ? uri.OriginalString : value.ToString()) : formattable.ToString(null, Culture)); SetToken(JsonToken.String, text, updateIndex: false); return text; } } throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } public virtual byte[]? ReadAsBytes() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.StartObject: { ReadIntoWrappedTypeObject(); byte[] array2 = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, array2, updateIndex: false); return array2; } case JsonToken.String: { string text = (string)Value; Guid g; byte[] array3 = ((text.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray())); SetToken(JsonToken.Bytes, array3, updateIndex: false); return array3; } case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Bytes: if (Value is Guid guid) { byte[] array = guid.ToByteArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } return (byte[])Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); default: throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal byte[] ReadArrayIntoByteArray() { List<byte> list = new List<byte>(); do { if (!Read()) { SetToken(JsonToken.None); } } while (!ReadArrayElementIntoByteArrayReportDone(list)); byte[] array = list.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer) { switch (TokenType) { case JsonToken.None: throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); case JsonToken.Integer: buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); return false; case JsonToken.EndArray: return true; case JsonToken.Comment: return false; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } public virtual double? ReadAsDouble() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is double) { return (double)value; } double num = ((!(value is BigInteger bigInteger)) ? Convert.ToDouble(value, CultureInfo.InvariantCulture) : ((double)bigInteger)); SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDoubleString((string)Value); default: throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal double? ReadDoubleString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual bool? ReadAsBoolean() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { bool flag = ((!(Value is BigInteger bigInteger)) ? Convert.ToBoolean(Value, CultureInfo.InvariantCulture) : (bigInteger != 0L)); SetToken(JsonToken.Boolean, flag, updateIndex: false); return flag; } case JsonToken.String: return ReadBooleanString((string)Value); case JsonToken.Boolean: return (bool)Value; default: throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal bool? ReadBooleanString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (bool.TryParse(s, out var result)) { SetToken(JsonToken.Boolean, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual decimal? ReadAsDecimal() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is decimal) { return (decimal)value; } decimal num; if (value is BigInteger bigInteger) { num = (decimal)bigInteger; } else { try { num = Convert.ToDecimal(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } } SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDecimalString((string)Value); default: throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal decimal? ReadDecimalString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out result) == ParseResult.Success) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTime? ReadAsDateTime() { switch (GetContentToken()) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTimeOffset dateTimeOffset) { SetToken(JsonToken.Date, dateTimeOffset.DateTime, updateIndex: false); } return (DateTime)Value; case JsonToken.String: return ReadDateTimeString((string)Value); default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } internal DateTime? ReadDateTimeString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTimeOffset? ReadAsDateTimeOffset() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTime dateTime) { SetToken(JsonToken.Date, new DateTimeOffset(dateTime), updateIndex: false); } return (DateTimeOffset)Value; case JsonToken.String: { string s = (string)Value; return ReadDateTimeOffsetString(s); } default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal DateTimeOffset? ReadDateTimeOffsetString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } internal void ReaderReadAndAssert() { if (!Read()) { throw CreateUnexpectedEndException(); } } internal JsonReaderException CreateUnexpectedEndException() { return JsonReaderException.Create(this, "Unexpected end when reading JSON."); } internal void ReadIntoWrappedTypeObject() { ReaderReadAndAssert(); if (Value != null && Value.ToString() == "$type") { ReaderReadAndAssert(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == "$value") { return; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } public void Skip() { if (TokenType == JsonToken.PropertyName) { Read(); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (Read() && depth < Depth) { } } } protected void SetToken(JsonToken newToken) { SetToken(newToken, null, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value) { SetToken(newToken, value, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Raw: case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: SetPostValueState(updateIndex); break; case JsonToken.Comment: break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != 0 || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } if (updateIndex) { UpdateScopeWithFinishedValue(); } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void ValidateEnd(JsonToken endToken) { JsonContainerType jsonContainerType = Pop(); if (GetTypeForCloseToken(endToken) != jsonContainerType) { throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType)); } if (Peek() != 0 || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } } protected void SetStateBasedOnCurrent() { JsonContainerType jsonContainerType = Peek(); switch (jsonContainerType) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType)); } } private void SetFinished() { _currentState = ((!SupportMultipleContent) ? State.Finished : State.Start); } private JsonContainerType GetTypeForCloseToken(JsonToken token) { return token switch { JsonToken.EndObject => JsonContainerType.Object, JsonToken.EndArray => JsonContainerType.Array, JsonToken.EndConstructor => JsonContainerType.Constructor, _ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), }; } void IDisposable.Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } internal void ReadAndAssert() { if (!Read()) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter) { if (!ReadForType(contract, hasConverter)) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal bool ReadForType(JsonContract? contract, bool hasConverter) { if (hasConverter) { return Read(); } switch (contract?.InternalReadType ?? ReadType.Read) { case ReadType.Read: return ReadAndMoveToContent(); case ReadType.ReadAsInt32: ReadAsInt32(); break; case ReadType.ReadAsInt64: { bool result = ReadAndMoveToContent(); if (TokenType == JsonToken.Undefined) { throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long))); } return result; } case ReadType.ReadAsDecimal: ReadAsDecimal(); break; case ReadType.ReadAsDouble: ReadAsDouble(); break; case ReadType.ReadAsBytes: ReadAsBytes(); break; case ReadType.ReadAsBoolean: ReadAsBoolean(); break; case ReadType.ReadAsString: ReadAsString(); break; case ReadType.ReadAsDateTime: ReadAsDateTime(); break; case ReadType.ReadAsDateTimeOffset: ReadAsDateTimeOffset(); break; default: throw new ArgumentOutOfRangeException(); } return TokenType != JsonToken.None; } internal bool ReadAndMoveToContent() { if (Read()) { return MoveToContent(); } return false; } internal bool MoveToContent() { JsonToken tokenType = TokenType; while (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { if (!Read()) { return false; } tokenType = TokenType; } return true; } private JsonToken GetContentToken() { JsonToken tokenType; do { if (!Read()) { SetToken(JsonToken.None); return JsonToken.None; } tokenType = TokenType; } while (tokenType == JsonToken.Comment); return tokenType; } } [Serializable] public class JsonReaderException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonReaderException() { } public JsonReaderException(string message) : base(message) { } public JsonReaderException(string message, Exception innerException) : base(message, innerException) { } public JsonReaderException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonReaderException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonReaderException(message, path, lineNumber, linePosition, ex); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonRequiredAttribute : Attribute { } [Serializable] public class JsonSerializationException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonSerializationException() { } public JsonSerializationException(string message) : base(message) { } public JsonSerializationException(string message, Exception innerException) : base(message, innerException) { } public JsonSerializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonSerializationException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonSerializationException(message, path, lineNumber, linePosition, ex); } } public class JsonSerializer { internal TypeNameHandling _typeNameHandling; internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling; internal PreserveReferencesHandling _preserveReferencesHandling; internal ReferenceLoopHandling _referenceLoopHandling; internal MissingMemberHandling _missingMemberHandling; internal ObjectCreationHandling _objectCreationHandling; internal NullValueHandling _nullValueHandling; internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; internal JsonConverterCollection? _converters; internal IContractResolver _contractResolver; internal ITraceWriter? _traceWriter; internal IEqualityComparer? _equalityComparer; internal ISerializationBinder _serializationBinder; internal StreamingContext _context; private IReferenceResolver? _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; private DateTimeZoneHandling? _dateTimeZoneHandling; private DateParseHandling? _dateParseHandling; private FloatFormatHandling? _floatFormatHandling; private FloatParseHandling? _floatParseHandling; private StringEscapeHandling? _stringEscapeHandling; private CultureInfo _culture; private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; private string? _dateFormatString; private bool _dateFormatStringSet; public virtual IReferenceResolver? ReferenceResolver { get { return GetReferenceResolver(); } set { if (value == null) { throw new ArgumentNullException("value", "Reference resolver cannot be null."); } _referenceResolver = value; } } [Obsolete("Binder is obsolete. Use SerializationBinder instead.")] public virtual SerializationBinder Binder { get { if (_serializationBinder is SerializationBinder result) { return result; } if (_serializationBinder is SerializationBinderAdapter serializationBinderAdapter) { return serializationBinderAdapter.SerializationBinder; } throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set."); } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = (value as ISerializationBinder) ?? new SerializationBinderAdapter(value); } } public virtual ISerializationBinder SerializationBinder { get { return _serializationBinder; } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = value; } } public virtual ITraceWriter? TraceWriter { get { return _traceWriter; } set { _traceWriter = value; } } public virtual IEqualityComparer? EqualityComparer { get { return _equalityComparer; } set { _equalityComparer = value; } } public virtual TypeNameHandling TypeNameHandling { get { return _typeNameHandling; } set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) { throw new ArgumentOutOfRangeException("value"); } _typeNameHandling = value; } } [Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")] public virtual FormatterAssemblyStyle TypeNameAssemblyFormat { get { return (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling; } set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value; } } public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling { get { return _typeNameAssemblyFormatHandling; } set { if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = value; } } public virtual PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling; } set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) { throw new ArgumentOutOfRangeException("value"); } _preserveReferencesHandling = value; } } public virtual ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) { throw new ArgumentOutOfRangeException("value"); } _referenceLoopHandling = value; } } public virtual MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling; } set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) { throw new ArgumentOutOfRangeException("value"); } _missingMemberHandling = value; } } public virtual NullValueHandling NullValueHandling { get { return _nullValueHandling; } set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _nullValueHandling = value; } } public virtual DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling; } set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) { throw new ArgumentOutOfRangeException("value"); } _defaultValueHandling = value; } } public virtual ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling; } set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) { throw new ArgumentOutOfRangeException("value"); } _objectCreationHandling = value; } } public virtual ConstructorHandling ConstructorHandling { get { return _constructorHandling; } set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) { throw new ArgumentOutOfRangeException("value"); } _constructorHandling = value; } } public virtual MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling; } set { if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _metadataPropertyHandling = value; } } public virtual JsonConverterCollection Converters { get { if (_converters == null) { _converters = new JsonConverterCollection(); } return _converters; } } public virtual IContractResolver ContractResolver { get { return _contractResolver; } set { _contractResolver = value ?? DefaultContractResolver.Instance; } } public virtual StreamingContext Context { get { return _context; } set { _context = value; } } public virtual Formatting Formatting { get { return _formatting.GetValueOrDefault(); } set { _formatting = value; } } public virtual DateFormatHandling DateFormatHandling { get { return _dateFormatHandling.GetValueOrDefault(); } set { _dateFormatHandling = value; } } public virtual DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind; } set { _dateTimeZoneHandling = value; } } public virtual DateParseHandling DateParseHandling { get { return _dateParseHandling ?? DateParseHandling.DateTime; } set { _dateParseHandling = value; } } public virtual FloatParseHandling FloatParseHandling { get { return _floatParseHandling.GetValueOrDefault(); } set { _floatParseHandling = value; } } public virtual FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling.GetValueOrDefault(); } set { _floatFormatHandling = value; } } public virtual StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling.GetValueOrDefault(); } set { _stringEscapeHandling = value; } } public virtual string DateFormatString { get { return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; } set { _dateFormatString = value; _dateFormatStringSet = true; } } public virtual CultureInfo Culture { get { return _culture ?? JsonSerializerSettings.DefaultCulture; } set { _culture = value; } } public virtual int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; _maxDepthSet = true; } } public virtual bool CheckAdditionalContent { get { return _checkAdditionalContent.GetValueOrDefault(); } set { _checkAdditionalContent = value; } } public virtual event EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>? Error; internal bool IsCheckAdditionalContentSet() { return _checkAdditionalContent.HasValue; } public JsonSerializer() { _referenceLoopHandling = ReferenceLoopHandling.Error; _missingMemberHandling = MissingMemberHandling.Ignore; _nullValueHandling = NullValueHandling.Include; _defaultValueHandling = DefaultValueHandling.Include; _objectCreationHandling = ObjectCreationHandling.Auto; _preserveReferencesHandling = PreserveReferencesHandling.None; _constructorHandling = ConstructorHandling.Default; _typeNameHandling = TypeNameHandling.None; _metadataPropertyHandling = MetadataPropertyHandling.Default; _context = JsonSerializerSettings.DefaultContext; _serializationBinder = DefaultSerializationBinder.Instance; _culture = JsonSerializerSettings.DefaultCulture; _contractResolver = DefaultContractResolver.Instance; } public static JsonSerializer Create() { return new JsonSerializer(); } public static JsonSerializer Create(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = Create(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } public static JsonSerializer CreateDefault() { return Create(JsonConvert.DefaultSettings?.Invoke()); } public static JsonSerializer CreateDefault(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = CreateDefault(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } if (settings._typeNameHandling.HasValue) { serializer.TypeNameHandling = settings.TypeNameHandling; } if (settings._metadataPropertyHandling.HasValue) { serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; } if (settings._typeNameAssemblyFormatHandling.HasValue) { serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling; } if (settings._preserveReferencesHandling.HasValue) { serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; } if (settings._referenceLoopHandling.HasValue) { serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; } if (settings._missingMemberHandling.HasValue) { serializer.MissingMemberHandling = settings.MissingMemberHandling; } if (settings._objectCreationHandling.HasValue) { serializer.ObjectCreationHandling = settings.ObjectCreationHandling; } if (settings._nullValueHandling.HasValue) { serializer.NullValueHandling = settings.NullValueHandling; } if (settings._defaultValueHandling.HasValue) { serializer.DefaultValueHandling = settings.DefaultValueHandling; } if (settings._constructorHandling.HasValue) { serializer.ConstructorHandling = settings.ConstructorHandling; } if (settings._context.HasValue) { serializer.Context = settings.Context; } if (settings._checkAdditionalContent.HasValue) { serializer._checkAdditionalContent = settings._checkAdditionalContent; } if (settings.Error != null) { serializer.Error += settings.Error; } if (settings.ContractResolver != null) { serializer.ContractResolver = settings.ContractResolver; } if (settings.ReferenceResolverProvider != null) { serializer.ReferenceResolver = settings.ReferenceResolverProvider(); } if (settings.TraceWriter != null) { serializer.TraceWriter = settings.TraceWriter; } if (settings.EqualityComparer != null) { serializer.EqualityComparer = settings.EqualityComparer; } if (settings.SerializationBinder != null) { serializer.SerializationBinder = settings.SerializationBinder; } if (settings._formatting.HasValue) { serializer._formatting = settings._formatting; } if (settings._dateFormatHandling.HasValue) { serializer._dateFormatHandling = settings._dateFormatHandling; } if (settings._dateTimeZoneHandling.HasValue) { serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; } if (settings._dateParseHandling.HasValue) { serializer._dateParseHandling = settings._dateParseHandling; } if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling.HasValue) { serializer._floatFormatHandling = settings._floatFormatHandling; } if (settings._floatParseHandling.HasValue) { serializer._floatParseHandling = settings._floatParseHandling; } if (settings._stringEscapeHandling.HasValue) { serializer._stringEscapeHandling = settings._stringEscapeHandling; } if (settings._culture != null) { serializer._culture = settings._culture; } if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } } [DebuggerStepThrough] public void Populate(TextReader reader, object target) { Populate(new JsonTextReader(reader), target); } [DebuggerStepThrough] public void Populate(JsonReader reader, object target) { PopulateInternal(reader, target); } internal virtual void PopulateInternal(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(reader, "reader"); ValidationUtils.ArgumentNotNull(target, "target"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); new JsonSerializerInternalReader(this).Populate(traceJsonReader ?? reader, target); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader) { return Deserialize(reader, null); } [DebuggerStepThrough] public object? Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } [DebuggerStepThrough] public T? Deserialize<T>(JsonReader reader) { return (T)Deserialize(reader, typeof(T)); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader, Type? objectType) { return DeserializeInternal(reader, objectType); } internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType) { ValidationUtils.ArgumentNotNull(reader, "reader"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); object? result = new JsonSerializerInternalReader(this).Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); return result; } private void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString) { if (_culture != null && !_culture.Equals(reader.Culture)) { previousCulture = reader.Culture; reader.Culture = _culture; } else { previousCulture = null; } if (_dateTimeZoneHandling.HasValue && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = reader.DateTimeZoneHandling; reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } else { previousDateTimeZoneHandling = null; } if (_dateParseHandling.HasValue && reader.DateParseHandling != _dateParseHandling) { previousDateParseHandling = reader.DateParseHandling; reader.DateParseHandling = _dateParseHandling.GetValueOrDefault(); } else { previousDateParseHandling = null; } if (_floatParseHandling.HasValue && reader.FloatParseHandling != _floatParseHandling) { previousFloatParseHandling = reader.FloatParseHandling; reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault(); } else { previousFloatParseHandling = null; } if (_maxDepthSet && reader.MaxDepth != _maxDepth) { previousMaxDepth = reader.MaxDepth; reader.MaxDepth = _maxDepth; } else { previousMaxDepth = null; } if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString) { previousDateFormatString = reader.DateFormatString; reader.DateFormatString = _dateFormatString; } else { previousDateFormatString = null; } if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable == null && _contractResolver is DefaultContractResolver defaultContractResolver) { jsonTextReader.PropertyNameTable = defaultContractResolver.GetNameTable(); } } private void ResetReader(JsonReader reader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString) { if (previousCulture != null) { reader.Culture = previousCulture; } if (previousDateTimeZoneHandling.HasValue) { reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousDateParseHandling.HasValue) { reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault(); } if (previousFloatParseHandling.HasValue) { reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault(); } if (_maxDepthSet) { reader.MaxDepth = previousMaxDepth; } if (_dateFormatStringSet) { reader.DateFormatString = previousDateFormatString; } if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable != null && _contractResolver is DefaultContractResolver defaultContractResolver && jsonTextReader.PropertyNameTable == defaultContractResolver.GetNameTable()) { jsonTextReader.PropertyNameTable = null; } } public void Serialize(TextWriter textWriter, object? value) { Serialize(new JsonTextWriter(textWriter), value); } public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType) { SerializeInternal(jsonWriter, value, objectType); } public void Serialize(TextWriter textWriter, object? value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } public void Serialize(JsonWriter jsonWriter, object? value) { SerializeInternal(jsonWriter, value, null); } private TraceJsonReader CreateTraceJsonReader(JsonReader reader) { TraceJsonReader traceJsonReader = new TraceJsonReader(reader); if (reader.TokenType != 0) { traceJsonReader.WriteCurrentToken(); } return traceJsonReader; } internal virtual void SerializeInternal(JsonWriter jsonWriter, object? value, Type? objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter"); Formatting? formatting = null; if (_formatting.HasValue && jsonWriter.Formatting != _formatting) { formatting = jsonWriter.Formatting; jsonWriter.Formatting = _formatting.GetValueOrDefault(); } DateFormatHandling? dateFormatHandling = null; if (_dateFormatHandling.HasValue && jsonWriter.DateFormatHandling != _dateFormatHandling) { dateFormatHandling = jsonWriter.DateFormatHandling; jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault(); } DateTimeZoneHandling? dateTimeZoneHandling = null; if (_dateTimeZoneHandling.HasValue && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling) { dateTimeZoneHandling = jsonWriter.DateTimeZoneHandling; jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } FloatFormatHandling? floatFormatHandling = null; if (_floatFormatHandling.HasValue && jsonWriter.FloatFormatHandling != _floatFormatHandling) { floatFormatHandling = jsonWriter.FloatFormatHandling; jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault(); } StringEscapeHandling? stringEscapeHandling = null; if (_stringEscapeHandling.HasValue && jsonWriter.StringEscapeHandling != _stringEscapeHandling) { stringEscapeHandling = jsonWriter.StringEscapeHandling; jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault(); } CultureInfo cultureInfo = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { cultureInfo = jsonWriter.Culture; jsonWriter.Culture = _culture; } string dateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { dateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } TraceJsonWriter traceJsonWriter = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null); new JsonSerializerInternalWriter(this).Serialize(traceJsonWriter ?? jsonWriter, value, objectType); if (traceJsonWriter != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); } if (formatting.HasValue) { jsonWriter.Formatting = formatting.GetValueOrDefault(); } if (dateFormatHandling.HasValue) { jsonWriter.DateFormatHandling = dateFormatHandling.GetValueOrDefault(); } if (dateTimeZoneHandling.HasValue) { jsonWriter.DateTimeZoneHandling = dateTimeZoneHandling.GetValueOrDefault(); } if (floatFormatHandling.HasValue) { jsonWriter.FloatFormatHandling = floatFormatHandling.GetValueOrDefault(); } if (stringEscapeHandling.HasValue) { jsonWriter.StringEscapeHandling = stringEscapeHandling.GetValueOrDefault(); } if (_dateFormatStringSet) { jsonWriter.DateFormatString = dateFormatString; } if (cultureInfo != null) { jsonWriter.Culture = cultureInfo; } } internal IReferenceResolver GetReferenceResolver() { if (_referenceResolver == null) { _referenceResolver = new DefaultReferenceResolver(); } return _referenceResolver; } internal JsonConverter? GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } internal static JsonConverter? GetMatchingConverter(IList<JsonConverter>? converters, Type objectType) { if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter jsonConverter = converters[i]; if (jsonConverter.CanConvert(objectType)) { return jsonConverter; } } } return null; } internal void OnError(Newtonsoft.Json.Serialization.ErrorEventArgs e) { this.Error?.Invoke(this, e); } } public class JsonSerializerSettings { internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error; internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore; internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include; internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include; internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto; internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None; internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default; internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None; internal const MetadataPropertyHandling DefaultMetadataPropertyHandling = MetadataPropertyHandling.Default; internal static readonly StreamingContext DefaultContext; internal const Formatting DefaultFormatting = Formatting.None; internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat; internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime; internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double; internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String; internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default; internal const TypeNameAssemblyFormatHandling DefaultTypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple; internal static readonly CultureInfo DefaultCulture; internal const bool DefaultCheckAdditionalContent = false; internal const string DefaultDateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; internal const int DefaultMaxDepth = 64; internal Formatting? _formatting; internal DateFormatHandling? _dateFormatHandling; internal DateTimeZoneHandling? _dateTimeZoneHandling; internal DateParseHandling? _dateParseHandling; internal FloatFormatHandling? _floatFormatHandling; internal FloatParseHandling? _floatParseHandling; internal StringEscapeHandling? _stringEscapeHandling; internal CultureInfo? _culture; internal bool? _checkAdditionalContent; internal int? _maxDepth; internal bool _maxDepthSet; internal string? _dateFormatString; internal bool _dateFormatStringSet; internal TypeNameAssemblyFormatHandling? _typeNameAssemblyFormatHandling; internal DefaultValueHandling? _defaultValueHandling; internal PreserveReferencesHandling? _preserveReferencesHandling; internal NullValueHandling? _nullValueHandling; internal ObjectCreationHandling? _objectCreationHandling; internal MissingMemberHandling? _missingMemberHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal StreamingContext? _context; internal ConstructorHandling? _constructorHandling; internal TypeNameHandling? _typeNameHandling; internal MetadataPropertyHandling? _metadataPropertyHandling; public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling.GetValueOrDefault(); } set { _referenceLoopHandling = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling.GetValueOrDefault(); } set { _objectCreationHandling = value; } } public NullValueHandling NullValueHandling { get { return _nullValueHandling.GetValueOrDefault(); } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling.GetValueOrDefault(); } set { _defaultValueHandling = value; } } public IList<JsonConverter> Converters { get; set; } public PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling.GetValueOrDefault(); } set { _preserveReferencesHandling = value; } } public TypeNameHandling TypeNameHandling
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/FullNET/XUnity.AutoTranslator.Plugin.ExtProtocol.dll
Decompiled 4 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyDescription("Package that contains a simple inter-process protocol format used in XUnity.")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyInformationalVersion("1.0.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("XUnity.AutoTranslator.Plugin.ExtProtocol")] [assembly: AssemblyTitle("XUnity.AutoTranslator.Plugin.ExtProtocol")] [assembly: AssemblyVersion("1.0.1.0")] namespace XUnity.AutoTranslator.Plugin.ExtProtocol; public class ConfigurationMessage : ProtocolMessage { public static readonly string Type = "4"; public string Config { get; set; } internal override void Decode(TextReader reader) { base.Id = new Guid(reader.ReadLine()); Config = reader.ReadToEnd(); } internal override void Encode(TextWriter writer) { writer.WriteLine(base.Id.ToString()); writer.Write(Config); } } public static class ExtProtocolConvert { private static readonly Dictionary<string, Type> IdToType; private static readonly Dictionary<Type, string> TypeToId; static ExtProtocolConvert() { IdToType = new Dictionary<string, Type>(); TypeToId = new Dictionary<Type, string>(); Register(TranslationRequest.Type, typeof(TranslationRequest)); Register(TranslationResponse.Type, typeof(TranslationResponse)); Register(TranslationError.Type, typeof(TranslationError)); Register(ConfigurationMessage.Type, typeof(ConfigurationMessage)); } public static void Register(string id, Type type) { IdToType[id] = type; TypeToId[type] = id; } public static string Encode(ProtocolMessage message) { StringWriter stringWriter = new StringWriter(); string value = TypeToId[message.GetType()]; stringWriter.WriteLine(value); message.Encode(stringWriter); return Convert.ToBase64String(Encoding.UTF8.GetBytes(stringWriter.ToString()), Base64FormattingOptions.None); } public static ProtocolMessage Decode(string message) { StringReader stringReader = new StringReader(Encoding.UTF8.GetString(Convert.FromBase64String(message))); string key = stringReader.ReadLine(); ProtocolMessage obj = (ProtocolMessage)Activator.CreateInstance(IdToType[key]); obj.Decode(stringReader); return obj; } } public abstract class ProtocolMessage { public Guid Id { get; set; } internal abstract void Decode(TextReader reader); internal abstract void Encode(TextWriter writer); } public enum StatusCode { OK = 0, Blocked = 1, Unknown = 1000 } public class TranslationError : ProtocolMessage { public static readonly string Type = "3"; public string Reason { get; set; } public StatusCode FailureCode { get; set; } internal override void Decode(TextReader reader) { base.Id = new Guid(reader.ReadLine()); FailureCode = (StatusCode)int.Parse(reader.ReadLine()); Reason = reader.ReadToEnd(); } internal override void Encode(TextWriter writer) { writer.WriteLine(base.Id.ToString()); writer.WriteLine((int)FailureCode); writer.Write(Reason); } } public class TranslationRequest : ProtocolMessage { public static readonly string Type = "1"; private string[] _untranslatedTexts; public string SourceLanguage { get; set; } public string DestinationLanguage { get; set; } public string[] UntranslatedTexts => _untranslatedTexts ?? (_untranslatedTexts = UntranslatedTextInfos.Select((TransmittableUntranslatedTextInfo x) => x.UntranslatedText).ToArray()); public TransmittableUntranslatedTextInfo[] UntranslatedTextInfos { get; set; } internal override void Decode(TextReader reader) { base.Id = new Guid(reader.ReadLine()); SourceLanguage = reader.ReadLine(); DestinationLanguage = reader.ReadLine(); int num = int.Parse(reader.ReadLine(), CultureInfo.InvariantCulture); TransmittableUntranslatedTextInfo[] array = new TransmittableUntranslatedTextInfo[num]; for (int i = 0; i < num; i++) { TransmittableUntranslatedTextInfo transmittableUntranslatedTextInfo = new TransmittableUntranslatedTextInfo(); transmittableUntranslatedTextInfo.Decode(reader); array[i] = transmittableUntranslatedTextInfo; } UntranslatedTextInfos = array; } internal override void Encode(TextWriter writer) { writer.WriteLine(base.Id.ToString()); writer.WriteLine(SourceLanguage); writer.WriteLine(DestinationLanguage); writer.WriteLine(UntranslatedTextInfos.Length.ToString(CultureInfo.InvariantCulture)); TransmittableUntranslatedTextInfo[] untranslatedTextInfos = UntranslatedTextInfos; for (int i = 0; i < untranslatedTextInfos.Length; i++) { untranslatedTextInfos[i].Encode(writer); } } } public class TranslationResponse : ProtocolMessage { public static readonly string Type = "2"; public string[] TranslatedTexts { get; set; } internal override void Decode(TextReader reader) { base.Id = new Guid(reader.ReadLine()); int num = int.Parse(reader.ReadLine(), CultureInfo.InvariantCulture); string[] array = new string[num]; for (int i = 0; i < num; i++) { string s = reader.ReadLine(); string @string = Encoding.UTF8.GetString(Convert.FromBase64String(s)); array[i] = @string; } TranslatedTexts = array; } internal override void Encode(TextWriter writer) { writer.WriteLine(base.Id.ToString()); writer.WriteLine(TranslatedTexts.Length.ToString(CultureInfo.InvariantCulture)); string[] translatedTexts = TranslatedTexts; foreach (string s in translatedTexts) { string value = Convert.ToBase64String(Encoding.UTF8.GetBytes(s), Base64FormattingOptions.None); writer.WriteLine(value); } } } public class TransmittableUntranslatedTextInfo { public string[] ContextBefore { get; set; } public string UntranslatedText { get; set; } public string[] ContextAfter { get; set; } public TransmittableUntranslatedTextInfo(string[] contextBefore, string untranslatedText, string[] contextAfter) { ContextBefore = contextBefore; UntranslatedText = untranslatedText; ContextAfter = contextAfter; } public TransmittableUntranslatedTextInfo() { } internal void Encode(TextWriter writer) { string[] contextBefore = ContextBefore; writer.WriteLine(((contextBefore != null) ? contextBefore.Length : 0).ToString(CultureInfo.InvariantCulture)); if (ContextBefore != null) { string[] contextBefore2 = ContextBefore; foreach (string s in contextBefore2) { string value = Convert.ToBase64String(Encoding.UTF8.GetBytes(s), Base64FormattingOptions.None); writer.WriteLine(value); } } string[] contextAfter = ContextAfter; writer.WriteLine(((contextAfter != null) ? contextAfter.Length : 0).ToString(CultureInfo.InvariantCulture)); if (ContextAfter != null) { string[] contextBefore2 = ContextAfter; foreach (string s2 in contextBefore2) { string value2 = Convert.ToBase64String(Encoding.UTF8.GetBytes(s2), Base64FormattingOptions.None); writer.WriteLine(value2); } } string value3 = Convert.ToBase64String(Encoding.UTF8.GetBytes(UntranslatedText), Base64FormattingOptions.None); writer.WriteLine(value3); } internal void Decode(TextReader reader) { int num = int.Parse(reader.ReadLine(), CultureInfo.InvariantCulture); string[] array = new string[num]; for (int i = 0; i < num; i++) { string s = reader.ReadLine(); string @string = Encoding.UTF8.GetString(Convert.FromBase64String(s)); array[i] = @string; } ContextBefore = array; int num2 = int.Parse(reader.ReadLine(), CultureInfo.InvariantCulture); string[] array2 = new string[num2]; for (int j = 0; j < num2; j++) { string s2 = reader.ReadLine(); string string2 = Encoding.UTF8.GetString(Convert.FromBase64String(s2)); array2[j] = string2; } ContextAfter = array2; string s3 = reader.ReadLine(); string string3 = Encoding.UTF8.GetString(Convert.FromBase64String(s3)); UntranslatedText = string3; } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "1.0.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/GoogleTranslate.dll
Decompiled 4 days agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using SimpleJSON; using XUnity.AutoTranslator.Plugin.Core; using XUnity.AutoTranslator.Plugin.Core.Constants; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Endpoints.Http; using XUnity.AutoTranslator.Plugin.Core.Extensions; using XUnity.AutoTranslator.Plugin.Core.Shims; using XUnity.AutoTranslator.Plugin.Core.Utilities; using XUnity.AutoTranslator.Plugin.Core.Web; using XUnity.Common.Extensions; using XUnity.Common.Logging; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("GoogleTranslate")] [assembly: AssemblyTitle("GoogleTranslate")] [assembly: AssemblyVersion("5.6.1.0")] namespace GoogleTranslate; public class GoogleTranslateEndpoint : HttpEndpoint { [CompilerGenerated] private sealed class <OnBeforeTranslate>d__32 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public GoogleTranslateEndpoint <>4__this; private IEnumerator <enumerator>5__2; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <OnBeforeTranslate>d__32(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <enumerator>5__2 = null; <>1__state = -2; } private bool MoveNext() { int num = <>1__state; GoogleTranslateEndpoint googleTranslateEndpoint = <>4__this; if (num != 0) { if (num != 1) { return false; } <>1__state = -1; } else { <>1__state = -1; if (googleTranslateEndpoint._hasSetup && googleTranslateEndpoint._translationCount % googleTranslateEndpoint._resetAfter != 0) { goto IL_009a; } googleTranslateEndpoint._resetAfter = RandomNumbers.Next(75, 125); googleTranslateEndpoint._translationCount = 1; googleTranslateEndpoint._hasSetup = true; <enumerator>5__2 = googleTranslateEndpoint.SetupTKK(); } if (<enumerator>5__2.MoveNext()) { <>2__current = <enumerator>5__2.Current; <>1__state = 1; return true; } <enumerator>5__2 = null; goto IL_009a; IL_009a: return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class <SetupTKK>d__39 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public GoogleTranslateEndpoint <>4__this; private XUnityWebResponse <response>5__2; private IEnumerator <iterator>5__3; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <SetupTKK>d__39(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <response>5__2 = null; <iterator>5__3 = null; <>1__state = -2; } private bool MoveNext() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown int num = <>1__state; GoogleTranslateEndpoint googleTranslateEndpoint = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <response>5__2 = null; googleTranslateEndpoint._cookieContainer = new CookieContainer(); try { XUnityWebClient val = new XUnityWebClient(); XUnityWebRequest val2 = googleTranslateEndpoint.CreateWebSiteRequest(); <response>5__2 = val.Send(val2); } catch (Exception ex) { XuaLogger.AutoTranslator.Warn(ex, "An error occurred while setting up GoogleTranslate TKK. Using fallback TKK values instead."); return false; } <iterator>5__3 = ((CustomYieldInstructionShim)<response>5__2).GetSupportedEnumerator(); break; case 1: <>1__state = -1; break; } if (<iterator>5__3.MoveNext()) { <>2__current = <iterator>5__3.Current; <>1__state = 1; return true; } if (((CustomYieldInstructionShim)<response>5__2).IsTimedOut) { XuaLogger.AutoTranslator.Warn("A timeout error occurred while setting up GoogleTranslate TKK. Using fallback TKK values instead."); return false; } if (<response>5__2.Error != null) { XuaLogger.AutoTranslator.Warn(<response>5__2.Error, "An error occurred while setting up GoogleTranslate TKK. Using fallback TKK values instead."); return false; } if (<response>5__2.Data == null) { XuaLogger.AutoTranslator.Warn((Exception)null, "An error occurred while setting up GoogleTranslate TKK. Using fallback TKK values instead."); return false; } googleTranslateEndpoint.InspectResponse(<response>5__2); try { string data = <response>5__2.Data; bool flag = false; string[] array = new string[2] { "tkk:'", "TKK='" }; foreach (string text in array) { int num2 = data.IndexOf(text, StringComparison.Ordinal); if (num2 > -1) { int num3 = num2 + text.Length; int num4 = data.IndexOf('\'', num3); string[] array2 = data.Substring(num3, num4 - num3).Split(new char[1] { '.' }); if (array2.Length == 2) { googleTranslateEndpoint.m = long.Parse(array2[0]); googleTranslateEndpoint.s = long.Parse(array2[1]); flag = true; break; } } } if (!flag) { XuaLogger.AutoTranslator.Warn("An error occurred while setting up GoogleTranslate TKK. Could not locate TKK value. Using fallback TKK values instead."); } } catch (Exception ex2) { XuaLogger.AutoTranslator.Warn(ex2, "An error occurred while setting up GoogleTranslate TKK. Using fallback TKK values instead."); } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private static readonly HashSet<string> SupportedLanguages = new HashSet<string> { "auto", "romaji", "af", "sq", "am", "ar", "hy", "az", "eu", "be", "bn", "bs", "bg", "ca", "ceb", "zh-CN", "zh-TW", "co", "hr", "cs", "da", "nl", "en", "eo", "et", "fi", "fr", "fy", "gl", "ka", "de", "el", "gu", "ht", "ha", "haw", "he", "hi", "hmn", "hu", "is", "ig", "id", "ga", "it", "ja", "jw", "kn", "kk", "km", "ko", "ku", "ky", "lo", "la", "lv", "lt", "lb", "mk", "mg", "ms", "ml", "mt", "mi", "mr", "mn", "my", "ne", "no", "ny", "ps", "fa", "pl", "pt", "pa", "ro", "ru", "sm", "gd", "sr", "st", "sn", "sd", "si", "sk", "sl", "so", "es", "su", "sw", "sv", "tl", "tg", "ta", "te", "th", "tr", "uk", "ur", "uz", "vi", "cy", "xh", "yi", "yo", "zu" }; private static readonly string DefaultApiBackend = "https://translate.googleapis.com"; private static readonly string DefaultUserBackend = "https://translate.google.com"; private static readonly string HttpsServicePointTranslateTemplateUrl = "/translate_a/single?client=webapp&sl={0}&tl={1}&dt=t&tk={2}&q={3}"; private static readonly string HttpsServicePointRomanizeTemplateUrl = "/translate_a/single?client=webapp&sl={0}&tl=en&dt=rm&tk={1}&q={2}"; private static readonly Random RandomNumbers = new Random(); private static readonly string[] Accepts = new string[3] { null, "*/*", "application/json" }; private static readonly string[] AcceptLanguages = new string[4] { null, "en-US,en;q=0.9", "en-US", "en" }; private static readonly string[] AcceptCharsets = new string[2] { null, Encoding.UTF8.WebName }; private static readonly string Accept = Accepts[RandomNumbers.Next(Accepts.Length)]; private static readonly string AcceptLanguage = AcceptLanguages[RandomNumbers.Next(AcceptLanguages.Length)]; private static readonly string AcceptCharset = AcceptCharsets[RandomNumbers.Next(AcceptCharsets.Length)]; private string _selectedApiBackend; private string _selectedUserBackend; private string _httpsServicePointTranslateTemplateUrl; private string _httpsServicePointRomanizeTemplateUrl; private CookieContainer _cookieContainer; private bool _hasSetup; private long m = 427761L; private long s = 1179739010L; private int _translationsPerRequest = 10; private int _translationCount; private int _resetAfter = RandomNumbers.Next(75, 125); public override string Id => "GoogleTranslate"; public override string FriendlyName => "Google! Translate"; public override int MaxTranslationsPerRequest => _translationsPerRequest; public GoogleTranslateEndpoint() { _cookieContainer = new CookieContainer(); } private string FixLanguage(string lang) { switch (lang) { case "zh-Hans": case "zh": return "zh-CN"; case "zh-Hant": return "zh-TW"; default: return lang; } } public override void Initialize(IInitializationContext context) { //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) if (context.DestinationLanguage == "romaji") { _translationsPerRequest = 1; } _selectedApiBackend = DefaultApiBackend; _selectedUserBackend = DefaultUserBackend; string orCreateSetting = context.GetOrCreateSetting<string>("Google", "ServiceUrl"); if (!StringExtensions.IsNullOrWhiteSpace(orCreateSetting)) { _selectedApiBackend = orCreateSetting; _selectedUserBackend = orCreateSetting; _httpsServicePointTranslateTemplateUrl = _selectedApiBackend + HttpsServicePointTranslateTemplateUrl; _httpsServicePointRomanizeTemplateUrl = _selectedApiBackend + HttpsServicePointRomanizeTemplateUrl; XuaLogger.AutoTranslator.Info("The default backend for google translate was overwritten."); } else { _selectedApiBackend = DefaultApiBackend; _selectedUserBackend = DefaultUserBackend; _httpsServicePointTranslateTemplateUrl = _selectedApiBackend + HttpsServicePointTranslateTemplateUrl; _httpsServicePointRomanizeTemplateUrl = _selectedApiBackend + HttpsServicePointRomanizeTemplateUrl; } context.DisableCertificateChecksFor(new string[2] { new Uri(_selectedApiBackend).Host, new Uri(_selectedUserBackend).Host }); if (!SupportedLanguages.Contains(FixLanguage(context.SourceLanguage))) { throw new EndpointInitializationException("The source language '" + context.SourceLanguage + "' is not supported."); } if (!SupportedLanguages.Contains(FixLanguage(context.DestinationLanguage))) { throw new EndpointInitializationException("The destination language '" + context.DestinationLanguage + "' is not supported."); } } public override IEnumerator OnBeforeTranslate(IHttpTranslationContext context) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <OnBeforeTranslate>d__32(0) { <>4__this = this }; } public override void OnCreateRequest(IHttpRequestCreationContext context) { //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Expected O, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown _translationCount++; string text = string.Join("\n", ((ITranslationContextBase)context).UntranslatedTexts); XUnityWebRequest val = ((!(((ITranslationContextBase)context).DestinationLanguage == "romaji")) ? new XUnityWebRequest(string.Format(_httpsServicePointTranslateTemplateUrl, FixLanguage(((ITranslationContextBase)context).SourceLanguage), FixLanguage(((ITranslationContextBase)context).DestinationLanguage), Tk(text), Uri.EscapeDataString(text))) : new XUnityWebRequest(string.Format(_httpsServicePointRomanizeTemplateUrl, FixLanguage(((ITranslationContextBase)context).SourceLanguage), Tk(text), Uri.EscapeDataString(text)))); val.Cookies = _cookieContainer; AddHeaders(val, isTranslationRequest: true); context.Complete(val); } public override void OnInspectResponse(IHttpResponseInspectionContext context) { InspectResponse(context.Response); } public override void OnExtractTranslation(IHttpTranslationExtractionContext context) { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) bool flag = ((ITranslationContextBase)context).DestinationLanguage == "romaji"; int num = (flag ? 3 : 0); string data = ((IHttpResponseInspectionContext)context).Response.Data; JSONNode val = JSON.Parse(data); StringBuilder stringBuilder = new StringBuilder(data.Length); val = ((JSONNode)val.AsArray)[0]; if (val.IsNull && flag) { context.Complete(((ITranslationContextBase)context).UntranslatedText); return; } Enumerator enumerator = ((JSONNode)val.AsArray).GetEnumerator(); while (((Enumerator)(ref enumerator)).MoveNext()) { string text = ((object)((JSONNode)JSONNode.op_Implicit(((Enumerator)(ref enumerator)).Current).AsArray)[num]).ToString(); text = JsonHelper.Unescape(text.Substring(1, text.Length - 2)); if (!StringBuilderExtensions.EndsWithWhitespaceOrNewline(stringBuilder)) { stringBuilder.Append('\n'); } stringBuilder.Append(text); } string text2 = stringBuilder.ToString(); if (((ITranslationContextBase)context).UntranslatedTexts.Length == 1) { context.Complete(text2); return; } string[] array = text2.Split(new char[1] { '\n' }); List<string> list = new List<string>(); int num2 = 0; string[] untranslatedTexts = ((ITranslationContextBase)context).UntranslatedTexts; for (int i = 0; i < untranslatedTexts.Length; i++) { int num3 = untranslatedTexts[i].Split(new char[1] { '\n' }).Length; string text3 = string.Empty; for (int j = 0; j < num3; j++) { if (num2 >= array.Length) { ((ITranslationContextBase)context).Fail("Batch operation received incorrect number of translations."); } string text4 = array[num2++]; text3 += text4; if (j != num3 - 1) { text3 += "\n"; } } list.Add(text3); } if (num2 != array.Length) { ((ITranslationContextBase)context).Fail("Batch operation received incorrect number of translations."); } context.Complete(list.ToArray()); } private XUnityWebRequest CreateWebSiteRequest() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown XUnityWebRequest val = new XUnityWebRequest(_selectedUserBackend); val.Cookies = _cookieContainer; AddHeaders(val, isTranslationRequest: false); return val; } private void AddHeaders(XUnityWebRequest request, bool isTranslationRequest) { request.Headers[HttpRequestHeader.UserAgent] = (string.IsNullOrEmpty(AutoTranslatorSettings.UserAgent) ? UserAgents.Chrome_Win10_Latest : AutoTranslatorSettings.UserAgent); if (AcceptLanguage != null) { request.Headers[HttpRequestHeader.AcceptLanguage] = AcceptLanguage; } if (Accept != null) { request.Headers[HttpRequestHeader.Accept] = Accept; } if (isTranslationRequest) { request.Headers[HttpRequestHeader.Referer] = _selectedUserBackend + "/"; } if (AcceptCharset != null) { request.Headers[HttpRequestHeader.AcceptCharset] = AcceptCharset; } } private void InspectResponse(XUnityWebResponse response) { CookieCollection newCookies = response.NewCookies; if (newCookies == null) { return; } foreach (Cookie item in newCookies) { item.Domain = ".googleapis.com"; } _cookieContainer.Add(newCookies); } public IEnumerator SetupTKK() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <SetupTKK>d__39(0) { <>4__this = this }; } private long Vi(long r, string o) { for (int i = 0; i < o.Length; i += 3) { long num = o[i + 2]; num = ((num >= 97) ? (num - 87) : (num - 48)); num = (('+' == o[i + 1]) ? (r >> (int)num) : (r << (int)num)); r = (('+' == o[i]) ? ((r + num) & 0xFFFFFFFFu) : (r ^ num)); } return r; } private string Tk(string r) { List<long> list = new List<long>(); for (int i = 0; i < r.Length; i++) { long num = r[i]; if (128 > num) { list.Add(num); continue; } if (2048 > num) { list.Add((num >> 6) | 0xC0); } else if (55296 == (0xFC00 & num) && i + 1 < r.Length && 56320 == (0xFC00 & r[i + 1])) { num = 65536 + ((0x3FF & num) << 10) + (0x3FF & r[++i]); list.Add((num >> 18) | 0xF0); list.Add(((num >> 12) & 0x3F) | 0x80); } else { list.Add((num >> 12) | 0xE0); list.Add(((num >> 6) & 0x3F) | 0x80); } list.Add((0x3F & num) | 0x80); } long num2 = m; for (int j = 0; j < list.Count; j++) { num2 += list[j]; num2 = Vi(num2, "+-a^+6"); } num2 = Vi(num2, "+-3^+b+-f"); num2 ^= s; if (0 > num2) { num2 = (0x7FFFFFFF & num2) + 2147483648u; } num2 %= 1000000; return num2.ToString(CultureInfo.InvariantCulture) + "." + (num2 ^ m).ToString(CultureInfo.InvariantCulture); } } public class GoogleTranslateEndpointV2 : HttpEndpoint { [CompilerGenerated] private sealed class <OnBeforeTranslate>d__29 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public GoogleTranslateEndpointV2 <>4__this; private IEnumerator <enumerator>5__2; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <OnBeforeTranslate>d__29(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <enumerator>5__2 = null; <>1__state = -2; } private bool MoveNext() { int num = <>1__state; GoogleTranslateEndpointV2 googleTranslateEndpointV = <>4__this; if (num != 0) { if (num != 1) { return false; } <>1__state = -1; } else { <>1__state = -1; if (googleTranslateEndpointV._hasSetup && googleTranslateEndpointV._translationCount % googleTranslateEndpointV._resetAfter != 0) { goto IL_00b4; } googleTranslateEndpointV._resetAfter = RandomNumbers.Next(75, 125); googleTranslateEndpointV._translationCount = 1; googleTranslateEndpointV._reqId = RandomNumbers.Next(0, 100000); googleTranslateEndpointV._hasSetup = true; <enumerator>5__2 = googleTranslateEndpointV.SetupFSID(); } if (<enumerator>5__2.MoveNext()) { <>2__current = <enumerator>5__2.Current; <>1__state = 1; return true; } <enumerator>5__2 = null; goto IL_00b4; IL_00b4: return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class <SetupFSID>d__34 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public GoogleTranslateEndpointV2 <>4__this; private XUnityWebResponse <response>5__2; private IEnumerator <iterator>5__3; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <SetupFSID>d__34(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <response>5__2 = null; <iterator>5__3 = null; <>1__state = -2; } private bool MoveNext() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown int num = <>1__state; GoogleTranslateEndpointV2 googleTranslateEndpointV = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <response>5__2 = null; googleTranslateEndpointV._cookieContainer = new CookieContainer(); try { XUnityWebClient val = new XUnityWebClient(); XUnityWebRequest val2 = googleTranslateEndpointV.CreateWebSiteRequest(); <response>5__2 = val.Send(val2); } catch (Exception ex) { XuaLogger.AutoTranslator.Warn(ex, "An error occurred while setting up GoogleTranslate FSID. Using random instead."); return false; } <iterator>5__3 = ((CustomYieldInstructionShim)<response>5__2).GetSupportedEnumerator(); break; case 1: <>1__state = -1; break; } if (<iterator>5__3.MoveNext()) { <>2__current = <iterator>5__3.Current; <>1__state = 1; return true; } if (((CustomYieldInstructionShim)<response>5__2).IsTimedOut) { XuaLogger.AutoTranslator.Warn("A timeout error occurred while setting up GoogleTranslate FSID. Using random instead."); return false; } if (<response>5__2.Error != null) { XuaLogger.AutoTranslator.Warn(<response>5__2.Error, "An error occurred while setting up GoogleTranslate FSID. Using random instead."); return false; } if (<response>5__2.Data == null) { XuaLogger.AutoTranslator.Warn((Exception)null, "An error occurred while setting up GoogleTranslate FSID. Using random instead."); return false; } try { string data = <response>5__2.Data; bool flag = false; string[] array = new string[1] { "FdrFJe\":\"" }; foreach (string text in array) { int num2 = data.IndexOf(text, StringComparison.Ordinal); if (num2 > -1) { int num3 = num2 + text.Length; int num4 = data.IndexOf('"', num3); string s = data.Substring(num3, num4 - num3); googleTranslateEndpointV._FSID = long.Parse(s, CultureInfo.InvariantCulture); flag = true; break; } } if (!flag) { XuaLogger.AutoTranslator.Warn("An error occurred while setting up GoogleTranslate FSID. Could not locate FSID value. Using random instead."); } } catch (Exception ex2) { XuaLogger.AutoTranslator.Warn(ex2, "An error occurred while setting up GoogleTranslate FSID. Using random instead."); } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private static readonly char[] WordSplitters = new char[3] { ' ', '\r', '\n' }; private static readonly HashSet<string> SupportedLanguages = new HashSet<string> { "auto", "af", "sq", "am", "ar", "hy", "az", "eu", "be", "bn", "bs", "bg", "ca", "ceb", "zh-CN", "zh-TW", "co", "hr", "cs", "da", "nl", "en", "eo", "et", "fi", "fr", "fy", "gl", "ka", "de", "el", "gu", "ht", "ha", "haw", "he", "hi", "hmn", "hu", "is", "ig", "id", "ga", "it", "ja", "jw", "kn", "kk", "km", "ko", "ku", "ky", "lo", "la", "lv", "lt", "lb", "mk", "mg", "ms", "ml", "mt", "mi", "mr", "mn", "my", "ne", "no", "ny", "ps", "fa", "pl", "pt", "pa", "ro", "ru", "sm", "gd", "sr", "st", "sn", "sd", "si", "sk", "sl", "so", "es", "su", "sw", "sv", "tl", "tg", "ta", "te", "th", "tr", "uk", "ur", "uz", "vi", "cy", "xh", "yi", "yo", "zu" }; private static readonly string DefaultUserBackend = "https://translate.google.com"; private static readonly string TranslationPostTemplate = "[[[\"{0}\",\"[[\\\"{1}\\\",\\\"{2}\\\",\\\"{3}\\\",true],[null]]\",null,\"generic\"]]]"; private static readonly string HttpsServicePointTranslateTemplateUrl = "/_/TranslateWebserverUi/data/batchexecute"; private static readonly Random RandomNumbers = new Random(); private static readonly string[] AcceptLanguages = new string[4] { null, "en-US,en;q=0.9", "en-US", "en" }; private static readonly string AcceptLanguage = AcceptLanguages[RandomNumbers.Next(AcceptLanguages.Length)]; private string _selectedUserBackend; private string _httpsServicePointTranslateTemplateUrl; private CookieContainer _cookieContainer; private bool _hasSetup; private long _FSID = LongRandom(long.MinValue, long.MaxValue, RandomNumbers); private int _translationCount; private int _resetAfter = RandomNumbers.Next(75, 125); private string _translateRpcId; private string _version; private bool _useSimplestSuggestion; private long _reqId; public override string Id => "GoogleTranslateV2"; public override string FriendlyName => "Google! Translate (v2)"; public override int MaxTranslationsPerRequest => 10; public GoogleTranslateEndpointV2() { _cookieContainer = new CookieContainer(); } private static long LongRandom(long min, long max, Random rand) { byte[] array = new byte[8]; rand.NextBytes(array); return Math.Abs(BitConverter.ToInt64(array, 0) % (max - min)) + min; } private string FixLanguage(string lang) { switch (lang) { case "zh-Hans": case "zh": return "zh-CN"; case "zh-Hant": return "zh-TW"; default: return lang; } } public override void Initialize(IInitializationContext context) { //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) string orCreateSetting = context.GetOrCreateSetting<string>("GoogleV2", "ServiceUrl"); if (!StringExtensions.IsNullOrWhiteSpace(orCreateSetting)) { _selectedUserBackend = orCreateSetting; _httpsServicePointTranslateTemplateUrl = _selectedUserBackend + HttpsServicePointTranslateTemplateUrl; XuaLogger.AutoTranslator.Info("The default backend for google translate was overwritten."); } else { _selectedUserBackend = DefaultUserBackend; _httpsServicePointTranslateTemplateUrl = _selectedUserBackend + HttpsServicePointTranslateTemplateUrl; } _translateRpcId = context.GetOrCreateSetting<string>("GoogleV2", "RPCID", "MkEWBc"); _version = context.GetOrCreateSetting<string>("GoogleV2", "VERSION", "boq_translate-webserver_20210323.10_p0"); _useSimplestSuggestion = context.GetOrCreateSetting<bool>("GoogleV2", "UseSimplest", false); context.DisableCertificateChecksFor(new string[2] { new Uri(_selectedUserBackend).Host, new Uri(_selectedUserBackend).Host }); if (!SupportedLanguages.Contains(FixLanguage(context.SourceLanguage))) { throw new EndpointInitializationException("The source language '" + context.SourceLanguage + "' is not supported."); } if (!SupportedLanguages.Contains(FixLanguage(context.DestinationLanguage))) { throw new EndpointInitializationException("The destination language '" + context.DestinationLanguage + "' is not supported."); } } public override IEnumerator OnBeforeTranslate(IHttpTranslationContext context) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <OnBeforeTranslate>d__29(0) { <>4__this = this }; } public override void OnCreateRequest(IHttpRequestCreationContext context) { //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Expected O, but got Unknown _translationCount++; string text = JsonHelper.Escape(JsonHelper.Escape(string.Join("\n", ((ITranslationContextBase)context).UntranslatedTexts))); string text2 = string.Join("&", "rpcids=" + _translateRpcId, "f.sid=" + _FSID.ToString(CultureInfo.InvariantCulture), "bl=" + Uri.EscapeDataString(_version), "hl=en-US", "soc-app=1", "soc-platform=1", "soc-device=1", "_reqid=" + _reqId.ToString(CultureInfo.InvariantCulture), "rt=c"); string text3 = "f.req=" + Uri.EscapeDataString(string.Format(TranslationPostTemplate, _translateRpcId, text, FixLanguage(((ITranslationContextBase)context).SourceLanguage), FixLanguage(((ITranslationContextBase)context).DestinationLanguage))) + "&"; string text4 = _httpsServicePointTranslateTemplateUrl + "?" + text2; XUnityWebRequest val = new XUnityWebRequest("POST", text4, text3); val.Cookies = _cookieContainer; AddHeaders(val, isTranslationRequest: true); _reqId += 100000L; context.Complete(val); } public override void OnExtractTranslation(IHttpTranslationExtractionContext context) { //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) string data = ((IHttpResponseInspectionContext)context).Response.Data; data = data.Substring(6); string text = data.Substring(0, data.IndexOf('\n')); int length = int.Parse(text, CultureInfo.InvariantCulture); data = data.Substring(text.Length, length); string text2 = ((object)((JSONNode)((JSONNode)JSON.Parse(data).AsArray)[0].AsArray)[2]).ToString(); string text3 = JsonHelper.Unescape(text2.Substring(1, text2.Length - 2)); JSONNode obj = ((JSONNode)((JSONNode)((JSONNode)((JSONNode)JSON.Parse(text3).AsArray)[1].AsArray)[0].AsArray)[0].AsArray)[5]; StringBuilder stringBuilder = new StringBuilder(text3.Length); Enumerator enumerator = ((JSONNode)obj.AsArray).GetEnumerator(); while (((Enumerator)(ref enumerator)).MoveNext()) { JSONArray asArray = JSONNode.op_Implicit(((Enumerator)(ref enumerator)).Current).AsArray; string text4 = ((object)((JSONNode)asArray)[0]).ToString(); text4 = JsonHelper.Unescape(text4.Substring(1, text4.Length - 2)); if (StringExtensions.IsNullOrWhiteSpace(text4)) { continue; } if (_useSimplestSuggestion && ((JSONNode)asArray).Count > 1) { JSONNode obj2 = ((JSONNode)asArray)[1]; JSONArray val = ((obj2 != null) ? obj2.AsArray : null); if ((JSONNode)(object)val != (object)null) { HashSet<string> hashSet = new HashSet<string>(); hashSet.Add(text4); for (int i = 0; i < ((JSONNode)val).Count; i++) { string text5 = ((object)((JSONNode)val)[i]).ToString(); text5 = JsonHelper.Unescape(text5.Substring(1, text5.Length - 2)); hashSet.Add(text5); } if (hashSet.Count > 1) { XuaLogger.AutoTranslator.Debug("[GoogleTranslateV2]: Primary translation is '" + text4 + "', but found multiple suggestion:"); foreach (string item in hashSet) { XuaLogger.AutoTranslator.Debug("[GoogleTranslateV2]: " + item); } int wordsInPrimary = text4.Split(WordSplitters).Length; text4 = (from x in hashSet where x.Split(WordSplitters).Length < wordsInPrimary orderby x.Split(WordSplitters).Length select x).FirstOrDefault() ?? text4; XuaLogger.AutoTranslator.Debug("[GoogleTranslateV2]: Selecting translation: " + text4); } } } if (!StringBuilderExtensions.EndsWithWhitespaceOrNewline(stringBuilder)) { stringBuilder.Append('\n'); } stringBuilder.Append(text4); } string text6 = stringBuilder.ToString(); if (((ITranslationContextBase)context).UntranslatedTexts.Length == 1) { context.Complete(text6); return; } string[] array = text6.Split(new char[1] { '\n' }); List<string> list = new List<string>(); int num = 0; string[] untranslatedTexts = ((ITranslationContextBase)context).UntranslatedTexts; for (int j = 0; j < untranslatedTexts.Length; j++) { int num2 = untranslatedTexts[j].Split(new char[1] { '\n' }).Length; string text7 = string.Empty; for (int k = 0; k < num2; k++) { if (num >= array.Length) { ((ITranslationContextBase)context).Fail("Batch operation received incorrect number of translations."); } string text8 = array[num++]; text7 += text8; if (k != num2 - 1) { text7 += "\n"; } } list.Add(text7); } if (num != array.Length) { ((ITranslationContextBase)context).Fail("Batch operation received incorrect number of translations."); } context.Complete(list.ToArray()); } private XUnityWebRequest CreateWebSiteRequest() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown XUnityWebRequest val = new XUnityWebRequest(_selectedUserBackend); val.Cookies = _cookieContainer; AddHeaders(val, isTranslationRequest: false); return val; } private void AddHeaders(XUnityWebRequest request, bool isTranslationRequest) { request.Headers[HttpRequestHeader.UserAgent] = (string.IsNullOrEmpty(AutoTranslatorSettings.UserAgent) ? UserAgents.Chrome_Win10_Latest : AutoTranslatorSettings.UserAgent); if (AcceptLanguage != null) { request.Headers[HttpRequestHeader.AcceptLanguage] = AcceptLanguage; } if (isTranslationRequest) { request.Headers[HttpRequestHeader.Referer] = _selectedUserBackend + "/"; request.Headers["X-Same-Domain"] = "1"; request.Headers["DNT"] = "1"; request.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded;charset=UTF-8"; request.Headers[HttpRequestHeader.Accept] = "*/*"; request.Headers["Origin"] = _selectedUserBackend; } else { request.Headers["Upgrade-Insecure-Requests"] = "1"; } } public IEnumerator SetupFSID() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <SetupFSID>d__34(0) { <>4__this = this }; } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/GoogleTranslateCompat.dll
Decompiled 4 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Endpoints.ExtProtocol; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("GoogleTranslateCompat")] [assembly: AssemblyTitle("GoogleTranslateCompat")] [assembly: AssemblyVersion("5.6.1.0")] namespace GoogleTranslateCompat; internal class GoogleTranslateCompatEndpoint : ExtProtocolEndpoint { private static readonly HashSet<string> SupportedLanguages = new HashSet<string> { "auto", "af", "sq", "am", "ar", "hy", "az", "eu", "be", "bn", "bs", "bg", "ca", "ceb", "zh-CN", "zh-TW", "co", "hr", "cs", "da", "nl", "en", "eo", "et", "fi", "fr", "fy", "gl", "ka", "de", "el", "gu", "ht", "ha", "haw", "he", "hi", "hmn", "hu", "is", "ig", "id", "ga", "it", "ja", "jw", "kn", "kk", "km", "ko", "ku", "ky", "lo", "la", "lv", "lt", "lb", "mk", "mg", "ms", "ml", "mt", "mi", "mr", "mn", "my", "ne", "no", "ny", "ps", "fa", "pl", "pt", "pa", "ro", "ru", "sm", "gd", "sr", "st", "sn", "sd", "si", "sk", "sl", "so", "es", "su", "sw", "sv", "tl", "tg", "ta", "te", "th", "tr", "uk", "ur", "uz", "vi", "cy", "xh", "yi", "yo", "zu" }; public override string Id => "GoogleTranslateCompat"; public override string FriendlyName => "Google! Translate (Compat)"; public override int MaxConcurrency => 1; public override int MaxTranslationsPerRequest => 10; private string FixLanguage(string lang) { switch (lang) { case "zh-Hans": case "zh": return "zh-CN"; case "zh-Hant": return "zh-TW"; default: return lang; } } public override void Initialize(IInitializationContext context) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) ((ExtProtocolEndpoint)this).Initialize(context); if (!SupportedLanguages.Contains(FixLanguage(context.SourceLanguage))) { throw new EndpointInitializationException("The source language '" + context.SourceLanguage + "' is not supported."); } if (!SupportedLanguages.Contains(FixLanguage(context.DestinationLanguage))) { throw new EndpointInitializationException("The destination language '" + context.DestinationLanguage + "' is not supported."); } ((ExtProtocolEndpoint)this).Arguments = Convert.ToBase64String(Encoding.UTF8.GetBytes("GoogleTranslateCompat.ExtProtocol.GoogleTranslateCompatTranslate, GoogleTranslateCompat.ExtProtocol")); } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/GoogleTranslateLegitimate.dll
Decompiled 4 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using SimpleJSON; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Endpoints.Http; using XUnity.AutoTranslator.Plugin.Core.Utilities; using XUnity.AutoTranslator.Plugin.Core.Web; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("GoogleTranslateLegitimate")] [assembly: AssemblyTitle("GoogleTranslateLegitimate")] [assembly: AssemblyVersion("5.6.1.0")] namespace GoogleTranslateLegitimate; internal class GoogleTranslateLegitimateEndpoint : HttpEndpoint { private static readonly HashSet<string> SupportedLanguages = new HashSet<string> { "af", "sq", "am", "ar", "hy", "az", "eu", "be", "bn", "bs", "bg", "ca", "ceb", "zh", "zh-Hans", "zh-Hant", "zh-CN", "zh-TW", "co", "hr", "cs", "da", "nl", "en", "eo", "et", "fi", "fr", "fy", "gl", "ka", "de", "el", "gu", "ht", "ha", "haw", "he", "hi", "hmn", "hu", "is", "ig", "id", "ga", "it", "ja", "jw", "kn", "kk", "km", "ko", "ku", "ky", "lo", "la", "lv", "lt", "lb", "mk", "mg", "ms", "ml", "mt", "mi", "mr", "mn", "my", "ne", "no", "ny", "ps", "fa", "pl", "pt", "pa", "ro", "ru", "sm", "gd", "sr", "st", "sn", "sd", "si", "sk", "sl", "so", "es", "su", "sw", "sv", "tl", "tg", "ta", "te", "th", "tr", "uk", "ur", "uz", "vi", "cy", "xh", "yi", "yo", "zu" }; private static readonly string HttpsServiceUrl = "https://translation.googleapis.com/language/translate/v2"; private string _key; public override string Id => "GoogleTranslateLegitimate"; public override string FriendlyName => "Google! Translate (Authenticated)"; public override int MaxTranslationsPerRequest => 10; private string FixLanguage(string lang) { switch (lang) { case "zh-Hans": case "zh": return "zh-CN"; case "zh-Hant": return "zh-TW"; default: return lang; } } public override void Initialize(IInitializationContext context) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) _key = context.GetOrCreateSetting<string>("GoogleLegitimate", "GoogleAPIKey", ""); if (string.IsNullOrEmpty(_key)) { throw new EndpointInitializationException("The GoogleTranslateLegitimate endpoint requires an API key which has not been provided."); } context.DisableCertificateChecksFor(new string[1] { "translation.googleapis.com" }); if (!SupportedLanguages.Contains(FixLanguage(context.SourceLanguage))) { throw new EndpointInitializationException("The source language '" + context.SourceLanguage + "' is not supported."); } if (!SupportedLanguages.Contains(FixLanguage(context.DestinationLanguage))) { throw new EndpointInitializationException("The destination language '" + context.DestinationLanguage + "' is not supported."); } } public override void OnCreateRequest(IHttpRequestCreationContext context) { //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Expected O, but got Unknown StringBuilder stringBuilder = new StringBuilder(HttpsServiceUrl); stringBuilder.Append("?key=").Append(Uri.EscapeDataString(_key)); stringBuilder.Append("&source=").Append(FixLanguage(((ITranslationContextBase)context).SourceLanguage)); stringBuilder.Append("&target=").Append(FixLanguage(((ITranslationContextBase)context).DestinationLanguage)); for (int i = 0; i < ((ITranslationContextBase)context).UntranslatedTexts.Length; i++) { string stringToEscape = ((ITranslationContextBase)context).UntranslatedTexts[i]; stringBuilder.Append("&q=").Append(Uri.EscapeDataString(stringToEscape)); } XUnityWebRequest val = new XUnityWebRequest("POST", stringBuilder.ToString()); context.Complete(val); } public override void OnExtractTranslation(IHttpTranslationExtractionContext context) { JSONArray asArray = ((JSONNode)((JSONNode)JSON.Parse(((IHttpResponseInspectionContext)context).Response.Data).AsObject)["data"].AsObject)["translations"].AsArray; List<string> list = new List<string>(); for (int i = 0; i < ((JSONNode)asArray).Count; i++) { string text = ((object)((JSONNode)((JSONNode)asArray)[i].AsObject)["translatedText"]).ToString(); string item = JsonHelper.Unescape(text.Substring(1, text.Length - 2)); list.Add(item); } context.Complete(list.ToArray()); } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/LecPowerTranslator15.dll
Decompiled 4 days agousing System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using Microsoft.Win32; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Endpoints.ExtProtocol; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("LecPowerTranslator15")] [assembly: AssemblyTitle("LecPowerTranslator15")] [assembly: AssemblyVersion("5.6.1.0")] namespace LecPowerTranslator15; internal class LecPowerTranslator15Endpoint : ExtProtocolEndpoint { public override string Id => "LecPowerTranslator15"; public override string FriendlyName => "LEC Power Translator 15"; public override int MaxConcurrency => 1; public override int MaxTranslationsPerRequest => 50; public override void Initialize(IInitializationContext context) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) string defaultInstallationPath = GetDefaultInstallationPath(); string text = context.GetOrCreateSetting<string>("LecPowerTranslator15", "InstallationPath", defaultInstallationPath); if (string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(defaultInstallationPath)) { context.SetSetting<string>("LecPowerTranslator15", "InstallationPath", defaultInstallationPath); text = defaultInstallationPath; } if (string.IsNullOrEmpty(text)) { throw new EndpointInitializationException("The LecPowerTranslator15 requires the path to the installation folder."); } context.DisableSpamChecks(); string text2 = Path.Combine(context.TranslatorDirectory, Path.Combine("FullNET", "Lec.ExtProtocol.exe")); if (!File.Exists(text2)) { throw new EndpointInitializationException("Could not find any executable at '" + text2 + "'"); } ((ExtProtocolEndpoint)this).ExecutablePath = text2; ((ExtProtocolEndpoint)this).Arguments = Convert.ToBase64String(Encoding.UTF8.GetBytes(text)); if (context.SourceLanguage != "ja") { throw new EndpointInitializationException("Current implementation only supports japanese-to-english."); } if (context.DestinationLanguage != "en") { throw new EndpointInitializationException("Current implementation only supports japanese-to-english."); } } public static string GetDefaultInstallationPath() { try { string text = GetInstallationPathFromRegistry(); if (!string.IsNullOrEmpty(text)) { text = new DirectoryInfo(text).Parent.FullName; } return text ?? string.Empty; } catch { return string.Empty; } } public static string GetInstallationPathFromRegistry() { try { if (IntPtr.Size == 8) { return (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\LogoMedia\\LEC Power Translator 15\\Configuration", "ApplicationPath", null); } return (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\LogoMedia\\LEC Power Translator 15\\Configuration", "ApplicationPath", null); } catch { return null; } } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/LingoCloudTranslate.dll
Decompiled 4 days agousing System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using SimpleJSON; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Endpoints.Http; using XUnity.AutoTranslator.Plugin.Core.Utilities; using XUnity.AutoTranslator.Plugin.Core.Web; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("LingoCloudTranslate")] [assembly: AssemblyTitle("LingoCloudTranslate")] [assembly: AssemblyVersion("5.6.1.0")] namespace LingoCloudTranslate; internal class LingoCloudTranslateEndpoint : HttpEndpoint { private static readonly Dictionary<string, string> SupportedLanguages = new Dictionary<string, string> { { "en", "en" }, { "ja", "ja" }, { "jp", "ja" }, { "zh", "zh" }, { "zh-Hans", "zh" }, { "zh-CN", "zh" }, { "zh-Hant", "zh" }, { "zh-TW", "zh" } }; private static readonly string HttpServicePointTemplateUrl = "https://api.interpreter.caiyunai.com/v1/translator"; public string _token; public override string Id => "LingoCloudTranslate"; public override string FriendlyName => "CaiYun Translator"; private string FixLanguage(string lang) { if (SupportedLanguages.TryGetValue(lang, out var value)) { return value; } return lang; } public override void Initialize(IInitializationContext context) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) _token = context.GetOrCreateSetting<string>("LingoCloud", "LingoCloudToken", ""); if (string.IsNullOrEmpty(_token)) { throw new EndpointInitializationException("The LingoCloudTranslate endpoint requires an App Id which has not been provided."); } context.DisableCertificateChecksFor(new string[1] { "api.interpreter.caiyunai.com" }); if (!SupportedLanguages.ContainsKey(context.SourceLanguage)) { throw new EndpointInitializationException("The source language '" + context.SourceLanguage + "' is not supported."); } if (!SupportedLanguages.ContainsKey(context.DestinationLanguage)) { throw new EndpointInitializationException("The destination language '" + context.DestinationLanguage + "' is not supported."); } } public override void OnCreateRequest(IHttpRequestCreationContext context) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Expected O, but got Unknown JSONObject val = new JSONObject(); string[] untranslatedTexts = ((ITranslationContextBase)context).UntranslatedTexts; foreach (string text in untranslatedTexts) { ((JSONNode)val)["source"].Add(JSONNode.op_Implicit(text)); } ((JSONNode)val)["trans_type"] = JSONNode.op_Implicit("auto2" + FixLanguage(((ITranslationContextBase)context).DestinationLanguage)); ((JSONNode)val)["request_id"] = JSONNode.op_Implicit("demo"); ((JSONNode)val)["detect"] = JSONNode.op_Implicit("true"); string text2 = ((object)val).ToString(); XUnityWebRequest val2 = new XUnityWebRequest("POST", HttpServicePointTemplateUrl, text2); val2.Headers[HttpRequestHeader.ContentType] = "application/json"; val2.Headers["X-Authorization"] = "token " + _token; context.Complete(val2); } public override void OnExtractTranslation(IHttpTranslationExtractionContext context) { string text = ((object)((JSONNode)JSON.Parse(((IHttpResponseInspectionContext)context).Response.Data).AsObject)["target"]).ToString(); string text2 = JsonHelper.Unescape(text.Substring(2, text.Length - 4)); context.Complete(text2); } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/PapagoTranslate.dll
Decompiled 4 days agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using SimpleJSON; using XUnity.AutoTranslator.Plugin.Core; using XUnity.AutoTranslator.Plugin.Core.Constants; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Endpoints.Http; using XUnity.AutoTranslator.Plugin.Core.Shims; using XUnity.AutoTranslator.Plugin.Core.Utilities; using XUnity.AutoTranslator.Plugin.Core.Web; using XUnity.Common.Logging; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("PapagoTranslate")] [assembly: AssemblyTitle("PapagoTranslate")] [assembly: AssemblyVersion("5.6.1.0")] namespace PapagoTranslate; public class PapagoTranslateEndpoint : HttpEndpoint { [CompilerGenerated] private sealed class <OnBeforeTranslate>d__22 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public PapagoTranslateEndpoint <>4__this; private IEnumerator <enumerator>5__2; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <OnBeforeTranslate>d__22(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <enumerator>5__2 = null; <>1__state = -2; } private bool MoveNext() { int num = <>1__state; PapagoTranslateEndpoint papagoTranslateEndpoint = <>4__this; if (num != 0) { if (num != 1) { return false; } <>1__state = -1; } else { <>1__state = -1; if (papagoTranslateEndpoint._resetAfter != 0 && papagoTranslateEndpoint._translationCount % papagoTranslateEndpoint._resetAfter != 0) { goto IL_0099; } papagoTranslateEndpoint._translationCount = 1; papagoTranslateEndpoint._resetAfter = RandomNumbers.Next(150, 200); <enumerator>5__2 = papagoTranslateEndpoint.SetupVersion(); } if (<enumerator>5__2.MoveNext()) { <>2__current = <enumerator>5__2.Current; <>1__state = 1; return true; } <enumerator>5__2 = null; goto IL_0099; IL_0099: return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class <SetupVersion>d__25 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public PapagoTranslateEndpoint <>4__this; private XUnityWebClient <client>5__2; private XUnityWebResponse <response>5__3; private IEnumerator <iterator>5__4; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <SetupVersion>d__25(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <client>5__2 = null; <response>5__3 = null; <iterator>5__4 = null; <>1__state = -2; } private bool MoveNext() { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Expected O, but got Unknown int num = <>1__state; PapagoTranslateEndpoint papagoTranslateEndpoint = <>4__this; Match match; string value; switch (num) { default: return false; case 0: <>1__state = -1; <client>5__2 = new XUnityWebClient(); <response>5__3 = <client>5__2.Send(new XUnityWebRequest(UrlBase)); <iterator>5__4 = ((CustomYieldInstructionShim)<response>5__3).GetSupportedEnumerator(); goto IL_0083; case 1: <>1__state = -1; goto IL_0083; case 2: { <>1__state = -1; break; } IL_0083: if (<iterator>5__4.MoveNext()) { <>2__current = <iterator>5__4.Current; <>1__state = 1; return true; } match = PatternSource.Match(<response>5__3.Data); if (!match.Success) { XuaLogger.AutoTranslator.Warn("Could not parse papago page"); return false; } value = match.Value; <response>5__3 = null; <iterator>5__4 = null; <response>5__3 = <client>5__2.Send(new XUnityWebRequest(UrlBase + value)); <iterator>5__4 = ((CustomYieldInstructionShim)<response>5__3).GetSupportedEnumerator(); break; } if (<iterator>5__4.MoveNext()) { <>2__current = <iterator>5__4.Current; <>1__state = 2; return true; } Match match2 = PatternVersion.Match(<response>5__3.Data); if (!match2.Success) { XuaLogger.AutoTranslator.Warn("Could not parse papago version"); return false; } XuaLogger.AutoTranslator.Debug("Current papago version is " + match2.Value); papagoTranslateEndpoint._version = match2.Value; <response>5__3 = null; <iterator>5__4 = null; return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private static readonly HashSet<string> SupportedLanguages = new HashSet<string> { "en", "ko", "zh-CN", "zh-TW", "es", "fr", "ru", "vi", "th", "id", "de", "ja", "hi", "pt" }; private static readonly HashSet<string> SMTLanguages = new HashSet<string> { "hi", "pt" }; private static readonly string UrlBase = "https://papago.naver.com"; private static readonly string UrlN2MT = "/apis/n2mt/translate"; private static readonly string UrlNSMT = "/apis/nsmt/translate"; private static readonly string FormUrlEncodedTemplate = "deviceId={0}&locale=en&dict=false&honorific=false&instant=true&source={1}&target={2}&text={3}"; private static readonly Random RandomNumbers = new Random(); private static readonly Guid UUID = Guid.NewGuid(); private static readonly Regex PatternSource = new Regex("/main\\.[a-f0-9]+\\.chunk\\.js", RegexOptions.Singleline); private static readonly Regex PatternVersion = new Regex("v\\d\\.\\d\\.\\d_[^\"]+", RegexOptions.Singleline); private string _version; private bool _isSMT; private int _translationCount; private int _resetAfter; public override string Id => "PapagoTranslate"; public override string FriendlyName => "Papago Translator"; public override int MaxTranslationsPerRequest => 10; private string FixLanguage(string lang) { switch (lang) { case "zh-Hans": case "zh": return "zh-CN"; case "zh-Hant": return "zh-TW"; default: return lang; } } public override void Initialize(IInitializationContext context) { //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) context.DisableCertificateChecksFor(new string[1] { "papago.naver.com" }); string text = FixLanguage(context.SourceLanguage); string text2 = FixLanguage(context.DestinationLanguage); _isSMT = SMTLanguages.Contains(text) || SMTLanguages.Contains(text2); if (!SupportedLanguages.Contains(text2)) { throw new EndpointInitializationException("The language '" + context.DestinationLanguage + "' is not supported by Papago Translate."); } if (_isSMT && text != "en" && text2 != "en") { throw new EndpointInitializationException("Translation from '" + context.SourceLanguage + "' to '" + context.DestinationLanguage + "' is not supported by Papago Translate."); } } public override IEnumerator OnBeforeTranslate(IHttpTranslationContext context) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <OnBeforeTranslate>d__22(0) { <>4__this = this }; } public override void OnCreateRequest(IHttpRequestCreationContext context) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Expected O, but got Unknown string text = Uri.EscapeDataString(string.Join("\n", ((ITranslationContextBase)context).UntranslatedTexts)); XUnityWebRequest val = new XUnityWebRequest("POST", UrlBase + (_isSMT ? UrlNSMT : UrlN2MT), string.Format(FormUrlEncodedTemplate, UUID, FixLanguage(((ITranslationContextBase)context).SourceLanguage), FixLanguage(((ITranslationContextBase)context).DestinationLanguage), text)); DateTime utcNow = DateTime.UtcNow; DateTime minValue = DateTime.MinValue; double num = Math.Truncate(utcNow.Subtract(minValue.AddYears(1969)).TotalMilliseconds); byte[] bytes = Encoding.UTF8.GetBytes(_version); byte[] bytes2 = Encoding.UTF8.GetBytes($"{UUID}\n{val.Address}\n{num}"); string arg = Convert.ToBase64String(new HMACMD5(bytes).ComputeHash(bytes2)); val.Headers[HttpRequestHeader.UserAgent] = (string.IsNullOrEmpty(AutoTranslatorSettings.UserAgent) ? UserAgents.Chrome_Win10_Latest : AutoTranslatorSettings.UserAgent); val.Headers["Authorization"] = $"PPG {UUID}:{arg}"; val.Headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8"; val.Headers["Timestamp"] = num.ToString(CultureInfo.InvariantCulture); context.Complete(val); _translationCount++; } public override void OnExtractTranslation(IHttpTranslationExtractionContext context) { string text = ((object)((JSONNode)JSON.Parse(((IHttpResponseInspectionContext)context).Response.Data).AsObject)["translatedText"]).ToString(); string text2 = JsonHelper.Unescape(text.Substring(1, text.Length - 2)); if (((ITranslationContextBase)context).UntranslatedTexts.Length == 1) { context.Complete(text2); return; } string[] array = text2.Split(new char[1] { '\n' }); string[] array2 = new string[((ITranslationContextBase)context).UntranslatedTexts.Length]; int num = 0; for (int i = 0; i < ((ITranslationContextBase)context).UntranslatedTexts.Length; i++) { string[] array3 = ((ITranslationContextBase)context).UntranslatedTexts[i].Split(new char[1] { '\n' }); StringBuilder stringBuilder = new StringBuilder(); for (int j = 0; j < array3.Length; j++) { string value = array[num++]; if (array3.Length - 1 == j) { stringBuilder.Append(value); } else { stringBuilder.AppendLine(value); } } array2[i] = stringBuilder.ToString(); } if (num != array.Length) { ((ITranslationContextBase)context).Fail("Received invalid number of translations in batch."); } context.Complete(array2); } private IEnumerator SetupVersion() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <SetupVersion>d__25(0) { <>4__this = this }; } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/WatsonTranslate.dll
Decompiled 4 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using SimpleJSON; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Endpoints.Www; using XUnity.AutoTranslator.Plugin.Core.Utilities; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("WatsonTranslate")] [assembly: AssemblyTitle("WatsonTranslate")] [assembly: AssemblyVersion("5.6.1.0")] namespace WatsonTranslate; internal class WatsonTranslateEndpoint : WwwEndpoint { private static readonly HashSet<string> SupportedLanguagePairs = new HashSet<string> { "ar-en", "ca-es", "zh-en", "zh-TW-en", "cs-en", "da-en", "nl-en", "en-ar", "en-cs", "en-da", "en-de", "en-es", "en-fi", "en-fr", "en-hi", "en-it", "en-ja", "en-ko", "en-nb", "en-nl", "en-pl", "en-pt", "en-ru", "en-sv", "en-tr", "en-zh", "en-zh-TW", "fi-en", "fr-de", "fr-en", "fr-es", "de-en", "de-fr", "de-it", "hi-en", "hu-en", "it-de", "it-en", "ja-en", "ko-en", "nb-en", "pl-en", "pt-en", "ru-en", "es-ca", "es-en", "es-fr", "sv-en", "tr-en" }; private string _fullUrl; private string _url; private string _key; public override string Id => "WatsonTranslate"; public override string FriendlyName => "Watson Language Translator"; public override int MaxTranslationsPerRequest => 10; private string FixLanguage(string lang) { switch (lang) { case "zh-CN": case "zh-Hans": return "zh"; case "zh-Hant": return "zh-TW"; default: return lang; } } public override void Initialize(IInitializationContext context) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) _url = context.GetOrCreateSetting<string>("Watson", "Url", ""); _key = context.GetOrCreateSetting<string>("Watson", "Key", ""); if (string.IsNullOrEmpty(_url)) { throw new EndpointInitializationException("The WatsonTranslate endpoint requires a url which has not been provided."); } if (string.IsNullOrEmpty(_key)) { throw new EndpointInitializationException("The WatsonTranslate endpoint requires a key which has not been provided."); } _fullUrl = _url.TrimEnd(new char[1] { '/' }) + "/v3/translate?version=2018-05-01"; string text = FixLanguage(context.SourceLanguage) + "-" + FixLanguage(context.DestinationLanguage); if (!SupportedLanguagePairs.Contains(text)) { throw new EndpointInitializationException("The language model '" + text + "' is not supported."); } } public override void OnCreateRequest(IWwwRequestCreationContext context) { //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Expected O, but got Unknown StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("{\"text\":["); for (int i = 0; i < ((ITranslationContextBase)context).UntranslatedTexts.Length; i++) { string value = JsonHelper.Escape(((ITranslationContextBase)context).UntranslatedTexts[i]); stringBuilder.Append("\"").Append(value).Append("\""); if (((ITranslationContextBase)context).UntranslatedTexts.Length - 1 != i) { stringBuilder.Append(","); } } stringBuilder.Append("],\"model_id\":\"").Append(FixLanguage(((ITranslationContextBase)context).SourceLanguage)).Append("-") .Append(FixLanguage(((ITranslationContextBase)context).DestinationLanguage)) .Append("\"}"); WwwRequestInfo val = new WwwRequestInfo(_fullUrl, stringBuilder.ToString()); val.Headers["Accept"] = "application/json"; val.Headers["Content-Type"] = "application/json"; val.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("apikey:" + _key)); context.Complete(val); } public override void OnExtractTranslation(IWwwTranslationExtractionContext context) { JSONArray asArray = ((JSONNode)JSON.Parse(context.ResponseData).AsObject)["translations"].AsArray; List<string> list = new List<string>(); for (int i = 0; i < ((JSONNode)asArray).Count; i++) { string text = ((object)((JSONNode)((JSONNode)asArray)[i].AsObject)["translation"]).ToString(); string item = JsonHelper.Unescape(text.Substring(1, text.Length - 2)); list.Add(item); } context.Complete(list.ToArray()); } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/Translators/YandexTranslate.dll
Decompiled 4 days agousing System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using SimpleJSON; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Endpoints.Http; using XUnity.AutoTranslator.Plugin.Core.Utilities; using XUnity.AutoTranslator.Plugin.Core.Web; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("YandexTranslate")] [assembly: AssemblyTitle("YandexTranslate")] [assembly: AssemblyVersion("5.6.1.0")] namespace YandexTranslate; internal class YandexTranslateEndpoint : HttpEndpoint { private static readonly HashSet<string> SupportedLanguages = new HashSet<string> { "az", "sq", "am", "en", "ar", "hy", "af", "eu", "ba", "be", "bn", "my", "bg", "bs", "cy", "hu", "vi", "ht", "gl", "nl", "mrj", "el", "ka", "gu", "da", "he", "yi", "id", "ga", "it", "is", "es", "kk", "kn", "ca", "ky", "zh", "ko", "xh", "km", "lo", "la", "lv", "lt", "lb", "mg", "ms", "ml", "mt", "mk", "mi", "mr", "mhr", "mn", "de", "ne", "no", "pa", "pap", "fa", "pl", "pt", "ro", "ru", "ceb", "sr", "si", "sk", "sl", "sw", "su", "tg", "th", "tl", "ta", "tt", "te", "tr", "udm", "uz", "uk", "ur", "fi", "fr", "hi", "hr", "cs", "sv", "gd", "et", "eo", "jv", "ja" }; private static readonly string HttpsServiceUrl = "https://translate.api.cloud.yandex.net/translate/v2/translate"; private string _key; public override string Id => "YandexTranslate"; public override string FriendlyName => "Yandex Translate"; private string FixLanguage(string lang) { if (lang == "zh-CN" || lang == "zh-Hans") { return "zh"; } return lang; } public override void Initialize(IInitializationContext context) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) _key = context.GetOrCreateSetting<string>("Yandex", "YandexAPIKey", ""); context.DisableCertificateChecksFor(new string[1] { "translate.api.cloud.yandex.net" }); if (string.IsNullOrEmpty(_key)) { throw new EndpointInitializationException("The YandexTranslate endpoint requires an API key which has not been provided."); } if (!SupportedLanguages.Contains(FixLanguage(context.SourceLanguage))) { throw new EndpointInitializationException("The source language '" + context.SourceLanguage + "' is not supported."); } if (!SupportedLanguages.Contains(FixLanguage(context.DestinationLanguage))) { throw new EndpointInitializationException("The destination language '" + context.DestinationLanguage + "' is not supported."); } } public override void OnCreateRequest(IHttpRequestCreationContext context) { //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Expected O, but got Unknown string text = FixLanguage(((ITranslationContextBase)context).SourceLanguage); string text2 = FixLanguage(((ITranslationContextBase)context).DestinationLanguage); string text3 = JsonHelper.Escape(((ITranslationContextBase)context).UntranslatedText ?? string.Empty); string text4 = "{\"sourceLanguageCode\":\"" + text + "\",\"targetLanguageCode\":\"" + text2 + "\",\"texts\":[\"" + text3 + "\"]}"; XUnityWebRequest val = new XUnityWebRequest("POST", HttpsServiceUrl, text4); val.Headers["Authorization"] = "Api-Key " + _key; val.Headers["Content-Type"] = "application/json; charset=utf-8"; val.Headers["Accept"] = "application/json"; context.Complete(val); } public override void OnExtractTranslation(IHttpTranslationExtractionContext context) { string data = ((IHttpResponseInspectionContext)context).Response.Data; if (string.IsNullOrEmpty(data)) { ((ITranslationContextBase)context).Fail("Empty response from Yandex."); } JSONNode obj = JSON.Parse(data); if (obj == (object)null) { ((ITranslationContextBase)context).Fail("Failed to parse JSON from Yandex response."); } JSONNode val = obj["translations"]; if (val == (object)null || val.Count == 0) { ((ITranslationContextBase)context).Fail("No translations found in response."); } JSONNode obj2 = val[0]["text"]; string text = ((obj2 != null) ? obj2.Value : null); if (string.IsNullOrEmpty(text)) { ((ITranslationContextBase)context).Fail("Received no translation."); } context.Complete(text); } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/XUnity.AutoTranslator.Plugin.BepInEx.dll
Decompiled 4 days agousing System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using BepInEx; using ExIni; using XUnity.AutoTranslator.Plugin.Core; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("XUnity.AutoTranslator.Plugin.BepInEx")] [assembly: AssemblyTitle("XUnity.AutoTranslator.Plugin.BepInEx")] [assembly: AssemblyVersion("5.6.1.0")] namespace XUnity.AutoTranslator.Plugin.BepInEx; [BepInPlugin("gravydevsupreme.xunity.autotranslator", "XUnity Auto Translator", "5.6.1")] public class AutoTranslatorPlugin : BaseUnityPlugin, IPluginEnvironment { private IniFile _file; private string _configPath; public IniFile Preferences => _file ?? (_file = ReloadConfig()); public string ConfigPath { get; } public string TranslationPath { get; } public bool AllowDefaultInitializeHarmonyDetourBridge => false; public AutoTranslatorPlugin() { ConfigPath = Paths.ConfigPath; TranslationPath = Paths.BepInExRootPath; _configPath = Path.Combine(ConfigPath, "AutoTranslatorConfig.ini"); } public IniFile ReloadConfig() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (!File.Exists(_configPath)) { return (IniFile)(((object)_file) ?? ((object)new IniFile())); } IniFile val = IniFile.FromFile(_configPath); if (_file == null) { return _file = val; } _file.Merge(val); return _file; } public void SaveConfig() { _file.Save(_configPath); } private void Awake() { PluginLoader.LoadWithConfig((IPluginEnvironment)(object)this); } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "5.6.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/XUnity.AutoTranslator.Plugin.Core.dll
Decompiled 4 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Net.Cache; using System.Net.Security; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using DynamicLinq; using ExIni; using Harmony; using ICSharpCode.SharpZipLib.Checksums; using ICSharpCode.SharpZipLib.Core; using ICSharpCode.SharpZipLib.Encryption; using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; using Microsoft.CodeAnalysis; using MonoMod.RuntimeDetour; using UnityEngine; using UnityEngine.SceneManagement; using XUnity.AutoTranslator.Plugin.Core.AssetRedirection; using XUnity.AutoTranslator.Plugin.Core.Configuration; using XUnity.AutoTranslator.Plugin.Core.Debugging; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Extensions; using XUnity.AutoTranslator.Plugin.Core.Fonts; using XUnity.AutoTranslator.Plugin.Core.Hooks; using XUnity.AutoTranslator.Plugin.Core.Hooks.NGUI; using XUnity.AutoTranslator.Plugin.Core.Hooks.TextMeshPro; using XUnity.AutoTranslator.Plugin.Core.Hooks.UGUI; using XUnity.AutoTranslator.Plugin.Core.Hooks.UIElements; using XUnity.AutoTranslator.Plugin.Core.Managed.Textures; using XUnity.AutoTranslator.Plugin.Core.Parsing; using XUnity.AutoTranslator.Plugin.Core.Properties; using XUnity.AutoTranslator.Plugin.Core.Shims; using XUnity.AutoTranslator.Plugin.Core.Text; using XUnity.AutoTranslator.Plugin.Core.Textures; using XUnity.AutoTranslator.Plugin.Core.UI; using XUnity.AutoTranslator.Plugin.Core.UIResize; using XUnity.AutoTranslator.Plugin.Core.Utilities; using XUnity.AutoTranslator.Plugin.Core.Web; using XUnity.AutoTranslator.Plugin.Core.Web.Internal; using XUnity.AutoTranslator.Plugin.ExtProtocol; using XUnity.AutoTranslator.Plugin.Utilities; using XUnity.Common.Constants; using XUnity.Common.Extensions; using XUnity.Common.Harmony; using XUnity.Common.Logging; using XUnity.Common.MonoMod; using XUnity.Common.Utilities; using XUnity.ResourceRedirector; [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyTitle("XUnity.AutoTranslator.Plugin.Core")] [assembly: AssemblyProduct("XUnity.AutoTranslator.Plugin.Core")] [assembly: AssemblyInformationalVersion("5.6.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyFileVersion("5.6.1.0")] [assembly: AssemblyDescription("Main development dependency for XUnity Auto Translator.")] [assembly: CompilationRelaxations(8)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("XUnity.AutoTranslator.Plugin.Core.Tests")] [assembly: AssemblyCompany("gravydevsupreme")] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyConfiguration("Release")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("5.6.1.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [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 DynamicLinq { internal static class DynamicQueryable { public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object[] values) { return (IQueryable<T>)((IQueryable)source).Where(predicate, values); } public static IQueryable Where(this IQueryable source, string predicate, params object[] values) { if (source == null) { throw new ArgumentNullException("source"); } if (predicate == null) { throw new ArgumentNullException("predicate"); } LambdaExpression expression = DynamicExpression.ParseLambda(source.ElementType, typeof(bool), predicate, values); return source.Provider.CreateQuery(Expression.Call(typeof(Queryable), "Where", new Type[1] { source.ElementType }, source.Expression, Expression.Quote(expression))); } public static IQueryable Select(this IQueryable source, string selector, params object[] values) { if (source == null) { throw new ArgumentNullException("source"); } if (selector == null) { throw new ArgumentNullException("selector"); } LambdaExpression lambdaExpression = DynamicExpression.ParseLambda(source.ElementType, null, selector, values); return source.Provider.CreateQuery(Expression.Call(typeof(Queryable), "Select", new Type[2] { source.ElementType, lambdaExpression.Body.Type }, source.Expression, Expression.Quote(lambdaExpression))); } public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, params object[] values) { return (IQueryable<T>)((IQueryable)source).OrderBy(ordering, values); } public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values) { if (source == null) { throw new ArgumentNullException("source"); } if (ordering == null) { throw new ArgumentNullException("ordering"); } ParameterExpression[] parameters = new ParameterExpression[1] { Expression.Parameter(source.ElementType, "") }; IEnumerable<DynamicOrdering> enumerable = new ExpressionParser(parameters, ordering, values).ParseOrdering(); Expression expression = source.Expression; string text = "OrderBy"; string text2 = "OrderByDescending"; foreach (DynamicOrdering item in enumerable) { expression = Expression.Call(typeof(Queryable), item.Ascending ? text : text2, new Type[2] { source.ElementType, item.Selector.Type }, expression, Expression.Quote(Expression.Lambda(item.Selector, parameters))); text = "ThenBy"; text2 = "ThenByDescending"; } return source.Provider.CreateQuery(expression); } public static IQueryable Take(this IQueryable source, int count) { if (source == null) { throw new ArgumentNullException("source"); } return source.Provider.CreateQuery(Expression.Call(typeof(Queryable), "Take", new Type[1] { source.ElementType }, source.Expression, Expression.Constant(count))); } public static IQueryable Skip(this IQueryable source, int count) { if (source == null) { throw new ArgumentNullException("source"); } return source.Provider.CreateQuery(Expression.Call(typeof(Queryable), "Skip", new Type[1] { source.ElementType }, source.Expression, Expression.Constant(count))); } public static IQueryable GroupBy(this IQueryable source, string keySelector, string elementSelector, params object[] values) { if (source == null) { throw new ArgumentNullException("source"); } if (keySelector == null) { throw new ArgumentNullException("keySelector"); } if (elementSelector == null) { throw new ArgumentNullException("elementSelector"); } LambdaExpression lambdaExpression = DynamicExpression.ParseLambda(source.ElementType, null, keySelector, values); LambdaExpression lambdaExpression2 = DynamicExpression.ParseLambda(source.ElementType, null, elementSelector, values); return source.Provider.CreateQuery(Expression.Call(typeof(Queryable), "GroupBy", new Type[3] { source.ElementType, lambdaExpression.Body.Type, lambdaExpression2.Body.Type }, source.Expression, Expression.Quote(lambdaExpression), Expression.Quote(lambdaExpression2))); } public static bool Any(this IQueryable source) { if (source == null) { throw new ArgumentNullException("source"); } return (bool)source.Provider.Execute(Expression.Call(typeof(Queryable), "Any", new Type[1] { source.ElementType }, source.Expression)); } public static int Count(this IQueryable source) { if (source == null) { throw new ArgumentNullException("source"); } return (int)source.Provider.Execute(Expression.Call(typeof(Queryable), "Count", new Type[1] { source.ElementType }, source.Expression)); } } internal abstract class DynamicClass { public override string ToString() { PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("{"); for (int i = 0; i < properties.Length; i++) { if (i > 0) { stringBuilder.Append(", "); } stringBuilder.Append(properties[i].Name); stringBuilder.Append("="); stringBuilder.Append(properties[i].GetValue(this, null)); } stringBuilder.Append("}"); return stringBuilder.ToString(); } } internal class DynamicProperty { private string name; private Type type; public string Name => name; public Type Type => type; public DynamicProperty(string name, Type type) { if (name == null) { throw new ArgumentNullException("name"); } if ((object)type == null) { throw new ArgumentNullException("type"); } this.name = name; this.type = type; } } internal static class DynamicExpression { public static Expression Parse(Type resultType, string expression, params object[] values) { return new ExpressionParser(null, expression, values).Parse(resultType); } public static LambdaExpression ParseLambda(Type itType, Type resultType, string expression, params object[] values) { return ParseLambda(new ParameterExpression[1] { Expression.Parameter(itType, "") }, resultType, expression, values); } public static LambdaExpression ParseLambda(ParameterExpression[] parameters, Type resultType, string expression, params object[] values) { return Expression.Lambda(new ExpressionParser(parameters, expression, values).Parse(resultType), parameters); } public static Expression<Func<T, S>> ParseLambda<T, S>(string expression, params object[] values) { return (Expression<Func<T, S>>)ParseLambda(typeof(T), typeof(S), expression, values); } public static Type CreateClass(params DynamicProperty[] properties) { throw new NotImplementedException(); } public static Type CreateClass(IEnumerable<DynamicProperty> properties) { throw new NotImplementedException(); } } internal class DynamicOrdering { public Expression Selector; public bool Ascending; } internal class Signature : IEquatable<Signature> { public DynamicProperty[] properties; public int hashCode; public Signature(IEnumerable<DynamicProperty> properties) { this.properties = properties.ToArray(); hashCode = 0; foreach (DynamicProperty property in properties) { hashCode ^= property.Name.GetHashCode() ^ property.Type.GetHashCode(); } } public override int GetHashCode() { return hashCode; } public override bool Equals(object obj) { if (!(obj is Signature)) { return false; } return Equals((Signature)obj); } public bool Equals(Signature other) { if (properties.Length != other.properties.Length) { return false; } for (int i = 0; i < properties.Length; i++) { if (properties[i].Name != other.properties[i].Name || (object)properties[i].Type != other.properties[i].Type) { return false; } } return true; } } internal sealed class ParseException : Exception { private int position; public int Position => position; public ParseException(string message, int position) : base(message) { this.position = position; } public override string ToString() { return $"{Message} (at index {position})"; } } internal class ExpressionParser { private struct Token { public TokenId id; public string text; public int pos; } private enum TokenId { Unknown, End, Identifier, StringLiteral, IntegerLiteral, RealLiteral, Exclamation, Percent, Amphersand, OpenParen, CloseParen, Asterisk, Plus, Comma, Minus, Dot, Slash, Colon, LessThan, Equal, GreaterThan, Question, OpenBracket, CloseBracket, Bar, ExclamationEqual, DoubleAmphersand, LessThanEqual, LessGreater, DoubleEqual, GreaterThanEqual, DoubleBar } private interface ILogicalSignatures { void F(bool x, bool y); void F(bool? x, bool? y); } private interface IArithmeticSignatures { void F(int x, int y); void F(uint x, uint y); void F(long x, long y); void F(ulong x, ulong y); void F(float x, float y); void F(double x, double y); void F(decimal x, decimal y); void F(int? x, int? y); void F(uint? x, uint? y); void F(long? x, long? y); void F(ulong? x, ulong? y); void F(float? x, float? y); void F(double? x, double? y); void F(decimal? x, decimal? y); } private interface IRelationalSignatures : IArithmeticSignatures { void F(string x, string y); void F(char x, char y); void F(DateTime x, DateTime y); void F(TimeSpan x, TimeSpan y); void F(char? x, char? y); void F(DateTime? x, DateTime? y); void F(TimeSpan? x, TimeSpan? y); } private interface IEqualitySignatures : IRelationalSignatures, IArithmeticSignatures { void F(bool x, bool y); void F(bool? x, bool? y); } private interface IAddSignatures : IArithmeticSignatures { void F(DateTime x, TimeSpan y); void F(TimeSpan x, TimeSpan y); void F(DateTime? x, TimeSpan? y); void F(TimeSpan? x, TimeSpan? y); } private interface ISubtractSignatures : IAddSignatures, IArithmeticSignatures { void F(DateTime x, DateTime y); void F(DateTime? x, DateTime? y); } private interface INegationSignatures { void F(int x); void F(long x); void F(float x); void F(double x); void F(decimal x); void F(int? x); void F(long? x); void F(float? x); void F(double? x); void F(decimal? x); } private interface INotSignatures { void F(bool x); void F(bool? x); } private interface IEnumerableSignatures { void Where(bool predicate); void Any(); void Any(bool predicate); void All(bool predicate); void Count(); void Count(bool predicate); void Min(object selector); void Max(object selector); void Sum(int selector); void Sum(int? selector); void Sum(long selector); void Sum(long? selector); void Sum(float selector); void Sum(float? selector); void Sum(double selector); void Sum(double? selector); void Sum(decimal selector); void Sum(decimal? selector); void Average(int selector); void Average(int? selector); void Average(long selector); void Average(long? selector); void Average(float selector); void Average(float? selector); void Average(double selector); void Average(double? selector); void Average(decimal selector); void Average(decimal? selector); } private class MethodData { public MethodBase MethodBase; public ParameterInfo[] Parameters; public Expression[] Args; } [CompilerGenerated] private sealed class <SelfAndBaseClasses>d__78 : IEnumerable<Type>, IEnumerable, IEnumerator<Type>, IDisposable, IEnumerator { private int <>1__state; private Type <>2__current; private int <>l__initialThreadId; private Type type; public Type <>3__type; Type IEnumerator<Type>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <SelfAndBaseClasses>d__78(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Thread.CurrentThread.ManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: <>1__state = -1; break; case 1: <>1__state = -1; type = type.BaseType; break; } if ((object)type != null) { <>2__current = type; <>1__state = 1; return true; } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<Type> IEnumerable<Type>.GetEnumerator() { <SelfAndBaseClasses>d__78 <SelfAndBaseClasses>d__; if (<>1__state == -2 && <>l__initialThreadId == Thread.CurrentThread.ManagedThreadId) { <>1__state = 0; <SelfAndBaseClasses>d__ = this; } else { <SelfAndBaseClasses>d__ = new <SelfAndBaseClasses>d__78(0); } <SelfAndBaseClasses>d__.type = <>3__type; return <SelfAndBaseClasses>d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<Type>)this).GetEnumerator(); } } private static readonly Type[] predefinedTypes = new Type[20] { typeof(object), typeof(bool), typeof(char), typeof(string), typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(decimal), typeof(DateTime), typeof(TimeSpan), typeof(Guid), typeof(Math), typeof(Convert) }; private static readonly Expression trueLiteral = Expression.Constant(true); private static readonly Expression falseLiteral = Expression.Constant(false); private static readonly Expression nullLiteral = Expression.Constant(null); private static readonly string keywordIt = "it"; private static readonly string keywordIif = "iif"; private static readonly string keywordNew = "new"; private static Dictionary<string, object> keywords; private Dictionary<string, object> symbols; private IDictionary<string, object> externals; private Dictionary<Expression, string> literals; private ParameterExpression it; private string text; private int textPos; private int textLen; private char ch; private Token token; public ExpressionParser(ParameterExpression[] parameters, string expression, object[] values) { if (expression == null) { throw new ArgumentNullException("expression"); } if (keywords == null) { keywords = CreateKeywords(); } symbols = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); literals = new Dictionary<Expression, string>(); if (parameters != null) { ProcessParameters(parameters); } if (values != null) { ProcessValues(values); } text = expression; textLen = text.Length; SetTextPos(0); NextToken(); } private void ProcessParameters(ParameterExpression[] parameters) { foreach (ParameterExpression parameterExpression in parameters) { if (!string.IsNullOrEmpty(parameterExpression.Name)) { AddSymbol(parameterExpression.Name, parameterExpression); } } if (parameters.Length == 1 && string.IsNullOrEmpty(parameters[0].Name)) { it = parameters[0]; } } private void ProcessValues(object[] values) { for (int i = 0; i < values.Length; i++) { object obj = values[i]; if (i == values.Length - 1 && obj is IDictionary<string, object>) { externals = (IDictionary<string, object>)obj; } else { AddSymbol("@" + i.ToString(CultureInfo.InvariantCulture), obj); } } } private void AddSymbol(string name, object value) { if (symbols.ContainsKey(name)) { throw ParseError("The identifier '{0}' was defined more than once", name); } symbols.Add(name, value); } public Expression Parse(Type resultType) { int pos = token.pos; Expression expression = ParseExpression(); if ((object)resultType != null && (expression = PromoteExpression(expression, resultType, exact: true)) == null) { throw ParseError(pos, "Expression of type '{0}' expected", GetTypeName(resultType)); } ValidateToken(TokenId.End, "Syntax error"); return expression; } public IEnumerable<DynamicOrdering> ParseOrdering() { List<DynamicOrdering> list = new List<DynamicOrdering>(); while (true) { Expression selector = ParseExpression(); bool ascending = true; if (TokenIdentifierIs("asc") || TokenIdentifierIs("ascending")) { NextToken(); } else if (TokenIdentifierIs("desc") || TokenIdentifierIs("descending")) { NextToken(); ascending = false; } list.Add(new DynamicOrdering { Selector = selector, Ascending = ascending }); if (token.id != TokenId.Comma) { break; } NextToken(); } ValidateToken(TokenId.End, "Syntax error"); return list; } private Expression ParseExpression() { int pos = token.pos; Expression expression = ParseLogicalOr(); if (token.id == TokenId.Question) { NextToken(); Expression expr = ParseExpression(); ValidateToken(TokenId.Colon, "':' expected"); NextToken(); Expression expr2 = ParseExpression(); expression = GenerateConditional(expression, expr, expr2, pos); } return expression; } private Expression ParseLogicalOr() { Expression left = ParseLogicalAnd(); while (this.token.id == TokenId.DoubleBar || TokenIdentifierIs("or")) { Token token = this.token; NextToken(); Expression right = ParseLogicalAnd(); CheckAndPromoteOperands(typeof(ILogicalSignatures), token.text, ref left, ref right, token.pos); left = Expression.OrElse(left, right); } return left; } private Expression ParseLogicalAnd() { Expression left = ParseComparison(); while (this.token.id == TokenId.DoubleAmphersand || TokenIdentifierIs("and")) { Token token = this.token; NextToken(); Expression right = ParseComparison(); CheckAndPromoteOperands(typeof(ILogicalSignatures), token.text, ref left, ref right, token.pos); left = Expression.AndAlso(left, right); } return left; } private Expression ParseComparison() { Expression left = ParseAdditive(); while (this.token.id == TokenId.Equal || this.token.id == TokenId.DoubleEqual || this.token.id == TokenId.ExclamationEqual || this.token.id == TokenId.LessGreater || this.token.id == TokenId.GreaterThan || this.token.id == TokenId.GreaterThanEqual || this.token.id == TokenId.LessThan || this.token.id == TokenId.LessThanEqual) { Token token = this.token; NextToken(); Expression right = ParseAdditive(); bool flag = token.id == TokenId.Equal || token.id == TokenId.DoubleEqual || token.id == TokenId.ExclamationEqual || token.id == TokenId.LessGreater; if (flag && !left.Type.IsValueType && !right.Type.IsValueType) { if ((object)left.Type != right.Type) { if (left.Type.IsAssignableFrom(right.Type)) { right = Expression.Convert(right, left.Type); } else { if (!right.Type.IsAssignableFrom(left.Type)) { throw IncompatibleOperandsError(token.text, left, right, token.pos); } left = Expression.Convert(left, right.Type); } } } else if (IsEnumType(left.Type) || IsEnumType(right.Type)) { if ((object)left.Type != right.Type) { Expression expression; if ((expression = PromoteExpression(right, left.Type, exact: true)) != null) { right = expression; } else { if ((expression = PromoteExpression(left, right.Type, exact: true)) == null) { throw IncompatibleOperandsError(token.text, left, right, token.pos); } left = expression; } } } else { CheckAndPromoteOperands(flag ? typeof(IEqualitySignatures) : typeof(IRelationalSignatures), token.text, ref left, ref right, token.pos); } switch (token.id) { case TokenId.Equal: case TokenId.DoubleEqual: left = GenerateEqual(left, right); break; case TokenId.ExclamationEqual: case TokenId.LessGreater: left = GenerateNotEqual(left, right); break; case TokenId.GreaterThan: left = GenerateGreaterThan(left, right); break; case TokenId.GreaterThanEqual: left = GenerateGreaterThanEqual(left, right); break; case TokenId.LessThan: left = GenerateLessThan(left, right); break; case TokenId.LessThanEqual: left = GenerateLessThanEqual(left, right); break; } } return left; } private Expression ParseAdditive() { Expression left = ParseMultiplicative(); while (this.token.id == TokenId.Plus || this.token.id == TokenId.Minus || this.token.id == TokenId.Amphersand) { Token token = this.token; NextToken(); Expression right = ParseMultiplicative(); TokenId id = token.id; if (id != TokenId.Amphersand) { if (id != TokenId.Plus) { if (id == TokenId.Minus) { CheckAndPromoteOperands(typeof(ISubtractSignatures), token.text, ref left, ref right, token.pos); left = GenerateSubtract(left, right); } continue; } if ((object)left.Type != typeof(string) && (object)right.Type != typeof(string)) { CheckAndPromoteOperands(typeof(IAddSignatures), token.text, ref left, ref right, token.pos); left = GenerateAdd(left, right); continue; } } left = GenerateStringConcat(left, right); } return left; } private Expression ParseMultiplicative() { Expression left = ParseUnary(); while (this.token.id == TokenId.Asterisk || this.token.id == TokenId.Slash || this.token.id == TokenId.Percent || TokenIdentifierIs("mod")) { Token token = this.token; NextToken(); Expression right = ParseUnary(); CheckAndPromoteOperands(typeof(IArithmeticSignatures), token.text, ref left, ref right, token.pos); switch (token.id) { case TokenId.Asterisk: left = Expression.Multiply(left, right); break; case TokenId.Slash: left = Expression.Divide(left, right); break; case TokenId.Identifier: case TokenId.Percent: left = Expression.Modulo(left, right); break; } } return left; } private Expression ParseUnary() { if (this.token.id == TokenId.Minus || this.token.id == TokenId.Exclamation || TokenIdentifierIs("not")) { Token token = this.token; NextToken(); if (token.id == TokenId.Minus && (this.token.id == TokenId.IntegerLiteral || this.token.id == TokenId.RealLiteral)) { this.token.text = "-" + this.token.text; this.token.pos = token.pos; return ParsePrimary(); } Expression expr = ParseUnary(); if (token.id == TokenId.Minus) { CheckAndPromoteOperand(typeof(INegationSignatures), token.text, ref expr, token.pos); return Expression.Negate(expr); } CheckAndPromoteOperand(typeof(INotSignatures), token.text, ref expr, token.pos); return Expression.Not(expr); } return ParsePrimary(); } private Expression ParsePrimary() { Expression expression = ParsePrimaryStart(); while (true) { if (token.id == TokenId.Dot) { NextToken(); expression = ParseMemberAccess(null, expression); continue; } if (token.id != TokenId.OpenBracket) { break; } expression = ParseElementAccess(expression); } return expression; } private Expression ParsePrimaryStart() { return token.id switch { TokenId.Identifier => ParseIdentifier(), TokenId.StringLiteral => ParseStringLiteral(), TokenId.IntegerLiteral => ParseIntegerLiteral(), TokenId.RealLiteral => ParseRealLiteral(), TokenId.OpenParen => ParseParenExpression(), _ => throw ParseError("Expression expected"), }; } private Expression ParseStringLiteral() { ValidateToken(TokenId.StringLiteral); char c = token.text[0]; string text = token.text.Substring(1, token.text.Length - 2); int startIndex = 0; while (true) { int num = text.IndexOf(c, startIndex); if (num < 0) { break; } text = text.Remove(num, 1); startIndex = num + 1; } if (c == '\'') { if (text.Length != 1) { throw ParseError("Character literal must contain exactly one character"); } NextToken(); return CreateLiteral(text[0], text); } NextToken(); return CreateLiteral(text, text); } private Expression ParseIntegerLiteral() { ValidateToken(TokenId.IntegerLiteral); string text = token.text; if (text[0] != '-') { if (!ulong.TryParse(text, out var result)) { throw ParseError("Invalid integer literal '{0}'", text); } NextToken(); if (result <= int.MaxValue) { return CreateLiteral((int)result, text); } if (result <= uint.MaxValue) { return CreateLiteral((uint)result, text); } if (result <= long.MaxValue) { return CreateLiteral((long)result, text); } return CreateLiteral(result, text); } if (!long.TryParse(text, out var result2)) { throw ParseError("Invalid integer literal '{0}'", text); } NextToken(); if (result2 >= int.MinValue && result2 <= int.MaxValue) { return CreateLiteral((int)result2, text); } return CreateLiteral(result2, text); } private Expression ParseRealLiteral() { ValidateToken(TokenId.RealLiteral); string text = token.text; object obj = null; char c = text[text.Length - 1]; double result2; if (c == 'F' || c == 'f') { if (float.TryParse(text.Substring(0, text.Length - 1), out var result)) { obj = result; } } else if (double.TryParse(text, out result2)) { obj = result2; } if (obj == null) { throw ParseError("Invalid real literal '{0}'", text); } NextToken(); return CreateLiteral(obj, text); } private Expression CreateLiteral(object value, string text) { ConstantExpression constantExpression = Expression.Constant(value); literals.Add(constantExpression, text); return constantExpression; } private Expression ParseParenExpression() { ValidateToken(TokenId.OpenParen, "'(' expected"); NextToken(); Expression result = ParseExpression(); ValidateToken(TokenId.CloseParen, "')' or operator expected"); NextToken(); return result; } private Expression ParseIdentifier() { ValidateToken(TokenId.Identifier); if (keywords.TryGetValue(token.text, out var value)) { if (value is Type) { return ParseTypeAccess((Type)value); } if (value == keywordIt) { return ParseIt(); } if (value == keywordIif) { return ParseIif(); } if (value == keywordNew) { return ParseNew(); } NextToken(); return (Expression)value; } if (symbols.TryGetValue(token.text, out value) || (externals != null && externals.TryGetValue(token.text, out value))) { Expression expression = value as Expression; if (expression == null) { expression = Expression.Constant(value); } else if (expression is LambdaExpression lambda) { return ParseLambdaInvocation(lambda); } NextToken(); return expression; } if (it != null) { return ParseMemberAccess(null, it); } throw ParseError("Unknown identifier '{0}'", token.text); } private Expression ParseIt() { if (it == null) { throw ParseError("No 'it' is in scope"); } NextToken(); return it; } private Expression ParseIif() { int pos = token.pos; NextToken(); Expression[] array = ParseArgumentList(); if (array.Length != 3) { throw ParseError(pos, "The 'iif' function requires three arguments"); } return GenerateConditional(array[0], array[1], array[2], pos); } private Expression GenerateConditional(Expression test, Expression expr1, Expression expr2, int errorPos) { if ((object)test.Type != typeof(bool)) { throw ParseError(errorPos, "The first expression must be of type 'Boolean'"); } if ((object)expr1.Type != expr2.Type) { Expression expression = ((expr2 != nullLiteral) ? PromoteExpression(expr1, expr2.Type, exact: true) : null); Expression expression2 = ((expr1 != nullLiteral) ? PromoteExpression(expr2, expr1.Type, exact: true) : null); if (expression != null && expression2 == null) { expr1 = expression; } else { if (expression2 == null || expression != null) { string text = ((expr1 != nullLiteral) ? expr1.Type.Name : "null"); string text2 = ((expr2 != nullLiteral) ? expr2.Type.Name : "null"); if (expression != null && expression2 != null) { throw ParseError(errorPos, "Both of the types '{0}' and '{1}' convert to the other", text, text2); } throw ParseError(errorPos, "Neither of the types '{0}' and '{1}' converts to the other", text, text2); } expr2 = expression2; } } return Expression.Condition(test, expr1, expr2); } private Expression ParseNew() { NextToken(); ValidateToken(TokenId.OpenParen, "'(' expected"); NextToken(); List<DynamicProperty> list = new List<DynamicProperty>(); List<Expression> list2 = new List<Expression>(); while (true) { int pos = token.pos; Expression expression = ParseExpression(); string name; if (TokenIdentifierIs("as")) { NextToken(); name = GetIdentifier(); NextToken(); } else { if (!(expression is MemberExpression memberExpression)) { throw ParseError(pos, "Expression is missing an 'as' clause"); } name = memberExpression.Member.Name; } list2.Add(expression); list.Add(new DynamicProperty(name, expression.Type)); if (token.id != TokenId.Comma) { break; } NextToken(); } ValidateToken(TokenId.CloseParen, "')' or ',' expected"); NextToken(); Type type = DynamicExpression.CreateClass(list); MemberBinding[] array = new MemberBinding[list.Count]; for (int i = 0; i < array.Length; i++) { array[i] = Expression.Bind(type.GetProperty(list[i].Name), list2[i]); } return Expression.MemberInit(Expression.New(type), array); } private Expression ParseLambdaInvocation(LambdaExpression lambda) { int pos = token.pos; NextToken(); Expression[] array = ParseArgumentList(); if (FindMethod(lambda.Type, "Invoke", staticAccess: false, array, out var _) != 1) { throw ParseError(pos, "Argument list incompatible with lambda expression"); } return Expression.Invoke(lambda, array); } private Expression ParseTypeAccess(Type type) { int pos = token.pos; NextToken(); if (token.id == TokenId.Question) { if (!type.IsValueType || IsNullableType(type)) { throw ParseError(pos, "Type '{0}' has no nullable form", GetTypeName(type)); } type = typeof(Nullable<>).MakeGenericType(type); NextToken(); } if (token.id == TokenId.OpenParen) { Expression[] array = ParseArgumentList(); MethodBase method; switch (FindBestMethod(type.GetConstructors(), array, out method)) { case 0: if (array.Length == 1) { return GenerateConversion(array[0], type, pos); } throw ParseError(pos, "No matching constructor in type '{0}'", GetTypeName(type)); case 1: return Expression.New((ConstructorInfo)method, array); default: throw ParseError(pos, "Ambiguous invocation of '{0}' constructor", GetTypeName(type)); } } ValidateToken(TokenId.Dot, "'.' or '(' expected"); NextToken(); return ParseMemberAccess(type, null); } private Expression GenerateConversion(Expression expr, Type type, int errorPos) { Type type2 = expr.Type; if ((object)type2 == type) { return expr; } if (type2.IsValueType && type.IsValueType) { if ((IsNullableType(type2) || IsNullableType(type)) && (object)GetNonNullableType(type2) == GetNonNullableType(type)) { return Expression.Convert(expr, type); } if (((IsNumericType(type2) || IsEnumType(type2)) && IsNumericType(type)) || IsEnumType(type)) { return Expression.ConvertChecked(expr, type); } } if (type2.IsAssignableFrom(type) || type.IsAssignableFrom(type2) || type2.IsInterface || type.IsInterface) { return Expression.Convert(expr, type); } throw ParseError(errorPos, "A value of type '{0}' cannot be converted to type '{1}'", GetTypeName(type2), GetTypeName(type)); } private Expression ParseMemberAccess(Type type, Expression instance) { if (instance != null) { type = instance.Type; } int pos = token.pos; string identifier = GetIdentifier(); NextToken(); if (token.id == TokenId.OpenParen) { if (instance != null && (object)type != typeof(string)) { Type type2 = FindGenericType(typeof(IEnumerable<>), type); if ((object)type2 != null) { Type elementType = type2.GetGenericArguments()[0]; return ParseAggregate(instance, elementType, identifier, pos); } } Expression[] array = ParseArgumentList(); MethodBase method; switch (FindMethod(type, identifier, instance == null, array, out method)) { case 0: throw ParseError(pos, "No applicable method '{0}' exists in type '{1}'", identifier, GetTypeName(type)); case 1: { MethodInfo methodInfo = (MethodInfo)method; if (!IsPredefinedType(methodInfo.DeclaringType)) { throw ParseError(pos, "Methods on type '{0}' are not accessible", GetTypeName(methodInfo.DeclaringType)); } if ((object)methodInfo.ReturnType == typeof(void)) { throw ParseError(pos, "Method '{0}' in type '{1}' does not return a value", identifier, GetTypeName(methodInfo.DeclaringType)); } return Expression.Call(instance, methodInfo, array); } default: throw ParseError(pos, "Ambiguous invocation of method '{0}' in type '{1}'", identifier, GetTypeName(type)); } } MemberInfo memberInfo = FindPropertyOrField(type, identifier, instance == null); if ((object)memberInfo == null) { throw ParseError(pos, "No property or field '{0}' exists in type '{1}'", identifier, GetTypeName(type)); } if (!(memberInfo is PropertyInfo)) { return Expression.Field(instance, (FieldInfo)memberInfo); } return Expression.Property(instance, (PropertyInfo)memberInfo); } private static Type FindGenericType(Type generic, Type type) { while ((object)type != null && (object)type != typeof(object)) { if (type.IsGenericType && (object)type.GetGenericTypeDefinition() == generic) { return type; } if (generic.IsInterface) { Type[] interfaces = type.GetInterfaces(); foreach (Type type2 in interfaces) { Type type3 = FindGenericType(generic, type2); if ((object)type3 != null) { return type3; } } } type = type.BaseType; } return null; } private Expression ParseAggregate(Expression instance, Type elementType, string methodName, int errorPos) { ParameterExpression parameterExpression = it; ParameterExpression parameterExpression2 = (it = Expression.Parameter(elementType, "")); Expression[] array = ParseArgumentList(); it = parameterExpression; if (FindMethod(typeof(IEnumerableSignatures), methodName, staticAccess: false, array, out var method) != 1) { throw ParseError(errorPos, "No applicable aggregate method '{0}' exists", methodName); } return Expression.Call(typeArguments: (!(method.Name == "Min") && !(method.Name == "Max")) ? new Type[1] { elementType } : new Type[2] { elementType, array[0].Type }, arguments: (array.Length != 0) ? new Expression[2] { instance, Expression.Lambda(array[0], parameterExpression2) } : new Expression[1] { instance }, type: typeof(Enumerable), methodName: method.Name); } private Expression[] ParseArgumentList() { ValidateToken(TokenId.OpenParen, "'(' expected"); NextToken(); Expression[] result = ((token.id != TokenId.CloseParen) ? ParseArguments() : new Expression[0]); ValidateToken(TokenId.CloseParen, "')' or ',' expected"); NextToken(); return result; } private Expression[] ParseArguments() { List<Expression> list = new List<Expression>(); while (true) { list.Add(ParseExpression()); if (token.id != TokenId.Comma) { break; } NextToken(); } return list.ToArray(); } private Expression ParseElementAccess(Expression expr) { int pos = token.pos; ValidateToken(TokenId.OpenBracket, "'(' expected"); NextToken(); Expression[] array = ParseArguments(); ValidateToken(TokenId.CloseBracket, "']' or ',' expected"); NextToken(); if (expr.Type.IsArray) { if (expr.Type.GetArrayRank() != 1 || array.Length != 1) { throw ParseError(pos, "Indexing of multi-dimensional arrays is not supported"); } Expression expression = PromoteExpression(array[0], typeof(int), exact: true); if (expression == null) { throw ParseError(pos, "Array index must be an integer expression"); } return Expression.ArrayIndex(expr, expression); } MethodBase method; return FindIndexer(expr.Type, array, out method) switch { 0 => throw ParseError(pos, "No applicable indexer exists in type '{0}'", GetTypeName(expr.Type)), 1 => Expression.Call(expr, (MethodInfo)method, array), _ => throw ParseError(pos, "Ambiguous invocation of indexer in type '{0}'", GetTypeName(expr.Type)), }; } private static bool IsPredefinedType(Type type) { Type[] array = predefinedTypes; for (int i = 0; i < array.Length; i++) { if ((object)array[i] == type) { return true; } } return false; } private static bool IsNullableType(Type type) { if (type.IsGenericType) { return (object)type.GetGenericTypeDefinition() == typeof(Nullable<>); } return false; } private static Type GetNonNullableType(Type type) { if (!IsNullableType(type)) { return type; } return type.GetGenericArguments()[0]; } private static string GetTypeName(Type type) { Type nonNullableType = GetNonNullableType(type); string text = nonNullableType.Name; if ((object)type != nonNullableType) { text += "?"; } return text; } private static bool IsNumericType(Type type) { return GetNumericTypeKind(type) != 0; } private static bool IsSignedIntegralType(Type type) { return GetNumericTypeKind(type) == 2; } private static bool IsUnsignedIntegralType(Type type) { return GetNumericTypeKind(type) == 3; } private static int GetNumericTypeKind(Type type) { type = GetNonNullableType(type); if (type.IsEnum) { return 0; } switch (Type.GetTypeCode(type)) { case TypeCode.Char: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return 1; case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: return 2; case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return 3; default: return 0; } } private static bool IsEnumType(Type type) { return GetNonNullableType(type).IsEnum; } private void CheckAndPromoteOperand(Type signatures, string opName, ref Expression expr, int errorPos) { Expression[] array = new Expression[1] { expr }; if (FindMethod(signatures, "F", staticAccess: false, array, out var _) != 1) { throw ParseError(errorPos, "Operator '{0}' incompatible with operand type '{1}'", opName, GetTypeName(array[0].Type)); } expr = array[0]; } private void CheckAndPromoteOperands(Type signatures, string opName, ref Expression left, ref Expression right, int errorPos) { Expression[] array = new Expression[2] { left, right }; if (FindMethod(signatures, "F", staticAccess: false, array, out var _) != 1) { throw IncompatibleOperandsError(opName, left, right, errorPos); } left = array[0]; right = array[1]; } private Exception IncompatibleOperandsError(string opName, Expression left, Expression right, int pos) { return ParseError(pos, "Operator '{0}' incompatible with operand types '{1}' and '{2}'", opName, GetTypeName(left.Type), GetTypeName(right.Type)); } private MemberInfo FindPropertyOrField(Type type, string memberName, bool staticAccess) { BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | (staticAccess ? BindingFlags.Static : BindingFlags.Instance); foreach (Type item in SelfAndBaseTypes(type)) { MemberInfo[] array = item.FindMembers(MemberTypes.Field | MemberTypes.Property, bindingAttr, Type.FilterNameIgnoreCase, memberName); if (array.Length != 0) { return array[0]; } } return null; } private int FindMethod(Type type, string methodName, bool staticAccess, Expression[] args, out MethodBase method) { BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | (staticAccess ? BindingFlags.Static : BindingFlags.Instance); foreach (Type item in SelfAndBaseTypes(type)) { MemberInfo[] source = item.FindMembers(MemberTypes.Method, bindingAttr, Type.FilterNameIgnoreCase, methodName); int num = FindBestMethod(source.Cast<MethodBase>(), args, out method); if (num != 0) { return num; } } method = null; return 0; } private int FindIndexer(Type type, Expression[] args, out MethodBase method) { foreach (Type item in SelfAndBaseTypes(type)) { MemberInfo[] defaultMembers = item.GetDefaultMembers(); if (defaultMembers.Length != 0) { IEnumerable<MethodBase> methods = from m in defaultMembers.OfType<PropertyInfo>().Select((Func<PropertyInfo, MethodBase>)((PropertyInfo p) => p.GetGetMethod())) where (object)m != null select m; int num = FindBestMethod(methods, args, out method); if (num != 0) { return num; } } } method = null; return 0; } private static IEnumerable<Type> SelfAndBaseTypes(Type type) { if (type.IsInterface) { List<Type> list = new List<Type>(); AddInterface(list, type); return list; } return SelfAndBaseClasses(type); } private static IEnumerable<Type> SelfAndBaseClasses(Type type) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <SelfAndBaseClasses>d__78(-2) { <>3__type = type }; } private static void AddInterface(List<Type> types, Type type) { if (!types.Contains(type)) { types.Add(type); Type[] interfaces = type.GetInterfaces(); foreach (Type type2 in interfaces) { AddInterface(types, type2); } } } private int FindBestMethod(IEnumerable<MethodBase> methods, Expression[] args, out MethodBase method) { MethodData[] applicable = (from m in methods select new MethodData { MethodBase = m, Parameters = m.GetParameters() } into m where IsApplicable(m, args) select m).ToArray(); if (applicable.Length > 1) { applicable = applicable.Where((MethodData m) => applicable.All((MethodData n) => m == n || IsBetterThan(args, m, n))).ToArray(); } if (applicable.Length == 1) { MethodData methodData = applicable[0]; for (int i = 0; i < args.Length; i++) { args[i] = methodData.Args[i]; } method = methodData.MethodBase; } else { method = null; } return applicable.Length; } private bool IsApplicable(MethodData method, Expression[] args) { if (method.Parameters.Length != args.Length) { return false; } Expression[] array = new Expression[args.Length]; for (int i = 0; i < args.Length; i++) { ParameterInfo parameterInfo = method.Parameters[i]; if (parameterInfo.IsOut) { return false; } Expression expression = PromoteExpression(args[i], parameterInfo.ParameterType, exact: false); if (expression == null) { return false; } array[i] = expression; } method.Args = array; return true; } private Expression PromoteExpression(Expression expr, Type type, bool exact) { if ((object)expr.Type == type) { return expr; } if (expr is ConstantExpression) { ConstantExpression constantExpression = (ConstantExpression)expr; string value; if (constantExpression == nullLiteral) { if (!type.IsValueType || IsNullableType(type)) { return Expression.Constant(null, type); } } else if (literals.TryGetValue(constantExpression, out value)) { Type nonNullableType = GetNonNullableType(type); object obj = null; switch (Type.GetTypeCode(constantExpression.Type)) { case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: obj = ParseNumber(value, nonNullableType); break; case TypeCode.Double: if ((object)nonNullableType == typeof(decimal)) { obj = ParseNumber(value, nonNullableType); } break; case TypeCode.String: obj = ParseEnum(value, nonNullableType); break; } if (obj != null) { return Expression.Constant(obj, type); } } } if (IsCompatibleWith(expr.Type, type)) { if (type.IsValueType || exact) { return Expression.Convert(expr, type); } return expr; } return null; } private static object ParseNumber(string text, Type type) { switch (Type.GetTypeCode(GetNonNullableType(type))) { case TypeCode.SByte: { if (sbyte.TryParse(text, out var result6)) { return result6; } break; } case TypeCode.Byte: { if (byte.TryParse(text, out var result10)) { return result10; } break; } case TypeCode.Int16: { if (short.TryParse(text, out var result2)) { return result2; } break; } case TypeCode.UInt16: { if (ushort.TryParse(text, out var result8)) { return result8; } break; } case TypeCode.Int32: { if (int.TryParse(text, out var result4)) { return result4; } break; } case TypeCode.UInt32: { if (uint.TryParse(text, out var result11)) { return result11; } break; } case TypeCode.Int64: { if (long.TryParse(text, out var result9)) { return result9; } break; } case TypeCode.UInt64: { if (ulong.TryParse(text, out var result7)) { return result7; } break; } case TypeCode.Single: { if (float.TryParse(text, out var result5)) { return result5; } break; } case TypeCode.Double: { if (double.TryParse(text, out var result3)) { return result3; } break; } case TypeCode.Decimal: { if (decimal.TryParse(text, out var result)) { return result; } break; } } return null; } private static object ParseEnum(string name, Type type) { if (type.IsEnum) { MemberInfo[] array = type.FindMembers(MemberTypes.Field, BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public, Type.FilterNameIgnoreCase, name); if (array.Length != 0) { return ((FieldInfo)array[0]).GetValue(null); } } return null; } private static bool IsCompatibleWith(Type source, Type target) { if ((object)source == target) { return true; } if (!target.IsValueType) { return target.IsAssignableFrom(source); } Type nonNullableType = GetNonNullableType(source); Type nonNullableType2 = GetNonNullableType(target); if ((object)nonNullableType != source && (object)nonNullableType2 == target) { return false; } TypeCode typeCode = (nonNullableType.IsEnum ? TypeCode.Object : Type.GetTypeCode(nonNullableType)); TypeCode typeCode2 = (nonNullableType2.IsEnum ? TypeCode.Object : Type.GetTypeCode(nonNullableType2)); switch (typeCode) { case TypeCode.SByte: switch (typeCode2) { case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Byte: if ((uint)(typeCode2 - 6) <= 9u) { return true; } break; case TypeCode.Int16: switch (typeCode2) { case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.UInt16: if ((uint)(typeCode2 - 8) <= 7u) { return true; } break; case TypeCode.Int32: switch (typeCode2) { case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.UInt32: if ((uint)(typeCode2 - 10) <= 5u) { return true; } break; case TypeCode.Int64: if (typeCode2 == TypeCode.Int64 || (uint)(typeCode2 - 13) <= 2u) { return true; } break; case TypeCode.UInt64: if ((uint)(typeCode2 - 12) <= 3u) { return true; } break; case TypeCode.Single: if ((uint)(typeCode2 - 13) <= 1u) { return true; } break; default: if ((object)nonNullableType == nonNullableType2) { return true; } break; } return false; } private static bool IsBetterThan(Expression[] args, MethodData m1, MethodData m2) { bool result = false; for (int i = 0; i < args.Length; i++) { int num = CompareConversions(args[i].Type, m1.Parameters[i].ParameterType, m2.Parameters[i].ParameterType); if (num < 0) { return false; } if (num > 0) { result = true; } } return result; } private static int CompareConversions(Type s, Type t1, Type t2) { if ((object)t1 == t2) { return 0; } if ((object)s == t1) { return 1; } if ((object)s == t2) { return -1; } bool flag = IsCompatibleWith(t1, t2); bool flag2 = IsCompatibleWith(t2, t1); if (flag && !flag2) { return 1; } if (flag2 && !flag) { return -1; } if (IsSignedIntegralType(t1) && IsUnsignedIntegralType(t2)) { return 1; } if (IsSignedIntegralType(t2) && IsUnsignedIntegralType(t1)) { return -1; } return 0; } private Expression GenerateEqual(Expression left, Expression right) { return Expression.Equal(left, right); } private Expression GenerateNotEqual(Expression left, Expression right) { return Expression.NotEqual(left, right); } private Expression GenerateGreaterThan(Expression left, Expression right) { if ((object)left.Type == typeof(string)) { return Expression.GreaterThan(GenerateStaticMethodCall("Compare", left, right), Expression.Constant(0)); } return Expression.GreaterThan(left, right); } private Expression GenerateGreaterThanEqual(Expression left, Expression right) { if ((object)left.Type == typeof(string)) { return Expression.GreaterThanOrEqual(GenerateStaticMethodCall("Compare", left, right), Expression.Constant(0)); } return Expression.GreaterThanOrEqual(left, right); } private Expression GenerateLessThan(Expression left, Expression right) { if ((object)left.Type == typeof(string)) { return Expression.LessThan(GenerateStaticMethodCall("Compare", left, right), Expression.Constant(0)); } return Expression.LessThan(left, right); } private Expression GenerateLessThanEqual(Expression left, Expression right) { if ((object)left.Type == typeof(string)) { return Expression.LessThanOrEqual(GenerateStaticMethodCall("Compare", left, right), Expression.Constant(0)); } return Expression.LessThanOrEqual(left, right); } private Expression GenerateAdd(Expression left, Expression right) { if ((object)left.Type == typeof(string) && (object)right.Type == typeof(string)) { return GenerateStaticMethodCall("Concat", left, right); } return Expression.Add(left, right); } private Expression GenerateSubtract(Expression left, Expression right) { return Expression.Subtract(left, right); } private Expression GenerateStringConcat(Expression left, Expression right) { return Expression.Call(null, typeof(string).GetMethod("Concat", new Type[2] { typeof(object), typeof(object) }), new Expression[2] { left, right }); } private MethodInfo GetStaticMethod(string methodName, Expression left, Expression right) { return left.Type.GetMethod(methodName, new Type[2] { left.Type, right.Type }); } private Expression GenerateStaticMethodCall(string methodName, Expression left, Expression right) { return Expression.Call(null, GetStaticMethod(methodName, left, right), new Expression[2] { left, right }); } private void SetTextPos(int pos) { textPos = pos; ch = ((textPos < textLen) ? text[textPos] : '\0'); } private void NextChar() { if (textPos < textLen) { textPos++; } ch = ((textPos < textLen) ? text[textPos] : '\0'); } private void NextToken() { while (char.IsWhiteSpace(ch)) { NextChar(); } int num = textPos; TokenId id; switch (ch) { case '!': NextChar(); if (ch == '=') { NextChar(); id = TokenId.ExclamationEqual; } else { id = TokenId.Exclamation; } break; case '%': NextChar(); id = TokenId.Percent; break; case '&': NextChar(); if (ch == '&') { NextChar(); id = TokenId.DoubleAmphersand; } else { id = TokenId.Amphersand; } break; case '(': NextChar(); id = TokenId.OpenParen; break; case ')': NextChar(); id = TokenId.CloseParen; break; case '*': NextChar(); id = TokenId.Asterisk; break; case '+': NextChar(); id = TokenId.Plus; break; case ',': NextChar(); id = TokenId.Comma; break; case '-': NextChar(); id = TokenId.Minus; break; case '.': NextChar(); id = TokenId.Dot; break; case '/': NextChar(); id = TokenId.Slash; break; case ':': NextChar(); id = TokenId.Colon; break; case '<': NextChar(); if (ch == '=') { NextChar(); id = TokenId.LessThanEqual; } else if (ch == '>') { NextChar(); id = TokenId.LessGreater; } else { id = TokenId.LessThan; } break; case '=': NextChar(); if (ch == '=') { NextChar(); id = TokenId.DoubleEqual; } else { id = TokenId.Equal; } break; case '>': NextChar(); if (ch == '=') { NextChar(); id = TokenId.GreaterThanEqual; } else { id = TokenId.GreaterThan; } break; case '?': NextChar(); id = TokenId.Question; break; case '[': NextChar(); id = TokenId.OpenBracket; break; case ']': NextChar(); id = TokenId.CloseBracket; break; case '|': NextChar(); if (ch == '|') { NextChar(); id = TokenId.DoubleBar; } else { id = TokenId.Bar; } break; case '"': case '\'': { char c = ch; do { NextChar(); while (textPos < textLen && ch != c) { NextChar(); } if (textPos == textLen) { throw ParseError(textPos, "Unterminated string literal"); } NextChar(); } while (ch == c); id = TokenId.StringLiteral; break; } default: if (char.IsLetter(ch) || ch == '@' || ch == '_') { do { NextChar(); } while (char.IsLetterOrDigit(ch) || ch == '_'); id = TokenId.Identifier; } else if (char.IsDigit(ch)) { id = TokenId.IntegerLiteral; do { NextChar(); } while (char.IsDigit(ch)); if (ch == '.') { id = TokenId.RealLiteral; NextChar(); ValidateDigit(); do { NextChar(); } while (char.IsDigit(ch)); } if (ch == 'E' || ch == 'e') { id = TokenId.RealLiteral; NextChar(); if (ch == '+' || ch == '-') { NextChar(); } ValidateDigit(); do { NextChar(); } while (char.IsDigit(ch)); } if (ch == 'F' || ch == 'f') { NextChar(); } } else { if (textPos != textLen) { throw ParseError(textPos, "Syntax error '{0}'", ch); } id = TokenId.End; } break; } token.id = id; token.text = text.Substring(num, textPos - num); token.pos = num; } private bool TokenIdentifierIs(string id) { if (token.id == TokenId.Identifier) { return string.Equals(id, token.text, StringComparison.OrdinalIgnoreCase); } return false; } private string GetIdentifier() { ValidateToken(TokenId.Identifier, "Identifier expected"); string text = token.text; if (text.Length > 1 && text[0] == '@') { text = text.Substring(1); } return text; } private void ValidateDigit() { if (!char.IsDigit(ch)) { throw ParseError(textPos, "Digit expected"); } } private void ValidateToken(TokenId t, string errorMessage) { if (token.id != t) { throw ParseError(errorMessage); } } private void ValidateToken(TokenId t) { if (token.id != t) { throw ParseError("Syntax error"); } } private Exception ParseError(string format, params object[] args) { return ParseError(token.pos, format, args); } private Exception ParseError(int pos, string format, params object[] args) { return new ParseException(string.Format(CultureInfo.CurrentCulture, format, args), pos); } private static Dictionary<string, object> CreateKeywords() { Dictionary<string, object> dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); dictionary.Add("true", trueLiteral); dictionary.Add("false", falseLiteral); dictionary.Add("null", nullLiteral); dictionary.Add(keywordIt, keywordIt); dictionary.Add(keywordIif, keywordIif); dictionary.Add(keywordNew, keywordNew); Type[] array = predefinedTypes; foreach (Type type in array) { dictionary.Add(type.Name, type); } return dictionary; } } internal static class Res { public const string DuplicateIdentifier = "The identifier '{0}' was defined more than once"; public const string ExpressionTypeMismatch = "Expression of type '{0}' expected"; public const string ExpressionExpected = "Expression expected"; public const string InvalidCharacterLiteral = "Character literal must contain exactly one character"; public const string InvalidIntegerLiteral = "Invalid integer literal '{0}'"; public const string InvalidRealLiteral = "Invalid real literal '{0}'"; public const string UnknownIdentifier = "Unknown identifier '{0}'"; public const string NoItInScope = "No 'it' is in scope"; public const string IifRequiresThreeArgs = "The 'iif' function requires three arguments"; public const string FirstExprMustBeBool = "The first expression must be of type 'Boolean'"; public const string BothTypesConvertToOther = "Both of the types '{0}' and '{1}' convert to the other"; public const string NeitherTypeConvertsToOther = "Neither of the types '{0}' and '{1}' converts to the other"; public const string MissingAsClause = "Expression is missing an 'as' clause"; public const string ArgsIncompatibleWithLambda = "Argument list incompatible with lambda expression"; public const string TypeHasNoNullableForm = "Type '{0}' has no nullable form"; public const string NoMatchingConstructor = "No matching constructor in type '{0}'"; public const string AmbiguousConstructorInvocation = "Ambiguous invocation of '{0}' constructor"; public const string CannotConvertValue = "A value of type '{0}' cannot be converted to type '{1}'"; public const string NoApplicableMethod = "No applicable method '{0}' exists in type '{1}'"; public const string MethodsAreInaccessible = "Methods on type '{0}' are not accessible"; public const string MethodIsVoid = "Method '{0}' in type '{1}' does not return a value"; public const string AmbiguousMethodInvocation = "Ambiguous invocation of method '{0}' in type '{1}'"; public const string UnknownPropertyOrField = "No property or field '{0}' exists in type '{1}'"; public const string NoApplicableAggregate = "No applicable aggregate method '{0}' exists"; public const string CannotIndexMultiDimArray = "Indexing of multi-dimensional arrays is not supported"; public const string InvalidIndex = "Array index must be an integer expression"; public const string NoApplicableIndexer = "No applicable indexer exists in type '{0}'"; public const string AmbiguousIndexerInvocation = "Ambiguous invocation of indexer in type '{0}'"; public const string IncompatibleOperand = "Operator '{0}' incompatible with operand type '{1}'"; public const string IncompatibleOperands = "Operator '{0}' incompatible with operand types '{1}' and '{2}'"; public const string UnterminatedStringLiteral = "Unterminated string literal"; public const string InvalidCharacter = "Syntax error '{0}'"; public const string DigitExpected = "Digit expected"; public const string SyntaxError = "Syntax error"; public const string TokenExpected = "{0} expected"; public const string ParseExceptionFormat = "{0} (at index {1})"; public const string ColonExpected = "':' expected"; public const string OpenParenExpected = "'(' expected"; public const string CloseParenOrOperatorExpected = "')' or operator expected"; public const string CloseParenOrCommaExpected = "')' or ',' expected"; public const string DotOrOpenParenExpected = "'.' or '(' expected"; public const string OpenBracketExpected = "'[' expected"; public const string CloseBracketOrCommaExpected = "']' or ',' expected"; public const string IdentifierExpected = "Identifier expected"; } } namespace SimpleJSON { public enum JSONNodeType { Array = 1, Object = 2, String = 3, Number = 4, NullValue = 5, Boolean = 6, None = 7, Custom = 255 } public enum JSONTextMode { Compact, Indent } public abstract class JSONNode { public struct Enumerator { private enum Type { None, Array, Object } private Type type; private Dictionary<string, JSONNode>.Enumerator m_Object; private List<JSONNode>.Enumerator m_Array; public bool IsValid => type != Type.None; public KeyValuePair<string, JSONNode> Current { get { if (type == Type.Array) { return new KeyValuePair<string, JSONNode>(string.Empty, m_Array.Current); } if (type == Type.Object) { return m_Object.Current; } return new KeyValuePair<string, JSONNode>(string.Empty, null); } } public Enumerator(List<JSONNode>.Enumerator aArrayEnum) { type = Type.Array; m_Object = default(Dictionary<string, JSONNode>.Enumerator); m_Array = aArrayEnum; } public Enumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum) { type = Type.Object; m_Object = aDictEnum; m_Array = default(List<JSONNode>.Enumerator); } public bool MoveNext() { if (type == Type.Array) { return m_Array.MoveNext(); } if (type == Type.Object) { return m_Object.MoveNext(); } return false; } } public struct ValueEnumerator { private Enumerator m_Enumerator; public JSONNode Current => m_Enumerator.Current.Value; public ValueEnumerator(List<JSONNode>.Enumerator aArrayEnum) : this(new Enumerator(aArrayEnum)) { } public ValueEnumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum) : this(new Enumerator(aDictEnum)) { } public ValueEnumerator(Enumerator aEnumerator) { m_Enumerator = aEnumerator; } public bool MoveNext() { return m_Enumerator.MoveNext(); } public ValueEnumerator GetEnumerator() { return this; } } public struct KeyEnumerator { private Enumerator m_Enumerator; public JSONNode Current => m_Enumerator.Current.Key; public KeyEnumerator(List<JSONNode>.Enumerator aArrayEnum) : this(new Enumerator(aArrayEnum)) { } public KeyEnumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum) : this(new Enumerator(aDictEnum)) { } public KeyEnumerator(Enumerator aEnumerator) { m_Enumerator = aEnumerator; } public bool MoveNext() { return m_Enumerator.MoveNext(); } public KeyEnumerator GetEnumerator() { return this; } } public class LinqEnumerator : IEnumerator<KeyValuePair<string, JSONNode>>, IDisposable, IEnumerator, IEnumerable<KeyValuePair<string, JSONNode>>, IEnumerable { private JSONNode m_Node; private Enumerator m_Enumerator; public KeyValuePair<string, JSONNode> Current => m_Enumerator.Current; object IEnumerator.Current => m_Enumerator.Current; internal LinqEnumerator(JSONNode aNode) { m_Node = aNode; if (m_Node != null) { m_Enumerator = m_Node.GetEnumerator(); } } public bool MoveNext() { return m_Enumerator.MoveNext(); } public void Dispose() { m_Node = null; m_Enumerator = default(Enumerator); } public IEnumerator<KeyValuePair<string, JSONNode>> GetEnumerator() { return new LinqEnumerator(m_Node); } public void Reset() { if (m_Node != null) { m_Enumerator = m_Node.GetEnumerator(); } } IEnumerator IEnumerable.GetEnumerator() { return new LinqEnumerator(m_Node); } } [CompilerGenerated] private sealed class <get_Children>d__39 : IEnumerable<JSONNode>, IEnumerable, IEnumerator<JSONNode>, IDisposable, IEnumerator { private int <>1__state; private JSONNode <>2__current; private int <>l__initialThreadId; JSONNode IEnumerator<JSONNode>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <get_Children>d__39(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Thread.CurrentThread.ManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { if (<>1__state != 0) { return false; } <>1__state = -1; return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<JSONNode> IEnumerable<JSONNode>.GetEnumerator() { if (<>1__state == -2 && <>l__initialThreadId == Thread.CurrentThread.ManagedThreadId) { <>1__state = 0; return this; } return new <get_Children>d__39(0); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<JSONNode>)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <get_DeepChildren>d__41 : IEnumerable<JSONNode>, IEnumerable, IEnumerator<JSONNode>, IDisposable, IEnumerator { private int <>1__state; private JSONNode <>2__current; private int <>l__initialThreadId; public JSONNode <>4__this; private IEnumerator<JSONNode> <>7__wrap1; private IEnumerator<JSONNode> <>7__wrap2; JSONNode IEnumerator<JSONNode>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <get_DeepChildren>d__41(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Thread.CurrentThread.ManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if ((uint)(num - -4) <= 1u || num == 1) { try { if (num == -4 || num == 1) { try { } finally { <>m__Finally2(); } } } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>7__wrap2 = null; <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; JSONNode jSONNode = <>4__this; if (num != 0) { if (num != 1) { return false; } <>1__state = -4; goto IL_008d; } <>1__state = -1; <>7__wrap1 = jSONNode.Children.GetEnumerator(); <>1__state = -3; goto IL_00a7; IL_008d: if (<>7__wrap2.MoveNext()) { JSONNode current = <>7__wrap2.Current; <>2__current = current; <>1__state = 1; return true; } <>m__Finally2(); <>7__wrap2 = null; goto IL_00a7; IL_00a7: if (<>7__wrap1.MoveNext()) { JSONNode current2 = <>7__wrap1.Current; <>7__wrap2 = current2.DeepChildren.GetEnumerator(); <>1__state = -4; goto IL_008d; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } private void <>m__Finally2() { <>1__state = -3; if (<>7__wrap2 != null) { <>7__wrap2.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<JSONNode> IEnumerable<JSONNode>.GetEnumerator() { <get_DeepChildren>d__41 result; if (<>1__state == -2 && <>l__initialThreadId == Thread.CurrentThread.ManagedThreadId) { <>1__state = 0; result = this; } else { result = new <get_DeepChildren>d__41(0) { <>4__this = <>4__this }; } return result; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<JSONNode>)this).GetEnumerator(); } } public static bool forceASCII; [ThreadStatic] private static StringBuilder m_EscapeBuilder; public abstract JSONNodeType Tag { get; } public virtual JSONNode this[int aIndex] { get { return null; } set { } } public virtual JSONNode this[string aKey] { get { return null; } set { } } public virtual string Value { get { return ""; } set { } } public virtual int Count => 0; public virtual bool IsNumber => false; public virtual bool IsString => false; public virtual bool IsBoolean => false; public virtual bool IsNull => false; public virtual bool IsArray => false; public virtual bool IsObject => false; public virtual bool Inline { get { return false; } set { } } public virtual IEnumerable<JSONNode> Children => new <get_Children>d__39(-2); public IEnumerable<JSONNode> DeepChildren => new <get_DeepChildren>d__41(-2) { <>4__this = this }; public IEnumerable<KeyValuePair<string, JSONNode>> Linq => new LinqEnumerator(this); public KeyEnumerator Keys => new KeyEnumerator(GetEnumerator()); public ValueEnumerator Values => new ValueEnumerator(GetEnumerator()); public virtual double AsDouble { get { double result = 0.0; if (double.TryParse(Value, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out result)) { return result; } return 0.0; } set { Value = value.ToString(CultureInfo.InvariantCulture); } } public virtual int AsInt { get { return (int)AsDouble; } set { AsDouble = value; } } public virtual float AsFloat { get { return (float)AsDouble; } set { AsDouble = value; } } public virtual bool AsBool { get { bool result = false; if (bool.TryParse(Value, out result)) { return result; } return !string.IsNullOrEmpty(Value); } set { Value = (value ? "true" : "false"); } } public virtual JSONArray AsArray => this as JSONArray; public virtual JSONObject AsObject => this as JSONObject; internal static StringBuilder EscapeBuilder { get { if (m_EscapeBuilder == null) { m_EscapeBuilder = new StringBuilder(); } return m_EscapeBuilder; } } public virtual void Add(string aKey, JSONNode aItem) { } public virtual void Add(JSONNode aItem) { Add("", aItem); } public virtual JSONNode Remove(string aKey) { return null; } public virtual JSONNode Remove(int aIndex) { return null; } public virtual JSONNode Remove(JSONNode aNode) { return aNode; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); WriteToStringBuilder(stringBuilder, 0, 0, JSONTextMode.Compact); return stringBuilder.ToString(); } public virtual string ToString(int aIndent) { StringBuilder stringBuilder = new StringBuilder(); WriteToStringBuilder(stringBuilder, 0, aIndent, JSONTextMode.Indent); return stringBuilder.ToString(); } internal abstract void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode); public abstract Enumerator GetEnumerator(); public static implicit operator JSONNode(string s) { return new JSONString(s); } public static implicit operator string(JSONNode d) { if (!(d == null)) { return d.Value; } return null; } public static implicit operator JSONNode(double n) { return new JSONNumber(n); } public static implicit operator double(JSONNode d) { if (!(d == null)) { return d.AsDouble; } return 0.0; } public static implicit operator JSONNode(float n) { return new JSONNumber(n); } public static implicit operator float(JSONNode d) { if (!(d == null)) { return d.AsFloat; } return 0f; } public static implicit operator JSONNode(int n) { return new JSONNumber(n); } public static implicit operator int(JSONNode d) { if (!(d == null)) { return d.AsInt; } return 0; } public static implicit operator JSONNode(bool b) { return new JSONBool(b); } public static implicit operator bool(JSONNode d) { if (!(d == null)) { return d.AsBool; } return false; } public static implicit operator JSONNode(KeyValuePair<string, JSONNode> aKeyValue) { return aKeyValue.Value; } public static bool operator ==(JSONNode a, object b) { if ((object)a == b) { return true; } bool flag = a is JSONNull || (object)a == null || a is JSONLazyCreator; bool flag2 = b is JSONNull || b == null || b is JSONLazyCreator; if (flag && flag2) { return true; } if (!flag) { return a.Equals(b); } return false; } public static bool operator !=(JSONNode a, object b) { return !(a == b); } public override bool Equals(object obj) { return (object)this == obj; } public override int GetHashCode() { return base.GetHashCode(); } internal static string Escape(string aText) { StringBuilder escapeBuilder = EscapeBuilder; escapeBuilder.Length = 0; if (escapeBuilder.Capacity < aText.Length + aText.Length / 10) { escapeBuilder.Capacity = aText.Length + aText.Length / 10; } foreach (char c in aText) { switch (c) { case '\\': escapeBuilder.Append("\\\\"); continue; case '"': escapeBuilder.Append("\\\""); continue; case '\n': escapeBuilder.Append("\\n"); continue; case '\r': escapeBuilder.Append("\\r"); continue; case '\t': escapeBuilder.Append("\\t"); continue; case '\b': escapeBuilder.Append("\\b"); continue; case '\f': escapeBuilder.Append("\\f"); continue; } if (c < ' ' || (forceASCII && c > '\u007f')) { ushort num = c; escapeBuilder.Append("\\u").Append(num.ToString("X4")); } else { escapeBuilder.Append(c); } } string result = escapeBuilder.ToString(); escapeBuilder.Length = 0; return result; } private static void ParseElement(JSONNode ctx, string token, string tokenName, bool quoted) { if (quoted) { ctx.Add(tokenName, token); return; } string text = token.ToLower(); switch (text) { case "false": case "true": ctx.Add(tokenName, text == "true"); return; case "null": ctx.Add(tokenName, null); return; } if (double.TryParse(token, out var result)) { ctx.Add(tokenName, result); } else { ctx.Add(tokenName, token); } } public static JSONNode Parse(string aJSON) { Stack<JSONNode> stack = new Stack<JSONNode>(); JSONNode jSONNode = null; int i = 0; StringBuilder stringBuilder = new StringBuilder(); string text = ""; bool flag = false; bool flag2 = false; for (; i < aJSON.Length; i++) { switch (aJSON[i]) { case '{': if (flag) { stringBuilder.Append(aJSON[i]); break; } stack.Push(new JSONObject()); if (jSONNode != null) { jSONNode.Add(text, stack.Peek()); } text = ""; stringBuilder.Length = 0; jSONNode = stack.Peek(); break; case '[': if (flag) { stringBuilder.Append(aJSON[i]); break; } stack.Push(new JSONArray()); if (jSONNode != null) { jSONNode.Add(text, stack.Peek()); } text = ""; stringBuilder.Length = 0; jSONNode = stack.Peek(); break; case ']': case '}': if (flag) { stringBuilder.Append(aJSON[i]); break; } if (stack.Count == 0) { throw new Exception("JSON Parse: Too many closing brackets"); } stack.Pop(); if (stringBuilder.Length > 0 || flag2) { ParseElement(jSONNode, stringBuilder.ToString(), text, flag2); flag2 = false; } text = ""; stringBuilder.Length = 0; if (stack.Count > 0) { jSONNode = stack.Peek(); } break; case ':': if (flag) { stringBuilder.Append(aJSON[i]); break; } text = stringBuilder.ToString(); stringBuilder.Length = 0; flag2 = false; break; case '"': flag = !flag; flag2 = flag2 || flag; break; case ',': if (flag) { stringBuilder.Append(aJSON[i]); break; } if (stringBuilder.Length > 0 || flag2) { ParseElement(jSONNode, stringBuilder.ToString(), text, flag2); flag2 = false; } text = ""; stringBuilder.Length = 0; flag2 = false; break; case '\t': case ' ': if (flag) { stringBuilder.Append(aJSON[i]); } break; case '\\': i++; if (flag) { char c = aJSON[i]; switch (c) { case 't': stringBuilder.Append('\t'); break; case 'r': stringBuilder.Append('\r'); break; case 'n': stringBuilder.Append('\n'); break; case 'b': stringBuilder.Append('\b'); break; case 'f': stringBuilder.Append('\f'); break; case 'u': { string s = aJSON.Substring(i + 1, 4); stringBuilder.Append((char)int.Parse(s, NumberStyles.AllowHexSpecifier)); i += 4; break; } default: stringBuilder.Append(c); break; } } break; default: stringBuilder.Append(aJSON[i]); break; case '\n': case '\r': break; } } if (flag) { throw new Exception("JSON Parse: Quotation marks seems to be messed up."); } return jSONNode; } } public class JSONArray : JSONNode { [CompilerGenerated] private sealed class <get_Children>d__22 : IEnumerable<JSONNode>, IEnumerable, IEnumerator<JSONNode>, IDisposable, IEnumerator { private int <>1__state; private JSONNode <>2__current; private int <>l__initialThreadId; public JSONArray <>4__this; private List<JSONNode>.Enumerator <>7__wrap1; JSONNode IEnumerator<JSONNode>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <get_Children>d__22(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Thread.CurrentThread.ManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>7__wrap1 = default(List<JSONNode>.Enumerator); <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; JSONArray jSONArray = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = jSONArray.m_List.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (<>7__wrap1.MoveNext()) { JSONNode current = <>7__wrap1.Current; <>2__current = current; <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap1 = default(List<JSONNode>.Enumerator); return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; ((IDisposable)<>7__wrap1).Dispose(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<JSONNode> IEnumerable<JSONNode>.GetEnumerator() { <get_Children>d__22 result; if (<>1__state == -2 && <>l__initialThreadId == Thread.CurrentThread.ManagedThreadId) { <>1__state = 0; result = this; } else { result = new <get_Children>d__22(0) { <>4__this = <>4__this }; } return result; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<JSONNode>)this).GetEnumerator(); } } private List<JSONNode> m_List = new List<JSONNode>(); private bool inline; public override bool Inline { get { return inline; } set { inline = value; } } public override JSONNodeType Tag => JSONNodeType.Array; public override bool IsArray => true; public override JSONNode this[int aIndex] { get { if (aIndex < 0 || aIndex >= m_List.Count) { return new JSONLazyCreator(this); } return m_List[aIndex]; } set { if (value == null) { value = JSONNull.CreateOrGet(); } if (aIndex < 0 || aIndex >= m_List.Count) { m_List.Add(value); } else { m_List[aIndex] = value; } } } public override JSONNode this[string aKey] { get { return new JSONLazyCreator(this); } set { if (value == null) { value = JSONNull.CreateOrGet(); } m_List.Add(value); } } public override int Count => m_List.Count; public override IEnumerable<JSONNode> Children => new <get_Children>d__22(-2) { <>4__this = this }; public override Enumerator GetEnumerator() { return new Enumerator(m_List.GetEnumerator()); } public override void Add(string aKey, JSONNode aItem) { if (aItem == null) { aItem = JSONNull.CreateOrGet(); } m_List.Add(aItem); } public override JSONNode Remove(int aIndex) { if (aIndex < 0 || aIndex >= m_List.Count) { return null; } JSONNode result = m_List[aIndex]; m_List.RemoveAt(aIndex); return result; } public override JSONNode Remove(JSONNode aNode) { m_List.Remove(aNode); return aNode; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append('['); int count = m_List.Count; if (inline) { aMode = JSONTextMode.Compact; } for (int i = 0; i < count; i++) { if (i > 0) { aSB.Append(','); } if (aMode == JSONTextMode.Indent) { aSB.AppendLine(); } if (aMode == JSONTextMode.Indent) { aSB.Append(' ', aIndent + aIndentInc); } m_List[i].WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode); } if (aMode == JSONTextMode.Indent) { aSB.AppendLine().Append(' ', aIndent); } aSB.Append(']'); } } public class JSONObject : JSONNode { [CompilerGenerated] private sealed class <get_Children>d__23 : IEnumerable<JSONNode>, IEnumerable, IEnumerator<JSONNode>, IDisposable, IEnumerator { private int <>1__state; private JSONNode <>2__current; private int <>l__initialThreadId; public JSONObject <>4__this; private Dictionary<string, JSONNode>.Enumerator <>7__wrap1; JSONNode IEnumerator<JSONNode>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <get_Children>d__23(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Thread.CurrentThread.ManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>7__wrap1 = default(Dictionary<string, JSONNode>.Enumerator); <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; JSONObject jSONObject = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = jSONObject.m_Dict.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (<>7__wrap1.MoveNext()) { <>2__current = <>7__wrap1.Current.Value; <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap1 = default(Dictionary<string, JSONNode>.Enumerator); return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; ((IDisposable)<>7__wrap1).Dispose(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<JSONNode> IEnumerable<JSONNode>.GetEnumerator() { <get_Children>d__23 result; if (<>1__state == -2 && <>l__initialThreadId == Thread.CurrentThread.ManagedThreadId) { <>1__state = 0; result = this; } else { result = new <get_Children>d__23(0) { <>4__this = <>4__this }; } return result; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<JSONNode>)this).GetEnumerator(); } } private Dictionary<string, JSONNode> m_Dict = new Dictionary<string, JSONNode>(); private bool inline; public override bool Inline { get { return inline; } set { inline = value; } } public override JSONNodeType Tag => JSONNodeType.Object; public override bool IsObject => true; public override JSONNode this[string aKey] { get { if (m_Dict.ContainsKey(aKey)) { return m_Dict[aKey]; } return new JSONLazyCreator(this, aKey); } set { if (value == null) { value = JSONNull.CreateOrGet(); } if (m_Dict.ContainsKey(aKey)) { m_Dict[aKey] = value; } else { m_Dict.Add(aKey, value); } } } public override JSONNode this[int aIndex] { get { if (aIndex < 0 || aIndex >= m_Dict.Count) { return null; } return m_Dict.ElementAt(aIndex).Value; } set { if (value == null) { value = JSONNull.CreateOrGet(); } if (aIndex >= 0 && aIndex < m_Dict.Count) { string key = m_Dict.ElementAt(aIndex).Key; m_Dict[key] = value; } } } public override int Count => m_Dict.Count; public override IEnumerable<JSONNode> Children => new <get_Children>d__23(-2) { <>4__this = this }; public override Enumerator GetEnumerator() { return new Enumerator(m_Dict.GetEnumerator()); } public override void Add(string aKey, JSONNode aItem) { if (aItem == null) { aItem = JSONNull.CreateOrGet(); } if (!string.IsNullOrEmpty(aKey)) { if (m_Dict.ContainsKey(aKey)) { m_Dict[aKey] = aItem; } else { m_Dict.Add(aKey, aItem); } } else { m_Dict.Add(Guid.NewGuid().ToString(), aItem); } } public override JSONNode Remove(string aKey) { if (!m_Dict.ContainsKey(aKey)) { return null; } JSONNode result = m_Dict[aKey]; m_Dict.Remove(aKey); return result; } public override JSONNode Remove(int aIndex) { if (aIndex < 0 || aIndex >= m_Dict.Count) { return null; } KeyValuePair<string, JSONNode> keyValuePair = m_Dict.ElementAt(aIndex); m_Dict.Remove(keyValuePair.Key); return keyValuePair.Value; } public override JSONNode Remove(JSONNode aNode) { try { KeyValuePair<string, JSONNode> keyValuePair = m_Dict.Where((KeyValuePair<string, JSONNode> k) => k.Value == aNode).First(); m_Dict.Remove(keyValuePair.Key); return aNode; } catch { return null; } } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append('{'); bool flag = true; if (inline) { aMode = JSONTextMode.Compact; } foreach (KeyValuePair<string, JSONNode> item in m_Dict) { if (!flag) { aSB.Append(','); } flag = false; if (aMode == JSONTextMode.Indent) { aSB.AppendLine(); } if (aMode == JSONTextMode.Indent) { aSB.Append(' ', aIndent + aIndentInc); } aSB.Append('"').Append(JSONNode.Escape(item.Key)).Append('"'); if (aMode == JSONTextMode.Compact) { aSB.Append(':'); } else { aSB.Append(" : "); } item.Value.WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode); } if (aMode == JSONTextMode.Indent) { aSB.AppendLine().Append(' ', aIndent); } aSB.Append('}'); } } public class JSONString : JSONNode { private string m_Data; public override JSONNodeType Tag => JSONNodeType.String; public override bool IsString => true; public override string Value { get { return m_Data; } set { m_Data = value; } } public override Enumerator GetEnumerator() { return default(Enumerator); } public JSONString(string aData) { m_Data = aData; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append('"').Append(JSONNode.Escape(m_Data)).Append('"'); } public override bool Equals(object obj) { if (base.Equals(obj)) { return true; } if (obj is string text) { return m_Data == text; } JSONString jSONString = obj as JSONString; if (jSONString != null) { return m_Data == jSONString.m_Data; } return false; } public override int GetHashCode() { return m_Data.GetHashCode(); } } public class JSONNumber : JSONNode { private double m_Data; public override JSONNodeType Tag => JSONNodeType.Number; public override bool IsNumber => true; public override string Value { get { return m_Data.ToString(CultureInfo.InvariantCulture); } set { if (double.TryParse(value, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var result)) { m_Data = result; } } } public override double AsDouble { get { return m_Data; } set { m_Data = value; } } public override Enumerator GetEnumerator() { return default(Enumerator); } public JSONNumber(double aData) { m_Data = aData; } public JSONNumber(string aData) { Value = aData; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append(m_Data); } private static bool IsNumeric(object value) { if (!(value is int) && !(value is uint) && !(value is float) && !(value is double) && !(value is decimal) && !(value is long) && !(value is ulong) && !(value is short) && !(value is ushort) && !(value is sbyte)) { return value is byte; } return true; } public override bool Equals(object obj) { if (obj == null) { return false; } if (base.Equals(obj)) { return true; } JSONNumber jSONNumber = obj as JSONNumber; if (jSONNumber != null) { return m_Data == jSONNumber.m_Data; } if (IsNumeric(obj)) { return Convert.ToDouble(obj) == m_Data; } return false; } public override int GetHashCode() { return m_Data.GetHashCode(); } } public class JSONBool : JSONNode { private bool m_Data; public override JSONNodeType Tag => JSONNodeType.Boolean; public override bool IsBoolean => true; public override string Value { get { return m_Data.ToString(); } set { if (bool.TryParse(value, out var result)) { m_Data = result; } } } public override bool AsBool { get { return m_Data; } set { m_Data = value; } } public override Enumerator GetEnumerator() { return default(Enumerator); } public JSONBool(bool aData) { m_Data = aData; } public JSONBool(string aData) { Value = aData; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append(m_Data ? "true" : "false"); } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is bool) { return m_Data == (bool)obj; } return false; } public override int GetHashCode() { return m_Data.GetHashCode(); } } public class JSONNull : JSONNode { private static JSONNull m_StaticInstance = new JSONNull(); public static bool reuseSameInstance = true; public override JSONNodeType Tag => JSONNodeType.NullValue; public override bool IsNull => true; public override string Value { get { return "null"; } set { } } public override bool AsBool { get { return false; } set { } } public static JSONNull CreateOrGet() { if (reuseSameInstance) { return m_StaticInstance; } return new JSONNull(); } private JSONNull() { } public override Enumerator GetEnumerator() { return default(Enumerator); } public override bool Equals(object obj) { if ((object)this == obj) { return true; } return obj is JSONNull; } public override int GetHashCode() { return 0; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append("null"); } } internal class JSONLazyCreator : JSONNode { private JSONNode m_Node; private string m_Key; public override JSONNodeType Tag => JSONNodeType.None; public override JSONNode this[int aIndex] { get { return new JSONLazyCreator(this); } set { JSONArray jSONArray = new JSONArray(); jSONArray.Add(value); Set(jSONArray); } } public override JSONNode this[string aKey] { get { return new JSONLazyCreator(this, aKey); } set { JSONObject jSONObject = new JSONObject(); jSONObject.Add(aKey, value); Set(jSONObject); } } public override int AsInt { get { JSONNumber aVal = new JSONNumber(0.0); Set(aVal); return 0; } set { JSONNumber aVal = new JSONNumber(value); Set(aVal); } } public override float AsFloat
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.AutoTranslator/XUnity.AutoTranslator.Plugin.ExtProtocol.dll
Decompiled 4 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyDescription("Package that contains a simple inter-process protocol format used in XUnity.")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyInformationalVersion("1.0.1+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("XUnity.AutoTranslator.Plugin.ExtProtocol")] [assembly: AssemblyTitle("XUnity.AutoTranslator.Plugin.ExtProtocol")] [assembly: AssemblyVersion("1.0.1.0")] namespace XUnity.AutoTranslator.Plugin.ExtProtocol; public class ConfigurationMessage : ProtocolMessage { public static readonly string Type = "4"; public string Config { get; set; } internal override void Decode(TextReader reader) { base.Id = new Guid(reader.ReadLine()); Config = reader.ReadToEnd(); } internal override void Encode(TextWriter writer) { writer.WriteLine(base.Id.ToString()); writer.Write(Config); } } public static class ExtProtocolConvert { private static readonly Dictionary<string, Type> IdToType; private static readonly Dictionary<Type, string> TypeToId; static ExtProtocolConvert() { IdToType = new Dictionary<string, Type>(); TypeToId = new Dictionary<Type, string>(); Register(TranslationRequest.Type, typeof(TranslationRequest)); Register(TranslationResponse.Type, typeof(TranslationResponse)); Register(TranslationError.Type, typeof(TranslationError)); Register(ConfigurationMessage.Type, typeof(ConfigurationMessage)); } public static void Register(string id, Type type) { IdToType[id] = type; TypeToId[type] = id; } public static string Encode(ProtocolMessage message) { StringWriter stringWriter = new StringWriter(); string value = TypeToId[message.GetType()]; stringWriter.WriteLine(value); message.Encode(stringWriter); return Convert.ToBase64String(Encoding.UTF8.GetBytes(stringWriter.ToString()), Base64FormattingOptions.None); } public static ProtocolMessage Decode(string message) { StringReader stringReader = new StringReader(Encoding.UTF8.GetString(Convert.FromBase64String(message))); string key = stringReader.ReadLine(); ProtocolMessage obj = (ProtocolMessage)Activator.CreateInstance(IdToType[key]); obj.Decode(stringReader); return obj; } } public abstract class ProtocolMessage { public Guid Id { get; set; } internal abstract void Decode(TextReader reader); internal abstract void Encode(TextWriter writer); } public enum StatusCode { OK = 0, Blocked = 1, Unknown = 1000 } public class TranslationError : ProtocolMessage { public static readonly string Type = "3"; public string Reason { get; set; } public StatusCode FailureCode { get; set; } internal override void Decode(TextReader reader) { base.Id = new Guid(reader.ReadLine()); FailureCode = (StatusCode)int.Parse(reader.ReadLine()); Reason = reader.ReadToEnd(); } internal override void Encode(TextWriter writer) { writer.WriteLine(base.Id.ToString()); writer.WriteLine((int)FailureCode); writer.Write(Reason); } } public class TranslationRequest : ProtocolMessage { public static readonly string Type = "1"; private string[] _untranslatedTexts; public string SourceLanguage { get; set; } public string DestinationLanguage { get; set; } public string[] UntranslatedTexts => _untranslatedTexts ?? (_untranslatedTexts = UntranslatedTextInfos.Select((TransmittableUntranslatedTextInfo x) => x.UntranslatedText).ToArray()); public TransmittableUntranslatedTextInfo[] UntranslatedTextInfos { get; set; } internal override void Decode(TextReader reader) { base.Id = new Guid(reader.ReadLine()); SourceLanguage = reader.ReadLine(); DestinationLanguage = reader.ReadLine(); int num = int.Parse(reader.ReadLine(), CultureInfo.InvariantCulture); TransmittableUntranslatedTextInfo[] array = new TransmittableUntranslatedTextInfo[num]; for (int i = 0; i < num; i++) { TransmittableUntranslatedTextInfo transmittableUntranslatedTextInfo = new TransmittableUntranslatedTextInfo(); transmittableUntranslatedTextInfo.Decode(reader); array[i] = transmittableUntranslatedTextInfo; } UntranslatedTextInfos = array; } internal override void Encode(TextWriter writer) { writer.WriteLine(base.Id.ToString()); writer.WriteLine(SourceLanguage); writer.WriteLine(DestinationLanguage); writer.WriteLine(UntranslatedTextInfos.Length.ToString(CultureInfo.InvariantCulture)); TransmittableUntranslatedTextInfo[] untranslatedTextInfos = UntranslatedTextInfos; for (int i = 0; i < untranslatedTextInfos.Length; i++) { untranslatedTextInfos[i].Encode(writer); } } } public class TranslationResponse : ProtocolMessage { public static readonly string Type = "2"; public string[] TranslatedTexts { get; set; } internal override void Decode(TextReader reader) { base.Id = new Guid(reader.ReadLine()); int num = int.Parse(reader.ReadLine(), CultureInfo.InvariantCulture); string[] array = new string[num]; for (int i = 0; i < num; i++) { string s = reader.ReadLine(); string @string = Encoding.UTF8.GetString(Convert.FromBase64String(s)); array[i] = @string; } TranslatedTexts = array; } internal override void Encode(TextWriter writer) { writer.WriteLine(base.Id.ToString()); writer.WriteLine(TranslatedTexts.Length.ToString(CultureInfo.InvariantCulture)); string[] translatedTexts = TranslatedTexts; foreach (string s in translatedTexts) { string value = Convert.ToBase64String(Encoding.UTF8.GetBytes(s), Base64FormattingOptions.None); writer.WriteLine(value); } } } public class TransmittableUntranslatedTextInfo { public string[] ContextBefore { get; set; } public string UntranslatedText { get; set; } public string[] ContextAfter { get; set; } public TransmittableUntranslatedTextInfo(string[] contextBefore, string untranslatedText, string[] contextAfter) { ContextBefore = contextBefore; UntranslatedText = untranslatedText; ContextAfter = contextAfter; } public TransmittableUntranslatedTextInfo() { } internal void Encode(TextWriter writer) { string[] contextBefore = ContextBefore; writer.WriteLine(((contextBefore != null) ? contextBefore.Length : 0).ToString(CultureInfo.InvariantCulture)); if (ContextBefore != null) { string[] contextBefore2 = ContextBefore; foreach (string s in contextBefore2) { string value = Convert.ToBase64String(Encoding.UTF8.GetBytes(s), Base64FormattingOptions.None); writer.WriteLine(value); } } string[] contextAfter = ContextAfter; writer.WriteLine(((contextAfter != null) ? contextAfter.Length : 0).ToString(CultureInfo.InvariantCulture)); if (ContextAfter != null) { string[] contextBefore2 = ContextAfter; foreach (string s2 in contextBefore2) { string value2 = Convert.ToBase64String(Encoding.UTF8.GetBytes(s2), Base64FormattingOptions.None); writer.WriteLine(value2); } } string value3 = Convert.ToBase64String(Encoding.UTF8.GetBytes(UntranslatedText), Base64FormattingOptions.None); writer.WriteLine(value3); } internal void Decode(TextReader reader) { int num = int.Parse(reader.ReadLine(), CultureInfo.InvariantCulture); string[] array = new string[num]; for (int i = 0; i < num; i++) { string s = reader.ReadLine(); string @string = Encoding.UTF8.GetString(Convert.FromBase64String(s)); array[i] = @string; } ContextBefore = array; int num2 = int.Parse(reader.ReadLine(), CultureInfo.InvariantCulture); string[] array2 = new string[num2]; for (int j = 0; j < num2; j++) { string s2 = reader.ReadLine(); string string2 = Encoding.UTF8.GetString(Convert.FromBase64String(s2)); array2[j] = string2; } ContextAfter = array2; string s3 = reader.ReadLine(); string string3 = Encoding.UTF8.GetString(Convert.FromBase64String(s3)); UntranslatedText = string3; } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "1.0.1"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.ResourceRedirector/XUnity.ResourceRedirector.BepInEx.dll
Decompiled 4 days agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using BepInEx; using BepInEx.Configuration; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme, Bepis, others at https://github.com/bbepis/XUnity.AutoTranslator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyInformationalVersion("2.1.0+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("XUnity.ResourceRedirector.BepInEx")] [assembly: AssemblyTitle("XUnity.ResourceRedirector.BepInEx")] [assembly: AssemblyVersion("2.1.0.0")] namespace XUnity.ResourceRedirector.BepInEx; [BepInPlugin("gravydevsupreme.xunity.resourceredirector", "XUnity Resource Redirector", "2.1.0")] public class ResourceRedirectorPlugin : BaseUnityPlugin { public static ConfigEntry<bool> LogAllLoadedResources { get; set; } public static ConfigEntry<bool> LogCallbackOrder { get; set; } private void Awake() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown LogAllLoadedResources = ((BaseUnityPlugin)this).Config.Bind<bool>(new ConfigDefinition("Diagnostics", "Log all loaded resources"), false, (ConfigDescription)null); ResourceRedirection.LogAllLoadedResources = LogAllLoadedResources.Value; LogAllLoadedResources.SettingChanged += delegate { ResourceRedirection.LogAllLoadedResources = LogAllLoadedResources.Value; }; LogCallbackOrder = ((BaseUnityPlugin)this).Config.Bind<bool>(new ConfigDefinition("Diagnostics", "Log callback order"), false, (ConfigDescription)null); ResourceRedirection.LogCallbackOrder = LogCallbackOrder.Value; LogCallbackOrder.SettingChanged += delegate { ResourceRedirection.LogCallbackOrder = LogCallbackOrder.Value; }; ((BaseUnityPlugin)this).Config.ConfigReloaded += Config_ConfigReloaded; } private static void Config_ConfigReloaded(object sender, EventArgs e) { ResourceRedirection.LogAllLoadedResources = LogAllLoadedResources.Value; ResourceRedirection.LogCallbackOrder = LogCallbackOrder.Value; } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "2.1.0"; }
BepInEx/plugins/Hayrizan-XUnity_AutoTranslator/XUnity.ResourceRedirector/XUnity.ResourceRedirector.dll
Decompiled 4 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis; using UnityEngine; using XUnity.Common.Constants; using XUnity.Common.Extensions; using XUnity.Common.Harmony; using XUnity.Common.Logging; using XUnity.Common.MonoMod; using XUnity.Common.Utilities; using XUnity.ResourceRedirector.Constants; using XUnity.ResourceRedirector.Hooks; using XUnity.ResourceRedirector.Properties; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("gravydevsupreme")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2018 / MIT License")] [assembly: AssemblyDescription("Main development dependency for XUnity Resource Redirector.")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyInformationalVersion("2.1.0+7f1f3b9e8fc7d93a97734773804ba9c8fdf57714")] [assembly: AssemblyProduct("XUnity.ResourceRedirector")] [assembly: AssemblyTitle("XUnity.ResourceRedirector")] [assembly: AssemblyVersion("2.1.0.0")] [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 XUnity.ResourceRedirector { internal class AssetBundleExtensionData { private string _normalizedPath; private string _path; public string NormalizedPath { get { if (Path != null && _normalizedPath == null) { _normalizedPath = StringExtensions.MakeRelativePath(Path.ToLowerInvariant(), EnvironmentEx.LoweredCurrentDirectory); } return _normalizedPath; } } public string Path { get { return _path; } set { if (_path != value) { _path = value; _normalizedPath = null; } } } } public static class AssetBundleHelper { internal static string PathForLoadedInMemoryBundle; public static AssetBundle CreateEmptyAssetBundle() { byte[] empty = Resources.empty; CabHelper.RandomizeCab(empty); return AssetBundle.LoadFromMemory(empty); } public static AssetBundleCreateRequest CreateEmptyAssetBundleRequest() { byte[] empty = Resources.empty; CabHelper.RandomizeCab(empty); return AssetBundle.LoadFromMemoryAsync(empty); } public static AssetBundle LoadFromMemory(string path, byte[] binary, uint crc) { try { PathForLoadedInMemoryBundle = path; return AssetBundle.LoadFromMemory(binary, crc); } finally { PathForLoadedInMemoryBundle = null; } } public static AssetBundleCreateRequest LoadFromMemoryAsync(string path, byte[] binary, uint crc) { try { PathForLoadedInMemoryBundle = path; return AssetBundle.LoadFromMemoryAsync(binary, crc); } finally { PathForLoadedInMemoryBundle = null; } } public static AssetBundle LoadFromFileWithRandomizedCabIfRequired(string path, uint crc, ulong offset) { return LoadFromFileWithRandomizedCabIfRequired(path, crc, offset, confirmFileExists: true); } internal static AssetBundle LoadFromFileWithRandomizedCabIfRequired(string path, uint crc, ulong offset, bool confirmFileExists) { AssetBundle val = AssetBundle.LoadFromFile(path, crc, offset); if ((Object)(object)val == (Object)null && (!confirmFileExists || File.Exists(path))) { byte[] array; using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read)) { long num = fileStream.Length - (long)offset; fileStream.Seek((long)offset, SeekOrigin.Begin); array = StreamExtensions.ReadFully((Stream)fileStream, (int)num); } CabHelper.RandomizeCabWithAnyLength(array); XuaLogger.ResourceRedirector.Warn("Randomized CAB for '" + path + "' in order to load it because another asset bundle already uses its CAB-string. You can ignore the previous error message, but this is likely caused by two mods incorrectly using the same CAB-string."); return AssetBundle.LoadFromMemory(array); } return val; } } public class AssetBundleLoadedContext { private string _normalizedPath; public AssetBundleLoadingParameters Parameters { get; } public AssetBundle Bundle { get; set; } internal bool SkipRemainingPostfixes { get; private set; } internal AssetBundleLoadedContext(AssetBundleLoadingParameters parameters, AssetBundle bundle) { Parameters = parameters; Bundle = bundle; } public string GetNormalizedPath() { if (_normalizedPath == null && Parameters.Path != null) { _normalizedPath = StringExtensions.MakeRelativePath(StringExtensions.UseCorrectDirectorySeparators(Parameters.Path.ToLowerInvariant()), EnvironmentEx.LoweredCurrentDirectory); } return _normalizedPath; } public void Complete(bool skipRemainingPostfixes = true) { SkipRemainingPostfixes = skipRemainingPostfixes; } public void DisableRecursion() { ResourceRedirection.RecursionEnabled = false; } } public class AssetBundleLoadingContext : IAssetBundleLoadingContext { private string _normalizedPath; public AssetBundleLoadingParameters Parameters { get; } public AssetBundle Bundle { get; set; } internal bool SkipRemainingPrefixes { get; private set; } internal bool SkipOriginalCall { get; private set; } internal bool SkipAllPostfixes { get; private set; } internal AssetBundleLoadingContext(AssetBundleLoadingParameters parameters) { Parameters = parameters; } public string GetNormalizedPath() { if (_normalizedPath == null && Parameters.Path != null) { _normalizedPath = StringExtensions.MakeRelativePath(StringExtensions.UseCorrectDirectorySeparators(Parameters.Path.ToLowerInvariant()), EnvironmentEx.LoweredCurrentDirectory); } return _normalizedPath; } public void Complete() { Complete(skipRemainingPrefixes: true, true, true); } public void Complete(bool skipRemainingPrefixes = true, bool? skipOriginalCall = true) { Complete(skipRemainingPrefixes, skipOriginalCall, true); } public void Complete(bool skipRemainingPrefixes = true, bool? skipOriginalCall = true, bool? skipAllPostfixes = true) { SkipRemainingPrefixes = skipRemainingPrefixes; if (skipOriginalCall.HasValue) { SkipOriginalCall = skipOriginalCall.Value; } if (skipAllPostfixes.HasValue) { SkipAllPostfixes = skipAllPostfixes.Value; } } public void DisableRecursion() { ResourceRedirection.RecursionEnabled = false; } } public class AssetBundleLoadingParameters { public string Path { get; set; } public uint Crc { get; set; } public ulong Offset { get; set; } public Stream Stream { get; set; } public uint ManagedReadBufferSize { get; } public byte[] Binary { get; set; } public AssetBundleLoadType LoadType { get; } internal AssetBundleLoadingParameters(byte[] data, string path, uint crc, ulong offset, Stream stream, uint managedReadBufferSize, AssetBundleLoadType loadType) { Binary = data; Path = path; Crc = crc; Offset = offset; Stream = stream; ManagedReadBufferSize = managedReadBufferSize; LoadType = loadType; } } public enum AssetBundleLoadType { LoadFromFile = 1, LoadFromMemory, LoadFromStream } public class AssetLoadedContext : IAssetOrResourceLoadedContext { private AssetBundleExtensionData _ext; private bool _lookedForExt; private BackingFieldOrArray _backingField; public AssetLoadedParameters Parameters { get; } public AssetBundle Bundle { get; } public Object[] Assets { get { return _backingField.Array; } set { _backingField.Array = value; } } public Object Asset { get { return _backingField.Field; } set { _backingField.Field = value; } } internal bool SkipRemainingPostfixes { get; private set; } internal AssetLoadedContext(AssetLoadedParameters parameters, AssetBundle bundle, Object[] assets) { Parameters = parameters; Bundle = bundle; _backingField = new BackingFieldOrArray(assets); } internal AssetLoadedContext(AssetLoadedParameters parameters, AssetBundle bundle, Object asset) { Parameters = parameters; Bundle = bundle; _backingField = new BackingFieldOrArray(asset); } public bool HasReferenceBeenRedirectedBefore(Object asset) { return ExtensionDataHelper.GetExtensionData<ResourceExtensionData>((object)asset)?.HasBeenRedirected ?? false; } public string GetUniqueFileSystemAssetPath(Object asset) { ResourceExtensionData orCreateExtensionData = ExtensionDataHelper.GetOrCreateExtensionData<ResourceExtensionData>((object)asset); if (orCreateExtensionData.FullFileSystemAssetPath == null) { string text = ExtensionDataHelper.GetExtensionData<AssetBundleExtensionData>((object)Bundle)?.NormalizedPath; string path = (string.IsNullOrEmpty(text) ? "unnamed_assetbundle" : text.ToLowerInvariant()); string name = asset.name; if (!string.IsNullOrEmpty(name)) { path = Path.Combine(path, name.ToLowerInvariant()); } else { string text2 = null; if (Assets.Length > 1) { int num = Array.IndexOf(Assets, asset); text2 = ((num != -1) ? ("_" + num.ToString(CultureInfo.InvariantCulture)) : "_with_unknown_index"); } path = Path.Combine(path, (Parameters.LoadType == AssetLoadType.LoadMainAsset) ? "main_asset" : ("unnamed_asset" + text2)); } path = StringExtensions.UseCorrectDirectorySeparators(path); orCreateExtensionData.FullFileSystemAssetPath = path; } return orCreateExtensionData.FullFileSystemAssetPath; } public string GetAssetBundlePath() { if (!_lookedForExt) { _lookedForExt = true; _ext = ExtensionDataHelper.GetExtensionData<AssetBundleExtensionData>((object)Bundle); } return _ext?.Path; } public string GetNormalizedAssetBundlePath() { if (!_lookedForExt) { _lookedForExt = true; _ext = ExtensionDataHelper.GetExtensionData<AssetBundleExtensionData>((object)Bundle); } return _ext?.NormalizedPath; } public void Complete(bool skipRemainingPostfixes = true) { SkipRemainingPostfixes = skipRemainingPostfixes; } public void DisableRecursion() { ResourceRedirection.RecursionEnabled = false; } } public class AssetLoadedParameters { public string Name { get; } public Type Type { get; } public AssetLoadType LoadType { get; } internal AssetLoadedParameters(string name, Type type, AssetLoadType loadType) { Name = name; Type = type; LoadType = loadType; } } public class AssetLoadingContext : IAssetLoadingContext { private AssetBundleExtensionData _ext; private bool _lookedForExt; private BackingFieldOrArray _backingField; public AssetLoadingParameters Parameters { get; } public AssetBundle Bundle { get; } public Object[] Assets { get { return _backingField.Array; } set { _backingField.Array = value; } } public Object Asset { get { return _backingField.Field; } set { _backingField.Field = value; } } internal bool SkipRemainingPrefixes { get; private set; } internal bool SkipOriginalCall { get; private set; } internal bool SkipAllPostfixes { get; private set; } internal AssetLoadingContext(AssetLoadingParameters parameters, AssetBundle bundle) { Parameters = parameters; Bundle = bundle; } public string GetAssetBundlePath() { if (!_lookedForExt) { _lookedForExt = true; _ext = ExtensionDataHelper.GetExtensionData<AssetBundleExtensionData>((object)Bundle); } return _ext?.Path; } public string GetNormalizedAssetBundlePath() { if (!_lookedForExt) { _lookedForExt = true; _ext = ExtensionDataHelper.GetExtensionData<AssetBundleExtensionData>((object)Bundle); } return _ext?.NormalizedPath; } public void Complete(bool skipRemainingPrefixes = true, bool? skipOriginalCall = true, bool? skipAllPostfixes = true) { SkipRemainingPrefixes = skipRemainingPrefixes; if (skipOriginalCall.HasValue) { SkipOriginalCall = skipOriginalCall.Value; } if (skipAllPostfixes.HasValue) { SkipAllPostfixes = skipAllPostfixes.Value; } } public void DisableRecursion() { ResourceRedirection.RecursionEnabled = false; } } public class AssetLoadingParameters { public string Name { get; set; } public Type Type { get; set; } public AssetLoadType LoadType { get; } internal AssetLoadingParameters(string name, Type type, AssetLoadType loadType) { Name = name; Type = type; LoadType = loadType; } internal AssetLoadedParameters ToAssetLoadedParameters() { return new AssetLoadedParameters(Name, Type, LoadType); } } public enum AssetLoadType { LoadMainAsset = 1, LoadByType, LoadNamed, LoadNamedWithSubAssets } internal class AsyncAssetBundleLoadInfo { public AssetBundleLoadingParameters Parameters { get; } public AssetBundle Bundle { get; } public bool SkipAllPostfixes { get; } public AsyncAssetBundleLoadingResolve ResolveType { get; } public AsyncAssetBundleLoadInfo(AssetBundleLoadingParameters parameters, AssetBundle bundle, bool skipAllPostfixes, AsyncAssetBundleLoadingResolve resolveType) { Parameters = parameters; Bundle = bundle; SkipAllPostfixes = skipAllPostfixes; ResolveType = resolveType; } } public class AsyncAssetBundleLoadingContext : IAssetBundleLoadingContext { private string _normalizedPath; private AssetBundle _bundle; private AssetBundleCreateRequest _request; public AssetBundleLoadingParameters Parameters { get; } public AssetBundleCreateRequest Request { get { return _request; } set { _request = value; ResolveType = AsyncAssetBundleLoadingResolve.ThroughRequest; } } public AssetBundle Bundle { get { return _bundle; } set { if (!ResourceRedirection.SyncOverAsyncEnabled) { throw new InvalidOperationException("Trying to set the Bundle property in async load operation while 'SyncOverAsyncAssetLoads' is disabled is not allowed. Consider settting the Request property instead if possible or enabling 'SyncOverAsyncAssetLoads' through the method 'ResourceRedirection.EnableSyncOverAsyncAssetLoads()'."); } _bundle = value; ResolveType = AsyncAssetBundleLoadingResolve.ThroughBundle; } } public AsyncAssetBundleLoadingResolve ResolveType { get; set; } internal bool SkipRemainingPrefixes { get; private set; } internal bool SkipOriginalCall { get; set; } internal bool SkipAllPostfixes { get; private set; } internal AsyncAssetBundleLoadingContext(AssetBundleLoadingParameters parameters) { Parameters = parameters; } public string GetNormalizedPath() { if (_normalizedPath == null && Parameters.Path != null) { _normalizedPath = StringExtensions.MakeRelativePath(StringExtensions.UseCorrectDirectorySeparators(Parameters.Path.ToLowerInvariant()), EnvironmentEx.LoweredCurrentDirectory); } return _normalizedPath; } public void Complete() { Complete(skipRemainingPrefixes: true, true, true); } public void Complete(bool skipRemainingPrefixes = true, bool? skipOriginalCall = true) { Complete(skipRemainingPrefixes, skipOriginalCall, true); } public void Complete(bool skipRemainingPrefixes = true, bool? skipOriginalCall = true, bool? skipAllPostfixes = true) { SkipRemainingPrefixes = skipRemainingPrefixes; if (skipOriginalCall.HasValue) { SkipOriginalCall = skipOriginalCall.Value; } if (skipAllPostfixes.HasValue) { SkipAllPostfixes = skipAllPostfixes.Value; } } public void DisableRecursion() { ResourceRedirection.RecursionEnabled = false; } } public enum AsyncAssetBundleLoadingResolve { ThroughRequest, ThroughBundle } internal class AsyncAssetLoadInfo { public AssetLoadingParameters Parameters { get; } public AssetBundle Bundle { get; } public bool SkipAllPostfixes { get; } public AsyncAssetLoadingResolve ResolveType { get; } public Object[] Assets { get; } public AsyncAssetLoadInfo(AssetLoadingParameters parameters, AssetBundle bundle, bool skipAllPostfixes, AsyncAssetLoadingResolve resolveType, Object[] assets) { Parameters = parameters; Bundle = bundle; SkipAllPostfixes = skipAllPostfixes; ResolveType = resolveType; Assets = assets; } } public class AsyncAssetLoadingContext : IAssetLoadingContext { private AssetBundleExtensionData _ext; private bool _lookedForExt; private Object[] _assets; private AssetBundleRequest _request; private BackingFieldOrArray _backingField; public AssetLoadingParameters Parameters { get; } public AssetBundle Bundle { get; } public AssetBundleRequest Request { get { return _request; } set { _request = value; ResolveType = AsyncAssetLoadingResolve.ThroughRequest; } } public Object[] Assets { get { return _backingField.Array; } set { if (!ResourceRedirection.SyncOverAsyncEnabled) { throw new InvalidOperationException("Trying to set the Assets/Asset property in async load operation while 'SyncOverAsyncAssetLoads' is disabled is not allowed. Consider settting the Request property instead if possible or enabling 'SyncOverAsyncAssetLoads' through the method 'ResourceRedirection.EnableSyncOverAsyncAssetLoads()'."); } _backingField.Array = value; ResolveType = AsyncAssetLoadingResolve.ThroughAssets; } } public Object Asset { get { return _backingField.Field; } set { if (!ResourceRedirection.SyncOverAsyncEnabled) { throw new InvalidOperationException("Trying to set the Assets/Asset property in async load operation while 'SyncOverAsyncAssetLoads' is disabled is not allowed. Consider settting the Request property instead if possible or enabling 'SyncOverAsyncAssetLoads' through the method 'ResourceRedirection.EnableSyncOverAsyncAssetLoads()'."); } _backingField.Field = value; ResolveType = AsyncAssetLoadingResolve.ThroughAssets; } } public AsyncAssetLoadingResolve ResolveType { get; set; } internal bool SkipRemainingPrefixes { get; private set; } internal bool SkipOriginalCall { get; set; } internal bool SkipAllPostfixes { get; private set; } internal AsyncAssetLoadingContext(AssetLoadingParameters parameters, AssetBundle bundle) { Parameters = parameters; Bundle = bundle; } public string GetAssetBundlePath() { if (!_lookedForExt) { _lookedForExt = true; _ext = ExtensionDataHelper.GetExtensionData<AssetBundleExtensionData>((object)Bundle); } return _ext?.Path; } public string GetNormalizedAssetBundlePath() { if (!_lookedForExt) { _lookedForExt = true; _ext = ExtensionDataHelper.GetExtensionData<AssetBundleExtensionData>((object)Bundle); } return _ext?.NormalizedPath; } public void Complete(bool skipRemainingPrefixes = true, bool? skipOriginalCall = true, bool? skipAllPostfixes = true) { SkipRemainingPrefixes = skipRemainingPrefixes; if (skipOriginalCall.HasValue) { SkipOriginalCall = skipOriginalCall.Value; } if (skipAllPostfixes.HasValue) { SkipAllPostfixes = skipAllPostfixes.Value; } } public void DisableRecursion() { ResourceRedirection.RecursionEnabled = false; } } public enum AsyncAssetLoadingResolve { ThroughRequest, ThroughAssets } internal struct BackingFieldOrArray { [CompilerGenerated] private sealed class <IterateObjects>d__11 : IEnumerable<Object>, IEnumerable, IEnumerator<Object>, IDisposable, IEnumerator { private int <>1__state; private Object <>2__current; private int <>l__initialThreadId; public BackingFieldOrArray <>4__this; public BackingFieldOrArray <>3__<>4__this; private Object[] <>7__wrap1; private int <>7__wrap2; Object IEnumerator<Object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <IterateObjects>d__11(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Thread.CurrentThread.ManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { <>7__wrap1 = null; <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: <>1__state = -1; if (<>4__this._array != null) { <>7__wrap1 = <>4__this._array; <>7__wrap2 = 0; goto IL_007c; } if (<>4__this._field != (Object)null) { <>2__current = <>4__this._field; <>1__state = 2; return true; } break; case 1: <>1__state = -1; <>7__wrap2++; goto IL_007c; case 2: { <>1__state = -1; break; } IL_007c: if (<>7__wrap2 < <>7__wrap1.Length) { Object val = <>7__wrap1[<>7__wrap2]; <>2__current = val; <>1__state = 1; return true; } <>7__wrap1 = null; break; } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<Object> IEnumerable<Object>.GetEnumerator() { <IterateObjects>d__11 <IterateObjects>d__; if (<>1__state == -2 && <>l__initialThreadId == Thread.CurrentThread.ManagedThreadId) { <>1__state = 0; <IterateObjects>d__ = this; } else { <IterateObjects>d__ = new <IterateObjects>d__11(0); } <IterateObjects>d__.<>4__this = <>3__<>4__this; return <IterateObjects>d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<Object>)this).GetEnumerator(); } } private Object _field; private Object[] _array; private BackingSource _source; public Object Field { get { if (_source == BackingSource.None) { return null; } if (_source == BackingSource.SingleField) { return _field; } if (_array == null || _array.Length == 0) { return null; } return _array[0]; } set { _field = value; _array = null; _source = BackingSource.SingleField; } } public Object[] Array { get { if (_source == BackingSource.Array) { return _array; } if (_field == (Object)null) { Array = (Object[])(object)new Object[0]; } else { Array = (Object[])(object)new Object[1] { _field }; } return _array; } set { _field = null; _array = value; _source = BackingSource.Array; } } public BackingFieldOrArray(Object field) { _field = field; _array = null; _source = BackingSource.SingleField; } public BackingFieldOrArray(Object[] array) { _field = null; _array = array; _source = BackingSource.Array; } public IEnumerable<Object> IterateObjects() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <IterateObjects>d__11(-2) { <>3__<>4__this = this }; } } internal enum BackingSource : byte { None, SingleField, Array } public static class CallbackPriority { public const int Default = 0; } public enum HookBehaviour { OneCallbackPerLoadCall = 1, OneCallbackPerResourceLoaded } public interface IAssetBundleLoadingContext { AssetBundleLoadingParameters Parameters { get; } AssetBundle Bundle { get; set; } string GetNormalizedPath(); void Complete(); void Complete(bool skipRemainingPrefixes = true, bool? skipOriginalCall = true); void Complete(bool skipRemainingPrefixes = true, bool? skipOriginalCall = true, bool? skipAllPostfixes = true); void DisableRecursion(); } public interface IAssetLoadingContext { AssetLoadingParameters Parameters { get; } AssetBundle Bundle { get; } Object[] Assets { get; set; } Object Asset { get; set; } string GetAssetBundlePath(); string GetNormalizedAssetBundlePath(); void Complete(bool skipRemainingPrefixes = true, bool? skipOriginalCall = true, bool? skipAllPostfixes = true); void DisableRecursion(); } public interface IAssetOrResourceLoadedContext { Object[] Assets { get; set; } Object Asset { get; set; } bool HasReferenceBeenRedirectedBefore(Object asset); string GetUniqueFileSystemAssetPath(Object asset); void Complete(bool skipRemainingPostfixes = true); void DisableRecursion(); } internal class PrioritizedCallback { public static PrioritizedCallback<TCallback> Create<TCallback>(TCallback item, int priority) where TCallback : Delegate { return new PrioritizedCallback<TCallback>(item, priority); } } internal class PrioritizedCallback<TCallback> : PrioritizedCallback, IComparable<PrioritizedCallback<TCallback>>, IEquatable<PrioritizedCallback<TCallback>> where TCallback : Delegate { public TCallback Callback { get; } public int Priority { get; } public Type TargetType { get; set; } public bool IsBeingCalled { get; set; } public PrioritizedCallback(TCallback callback, int priority) { Callback = callback; Priority = priority; TargetType = callback.Target?.GetType(); } public int CompareTo(PrioritizedCallback<TCallback> other) { return other.Priority.CompareTo(Priority); } public override bool Equals(object obj) { return Equals(obj as PrioritizedCallback<TCallback>); } public bool Equals(PrioritizedCallback<TCallback> other) { return EqualityComparer<TCallback>.Default.Equals(Callback, other.Callback); } public override int GetHashCode() { return -1406788065 * -1521134295 + EqualityComparer<TCallback>.Default.GetHashCode(Callback); } public override string ToString() { return "[" + Priority + "] " + (TargetType?.Name ?? Callback.Method.DeclaringType?.Name) + "." + Callback.Method?.Name; } } internal class ResourceExtensionData { public bool HasBeenRedirected { get; set; } public string FullFileSystemAssetPath { get; set; } } public class ResourceLoadedContext : IAssetOrResourceLoadedContext { private BackingFieldOrArray _backingField; public ResourceLoadedParameters Parameters { get; } public Object[] Assets { get { return _backingField.Array; } set { _backingField.Array = value; } } public Object Asset { get { return _backingField.Field; } set { _backingField.Field = value; } } internal bool SkipRemainingPostfixes { get; set; } internal ResourceLoadedContext(ResourceLoadedParameters parameters, Object[] assets) { Parameters = parameters; _backingField = new BackingFieldOrArray(assets); } internal ResourceLoadedContext(ResourceLoadedParameters parameters, Object asset) { Parameters = parameters; _backingField = new BackingFieldOrArray(asset); } public bool HasReferenceBeenRedirectedBefore(Object asset) { return ExtensionDataHelper.GetExtensionData<ResourceExtensionData>((object)asset)?.HasBeenRedirected ?? false; } public string GetUniqueFileSystemAssetPath(Object asset) { ResourceExtensionData orCreateExtensionData = ExtensionDataHelper.GetOrCreateExtensionData<ResourceExtensionData>((object)asset); if (orCreateExtensionData.FullFileSystemAssetPath == null) { string text = string.Empty; if (!string.IsNullOrEmpty(Parameters.Path)) { text = Parameters.Path.ToLowerInvariant(); } if (Parameters.LoadType == ResourceLoadType.LoadByType) { string name = asset.name; if (!string.IsNullOrEmpty(name)) { text = Path.Combine(text, name.ToLowerInvariant()); } else { string text2 = null; if (Assets.Length > 1) { int num = Array.IndexOf(Assets, asset); text2 = ((num != -1) ? ("_" + num.ToString(CultureInfo.InvariantCulture)) : "_with_unknown_index"); } text = Path.Combine(text, "unnamed_asset" + text2); } } text = StringExtensions.UseCorrectDirectorySeparators(text); orCreateExtensionData.FullFileSystemAssetPath = text; } return orCreateExtensionData.FullFileSystemAssetPath; } public void Complete(bool skipRemainingPostfixes = true) { SkipRemainingPostfixes = skipRemainingPostfixes; } public void DisableRecursion() { ResourceRedirection.RecursionEnabled = false; } } public class ResourceLoadedParameters { public string Path { get; set; } public Type Type { get; set; } public ResourceLoadType LoadType { get; } internal ResourceLoadedParameters(string path, Type type, ResourceLoadType loadType) { Path = path; Type = type; LoadType = loadType; } } public enum ResourceLoadType { LoadByType = 1, LoadNamed, LoadNamedBuiltIn } public static class ResourceRedirection { private static readonly List<PrioritizedCallback<Action<AssetLoadedContext>>> PostfixRedirectionsForAssetsPerCall = new List<PrioritizedCallback<Action<AssetLoadedContext>>>(); private static readonly List<PrioritizedCallback<Action<AssetLoadedContext>>> PostfixRedirectionsForAssetsPerResource = new List<PrioritizedCallback<Action<AssetLoadedContext>>>(); private static readonly List<PrioritizedCallback<Action<ResourceLoadedContext>>> PostfixRedirectionsForResourcesPerCall = new List<PrioritizedCallback<Action<ResourceLoadedContext>>>(); private static readonly List<PrioritizedCallback<Action<ResourceLoadedContext>>> PostfixRedirectionsForResourcesPerResource = new List<PrioritizedCallback<Action<ResourceLoadedContext>>>(); private static readonly List<PrioritizedCallback<Delegate>> PrefixRedirectionsForAssetsPerCall = new List<PrioritizedCallback<Delegate>>(); private static readonly List<PrioritizedCallback<Delegate>> PrefixRedirectionsForAsyncAssetsPerCall = new List<PrioritizedCallback<Delegate>>(); private static readonly List<PrioritizedCallback<Delegate>> PrefixRedirectionsForAssetBundles = new List<PrioritizedCallback<Delegate>>(); private static readonly List<PrioritizedCallback<Delegate>> PrefixRedirectionsForAsyncAssetBundles = new List<PrioritizedCallback<Delegate>>(); private static readonly List<PrioritizedCallback<Action<AssetBundleLoadedContext>>> PostfixRedirectionsForAssetBundles = new List<PrioritizedCallback<Action<AssetBundleLoadedContext>>>(); private static Action<AssetBundleLoadingContext> _emulateAssetBundles; private static Action<AsyncAssetBundleLoadingContext> _emulateAssetBundlesAsync; private static Action<AssetBundleLoadingContext> _redirectionMissingAssetBundlesToEmpty; private static Action<AsyncAssetBundleLoadingContext> _redirectionMissingAssetBundlesToEmptyAsync; private static bool _enabledRandomizeCabIfConflict = false; private static Action<AssetBundleLoadingContext> _enableCabRandomizationPrefix; private static Action<AsyncAssetBundleLoadingContext> _enableCabRandomizationPrefixAsync; private static Action<AssetBundleLoadedContext> _enableCabRandomizationPostfix; private static bool _initialized = false; private static bool _initializedSyncOverAsyncEnabled = false; private static bool _logAllLoadedResources = false; private static bool _isFiringAssetBundle; private static bool _isFiringResource; private static bool _isFiringAsset; private static bool _isRecursionDisabledPermanently; internal static bool RecursionEnabled = true; internal static bool SyncOverAsyncEnabled = false; public static bool LogAllLoadedResources { get { return _logAllLoadedResources; } set { if (value) { Initialize(); } _logAllLoadedResources = value; } } public static bool LogCallbackOrder { get; set; } public static void Initialize() { if (!_initialized) { _initialized = true; HookingHelper.PatchAll((IEnumerable<Type>)ResourceAndAssetHooks.GeneralHooks, false); } } public static void EnableSyncOverAsyncAssetLoads() { Initialize(); if (!_initializedSyncOverAsyncEnabled) { _initializedSyncOverAsyncEnabled = true; SyncOverAsyncEnabled = true; HookingHelper.PatchAll((IEnumerable<Type>)ResourceAndAssetHooks.SyncOverAsyncHooks, false); } } public static void DisableRecursionPermanently() { _isRecursionDisabledPermanently = true; } public static void EnableEmulateAssetBundles(int priority, string emulationDirectory) { if (_emulateAssetBundles == null && _emulateAssetBundlesAsync == null) { _emulateAssetBundles = delegate(AssetBundleLoadingContext ctx) { HandleAssetBundleEmulation<AssetBundleLoadingContext>(ctx, SetBundle); }; _emulateAssetBundlesAsync = delegate(AsyncAssetBundleLoadingContext ctx) { HandleAssetBundleEmulation<AsyncAssetBundleLoadingContext>(ctx, SetRequest); }; RegisterAssetBundleLoadingHook(priority, _emulateAssetBundles); RegisterAsyncAssetBundleLoadingHook(priority, _emulateAssetBundlesAsync); } void HandleAssetBundleEmulation<T>(T context, Action<T, string> changeBundle) where T : IAssetBundleLoadingContext { if (context.Parameters.LoadType == AssetBundleLoadType.LoadFromFile) { string normalizedPath = context.GetNormalizedPath(); string text = Path.Combine(emulationDirectory, normalizedPath); if (File.Exists(text)) { changeBundle(context, text); ref T reference = ref context; T val = default(T); if (val == null) { val = reference; reference = ref val; } reference.Complete(skipRemainingPrefixes: true, true); XuaLogger.ResourceRedirector.Debug("Redirected asset bundle: '" + context.Parameters.Path + "' => '" + text + "'"); } } } static void SetBundle(AssetBundleLoadingContext context, string path) { context.Bundle = AssetBundle.LoadFromFile(path, context.Parameters.Crc, context.Parameters.Offset); } static void SetRequest(AsyncAssetBundleLoadingContext context, string path) { context.Request = AssetBundle.LoadFromFileAsync(path, context.Parameters.Crc, context.Parameters.Offset); } } public static void DisableEmulateAssetBundles() { if (_emulateAssetBundles != null && _emulateAssetBundlesAsync != null) { UnregisterAssetBundleLoadingHook(_emulateAssetBundles); UnregisterAsyncAssetBundleLoadingHook(_emulateAssetBundlesAsync); _emulateAssetBundles = null; _emulateAssetBundlesAsync = null; } } public static void EnableRedirectMissingAssetBundlesToEmptyAssetBundle(int priority) { if (_redirectionMissingAssetBundlesToEmpty == null && _redirectionMissingAssetBundlesToEmptyAsync == null) { _redirectionMissingAssetBundlesToEmpty = delegate(AssetBundleLoadingContext ctx) { HandleMissingBundle<AssetBundleLoadingContext>(ctx, SetBundle); }; _redirectionMissingAssetBundlesToEmptyAsync = delegate(AsyncAssetBundleLoadingContext ctx) { HandleMissingBundle<AsyncAssetBundleLoadingContext>(ctx, SetRequest); }; RegisterAssetBundleLoadingHook(priority, _redirectionMissingAssetBundlesToEmpty); RegisterAsyncAssetBundleLoadingHook(priority, _redirectionMissingAssetBundlesToEmptyAsync); } static void HandleMissingBundle<TContext>(TContext context, Action<TContext, byte[]> changeBundle) where TContext : IAssetBundleLoadingContext { if (context.Parameters.LoadType == AssetBundleLoadType.LoadFromFile && !File.Exists(context.Parameters.Path)) { byte[] empty = Resources.empty; CabHelper.RandomizeCab(empty); changeBundle(context, empty); ref TContext reference = ref context; TContext val = default(TContext); if (val == null) { val = reference; reference = ref val; } reference.Complete(skipRemainingPrefixes: true, true); XuaLogger.ResourceRedirector.Warn("Tried to load non-existing asset bundle: " + context.Parameters.Path); } } static void SetBundle(AssetBundleLoadingContext context, byte[] assetBundleData) { AssetBundle bundle = AssetBundle.LoadFromMemory(assetBundleData); context.Bundle = bundle; } static void SetRequest(AsyncAssetBundleLoadingContext context, byte[] assetBundleData) { AssetBundleCreateRequest request = AssetBundle.LoadFromMemoryAsync(assetBundleData); context.Request = request; } } public static void EnableRandomizeCabIfConflict(int priority, bool forceRandomizeWhenInMemory) { if (_enabledRandomizeCabIfConflict) { return; } _enabledRandomizeCabIfConflict = true; if (forceRandomizeWhenInMemory) { _enableCabRandomizationPrefix = delegate(AssetBundleLoadingContext ctx) { HandleCabRandomizePrefix(ctx); }; _enableCabRandomizationPrefixAsync = delegate(AsyncAssetBundleLoadingContext ctx) { HandleCabRandomizePrefix(ctx); }; RegisterAssetBundleLoadingHook(priority, _enableCabRandomizationPrefix); RegisterAsyncAssetBundleLoadingHook(priority, _enableCabRandomizationPrefixAsync); } _enableCabRandomizationPostfix = delegate(AssetBundleLoadedContext ctx) { HandleCabRandomizePostfix(ctx); }; RegisterAssetBundleLoadedHook(priority, _enableCabRandomizationPostfix); void HandleCabRandomizePostfix(AssetBundleLoadedContext context) { if (context.Parameters.LoadType == AssetBundleLoadType.LoadFromFile) { if ((Object)(object)context.Bundle == (Object)null && File.Exists(context.Parameters.Path)) { XuaLogger.ResourceRedirector.Warn("The asset bundle '" + context.Parameters.Path + "' could not be loaded likely due to conflicting CAB-string. Retrying in-memory with randomized CAB-string."); byte[] array; using (FileStream fileStream = new FileStream(context.Parameters.Path, FileMode.Open, FileAccess.Read)) { long length = fileStream.Length; long offset = (long)context.Parameters.Offset; long num = length - offset; fileStream.Seek(offset, SeekOrigin.Begin); array = StreamExtensions.ReadFully((Stream)fileStream, (int)num); } if (!forceRandomizeWhenInMemory) { CabHelper.RandomizeCabWithAnyLength(array); } AssetBundle val = AssetBundle.LoadFromMemory(array, 0u); if ((Object)(object)val != (Object)null) { context.Bundle = val; context.Complete(); } } } else if (context.Parameters.LoadType == AssetBundleLoadType.LoadFromMemory) { if ((Object)(object)context.Bundle == (Object)null && !forceRandomizeWhenInMemory) { string text = AssetBundleHelper.PathForLoadedInMemoryBundle ?? "Unnamed"; XuaLogger.ResourceRedirector.Warn("Could not load an in-memory asset bundle (" + text + ") likely due to conflicting CAB-string. Retrying with randomized CAB-string."); CabHelper.RandomizeCabWithAnyLength(context.Parameters.Binary); AssetBundle val2 = AssetBundle.LoadFromMemory(context.Parameters.Binary, 0u); if ((Object)(object)val2 != (Object)null) { context.Bundle = val2; context.Complete(); } } } else if (context.Parameters.LoadType == AssetBundleLoadType.LoadFromStream && (Object)(object)context.Bundle == (Object)null) { string text2 = AssetBundleHelper.PathForLoadedInMemoryBundle ?? "Unnamed"; XuaLogger.ResourceRedirector.Warn("Could not load a stream asset bundle (" + text2 + ") likely due to conflicting CAB-string. Retrying with randomized CAB-string."); byte[] array2 = StreamExtensions.ReadFully(context.Parameters.Stream, 0); if (!forceRandomizeWhenInMemory) { CabHelper.RandomizeCabWithAnyLength(array2); } AssetBundle val3 = AssetBundle.LoadFromMemory(array2, 0u); if ((Object)(object)val3 != (Object)null) { context.Bundle = val3; context.Complete(); } } } static void HandleCabRandomizePrefix(IAssetBundleLoadingContext context) { if (context.Parameters.LoadType == AssetBundleLoadType.LoadFromMemory) { CabHelper.RandomizeCabWithAnyLength(context.Parameters.Binary); } } } public static void DisableRandomizeCabIfConflict() { if (_enabledRandomizeCabIfConflict) { _enabledRandomizeCabIfConflict = false; if (_enableCabRandomizationPrefix != null) { UnregisterAssetBundleLoadingHook(_enableCabRandomizationPrefix); _enableCabRandomizationPrefix = null; } if (_enableCabRandomizationPrefixAsync != null) { UnregisterAsyncAssetBundleLoadingHook(_enableCabRandomizationPrefixAsync); _enableCabRandomizationPrefixAsync = null; } if (_enableCabRandomizationPostfix != null) { UnregisterAssetBundleLoadedHook(_enableCabRandomizationPostfix); _enableCabRandomizationPostfix = null; } } } public static void DisableRedirectMissingAssetBundlesToEmptyAssetBundle() { if (_redirectionMissingAssetBundlesToEmpty != null && _redirectionMissingAssetBundlesToEmptyAsync != null) { UnregisterAssetBundleLoadingHook(_redirectionMissingAssetBundlesToEmpty); UnregisterAsyncAssetBundleLoadingHook(_redirectionMissingAssetBundlesToEmptyAsync); _redirectionMissingAssetBundlesToEmpty = null; _redirectionMissingAssetBundlesToEmptyAsync = null; } } internal static bool TryGetAssetBundleLoadInfo(AssetBundleRequest request, out AsyncAssetLoadInfo result) { result = ExtensionDataHelper.GetExtensionData<AsyncAssetLoadInfo>((object)request); return result != null; } internal static bool TryGetAssetBundle(AssetBundleCreateRequest request, out AsyncAssetBundleLoadInfo result) { result = ExtensionDataHelper.GetExtensionData<AsyncAssetBundleLoadInfo>((object)request); return result != null; } internal static bool ShouldBlockAsyncOperationMethods(AssetBundleRequest operation) { if (TryGetAssetBundleLoadInfo(operation, out var result)) { return result.ResolveType == AsyncAssetLoadingResolve.ThroughAssets; } return false; } internal static bool ShouldBlockAsyncOperationMethods(AssetBundleCreateRequest operation) { if (TryGetAssetBundle(operation, out var result)) { return result.ResolveType == AsyncAssetBundleLoadingResolve.ThroughBundle; } return false; } internal static bool ShouldBlockAsyncOperationMethods(AsyncOperation operation) { if (SyncOverAsyncEnabled) { AssetBundleRequest operation2 = default(AssetBundleRequest); if (!ObjectExtensions.TryCastTo<AssetBundleRequest>((object)operation, ref operation2) || !ShouldBlockAsyncOperationMethods(operation2)) { AssetBundleCreateRequest operation3 = default(AssetBundleCreateRequest); if (ObjectExtensions.TryCastTo<AssetBundleCreateRequest>((object)operation, ref operation3)) { return ShouldBlockAsyncOperationMethods(operation3); } return false; } return true; } return false; } internal static AssetBundleLoadingContext Hook_AssetBundleLoading_Prefix(AssetBundleLoadingParameters parameters, out AssetBundle bundle) { AssetBundleLoadingContext assetBundleLoadingContext = new AssetBundleLoadingContext(parameters); if (_isFiringAssetBundle && (_isRecursionDisabledPermanently || !RecursionEnabled)) { bundle = null; return assetBundleLoadingContext; } try { _isFiringAssetBundle = true; if (_logAllLoadedResources) { XuaLogger.ResourceRedirector.Debug("Loading Asset Bundle: (" + assetBundleLoadingContext.GetNormalizedPath() + ")."); } List<PrioritizedCallback<Delegate>> prefixRedirectionsForAssetBundles = PrefixRedirectionsForAssetBundles; int count = prefixRedirectionsForAssetBundles.Count; for (int i = 0; i < count; i++) { PrioritizedCallback<Delegate> prioritizedCallback = prefixRedirectionsForAssetBundles[i]; if (prioritizedCallback.IsBeingCalled) { continue; } try { prioritizedCallback.IsBeingCalled = true; if (prioritizedCallback.Callback is Action<AssetBundleLoadingContext> action) { action(assetBundleLoadingContext); } else if (prioritizedCallback.Callback is Action<IAssetBundleLoadingContext> action2) { action2(assetBundleLoadingContext); } if (assetBundleLoadingContext.SkipRemainingPrefixes) { break; } } catch (Exception ex) { XuaLogger.ResourceRedirector.Error(ex, "An error occurred while invoking AssetBundleLoading event."); } finally { RecursionEnabled = true; prioritizedCallback.IsBeingCalled = false; } } } catch (Exception ex2) { XuaLogger.ResourceRedirector.Error(ex2, "An error occurred while invoking AssetBundleLoading event."); } finally { _isFiringAssetBundle = false; } bundle = assetBundleLoadingContext.Bundle; return assetBundleLoadingContext; } internal static AssetBundleLoadedContext Hook_AssetBundleLoaded_Postfix(AssetBundleLoadingParameters parameters, ref AssetBundle bundle) { AssetBundleLoadedContext assetBundleLoadedContext = new AssetBundleLoadedContext(parameters, bundle); if (_isFiringAssetBundle && (_isRecursionDisabledPermanently || !RecursionEnabled)) { bundle = null; return assetBundleLoadedContext; } try { _isFiringAssetBundle = true; List<PrioritizedCallback<Action<AssetBundleLoadedContext>>> postfixRedirectionsForAssetBundles = PostfixRedirectionsForAssetBundles; int count = postfixRedirectionsForAssetBundles.Count; for (int i = 0; i < count; i++) { PrioritizedCallback<Action<AssetBundleLoadedContext>> prioritizedCallback = postfixRedirectionsForAssetBundles[i]; if (prioritizedCallback.IsBeingCalled) { continue; } try { prioritizedCallback.IsBeingCalled = true; prioritizedCallback.Callback(assetBundleLoadedContext); if (assetBundleLoadedContext.SkipRemainingPostfixes) { break; } } catch (Exception ex) { XuaLogger.ResourceRedirector.Error(ex, "An error occurred while invoking AssetBundleLoaded event."); } finally { RecursionEnabled = true; prioritizedCallback.IsBeingCalled = false; } } } catch (Exception ex2) { XuaLogger.ResourceRedirector.Error(ex2, "An error occurred while invoking AssetBundleLoaded event."); } finally { _isFiringAssetBundle = false; } bundle = assetBundleLoadedContext.Bundle; return assetBundleLoadedContext; } internal static AsyncAssetBundleLoadingContext Hook_AssetBundleLoading_Prefix(AssetBundleLoadingParameters parameters, out AssetBundleCreateRequest request) { //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Expected O, but got Unknown AsyncAssetBundleLoadingContext asyncAssetBundleLoadingContext = new AsyncAssetBundleLoadingContext(parameters); if (_isFiringAssetBundle && (_isRecursionDisabledPermanently || !RecursionEnabled)) { request = null; return asyncAssetBundleLoadingContext; } try { _isFiringAssetBundle = true; if (_logAllLoadedResources) { XuaLogger.ResourceRedirector.Debug("Loading Asset Bundle (async): (" + asyncAssetBundleLoadingContext.GetNormalizedPath() + ")."); } List<PrioritizedCallback<Delegate>> prefixRedirectionsForAsyncAssetBundles = PrefixRedirectionsForAsyncAssetBundles; int count = prefixRedirectionsForAsyncAssetBundles.Count; for (int i = 0; i < count; i++) { PrioritizedCallback<Delegate> prioritizedCallback = prefixRedirectionsForAsyncAssetBundles[i]; if (prioritizedCallback.IsBeingCalled) { continue; } try { prioritizedCallback.IsBeingCalled = true; if (prioritizedCallback.Callback is Action<AsyncAssetBundleLoadingContext> action) { action(asyncAssetBundleLoadingContext); } else if (prioritizedCallback.Callback is Action<IAssetBundleLoadingContext> action2) { action2(asyncAssetBundleLoadingContext); } if (asyncAssetBundleLoadingContext.SkipRemainingPrefixes) { break; } } catch (Exception ex) { XuaLogger.ResourceRedirector.Error(ex, "An error occurred while invoking AssetBundleLoading event."); } finally { RecursionEnabled = true; prioritizedCallback.IsBeingCalled = false; } } } catch (Exception ex2) { XuaLogger.ResourceRedirector.Error(ex2, "An error occurred while invoking AsyncAssetBundleLoading event."); } finally { _isFiringAssetBundle = false; } if (asyncAssetBundleLoadingContext.ResolveType == AsyncAssetBundleLoadingResolve.ThroughRequest) { request = asyncAssetBundleLoadingContext.Request; } else { if (asyncAssetBundleLoadingContext.ResolveType != AsyncAssetBundleLoadingResolve.ThroughBundle) { throw new InvalidOperationException("Found invalid ResolveType on context: " + asyncAssetBundleLoadingContext.ResolveType); } request = new AssetBundleCreateRequest(); if (!asyncAssetBundleLoadingContext.SkipOriginalCall) { XuaLogger.ResourceRedirector.Warn("Resolving sync over async asset load, but 'SkipOriginalCall' was not set to true. Forcing it to true."); asyncAssetBundleLoadingContext.SkipOriginalCall = true; } } return asyncAssetBundleLoadingContext; } internal static void Hook_AssetBundleLoading_Postfix(AsyncAssetBundleLoadingContext context, AssetBundleCreateRequest request) { if (request != null) { ExtensionDataHelper.SetExtensionData<AsyncAssetBundleLoadInfo>((object)request, new AsyncAssetBundleLoadInfo(context.Parameters, context.Bundle, context.SkipAllPostfixes, context.ResolveType)); } } internal static void Hook_AssetLoading_Postfix(AsyncAssetLoadingContext context, AssetBundleRequest request) { if (request != null) { ExtensionDataHelper.SetExtensionData<AsyncAssetLoadInfo>((object)request, new AsyncAssetLoadInfo(context.Parameters, context.Bundle, context.SkipAllPostfixes, context.ResolveType, context.Assets)); } } internal static AssetLoadingContext Hook_AssetLoading_Prefix(AssetLoadingParameters parameters, AssetBundle parentBundle, ref Object asset) { Object[] assets = null; AssetLoadingContext result = Hook_AssetLoading_Prefix(parameters, parentBundle, ref assets); if (assets == null || assets.Length == 0) { asset = null; return result; } if (assets.Length > 1) { XuaLogger.ResourceRedirector.Warn("Illegal behaviour by redirection handler in AssetLoadeding event. Returned more than one asset to call requiring only a single asset."); asset = assets[0]; return result; } if (assets.Length == 1) { asset = assets[0]; } return result; } internal static AssetLoadingContext Hook_AssetLoading_Prefix(AssetLoadingParameters parameters, AssetBundle bundle, ref Object[] assets) { AssetLoadingContext assetLoadingContext = new AssetLoadingContext(parameters, bundle); try { if (_isFiringAsset && (_isRecursionDisabledPermanently || !RecursionEnabled)) { return assetLoadingContext; } _isFiringAsset = true; List<PrioritizedCallback<Delegate>> prefixRedirectionsForAssetsPerCall = PrefixRedirectionsForAssetsPerCall; int count = prefixRedirectionsForAssetsPerCall.Count; for (int i = 0; i < count; i++) { PrioritizedCallback<Delegate> prioritizedCallback = prefixRedirectionsForAssetsPerCall[i]; if (prioritizedCallback.IsBeingCalled) { continue; } try { prioritizedCallback.IsBeingCalled = true; if (prioritizedCallback.Callback is Action<AssetLoadingContext> action) { action(assetLoadingContext); } else if (prioritizedCallback.Callback is Action<IAssetLoadingContext> action2) { action2(assetLoadingContext); } if (assetLoadingContext.SkipRemainingPrefixes) { break; } } catch (Exception ex) { XuaLogger.ResourceRedirector.Error(ex, "An error occurred while invoking AssetLoading event."); } finally { RecursionEnabled = true; prioritizedCallback.IsBeingCalled = false; } } assets = assetLoadingContext.Assets; } catch (Exception ex2) { XuaLogger.ResourceRedirector.Error(ex2, "An error occurred while invoking AssetLoading event."); } finally { _isFiringAsset = false; } return assetLoadingContext; } internal static AsyncAssetLoadingContext Hook_AsyncAssetLoading_Prefix(AssetLoadingParameters parameters, AssetBundle bundle, ref AssetBundleRequest request) { //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Expected O, but got Unknown AsyncAssetLoadingContext asyncAssetLoadingContext = new AsyncAssetLoadingContext(parameters, bundle); try { if (_isFiringAsset && (_isRecursionDisabledPermanently || !RecursionEnabled)) { return asyncAssetLoadingContext; } _isFiringAsset = true; List<PrioritizedCallback<Delegate>> prefixRedirectionsForAsyncAssetsPerCall = PrefixRedirectionsForAsyncAssetsPerCall; int count = prefixRedirectionsForAsyncAssetsPerCall.Count; for (int i = 0; i < count; i++) { PrioritizedCallback<Delegate> prioritizedCallback = prefixRedirectionsForAsyncAssetsPerCall[i]; if (prioritizedCallback.IsBeingCalled) { continue; } try { prioritizedCallback.IsBeingCalled = true; if (prioritizedCallback.Callback is Action<AsyncAssetLoadingContext> action) { action(asyncAssetLoadingContext); } else if (prioritizedCallback.Callback is Action<IAssetLoadingContext> action2) { action2(asyncAssetLoadingContext); } if (asyncAssetLoadingContext.SkipRemainingPrefixes) { break; } } catch (Exception ex) { XuaLogger.ResourceRedirector.Error(ex, "An error occurred while invoking AsyncAssetLoading event."); } finally { RecursionEnabled = true; prioritizedCallback.IsBeingCalled = false; } } if (asyncAssetLoadingContext.ResolveType == AsyncAssetLoadingResolve.ThroughRequest) { request = asyncAssetLoadingContext.Request; } else { if (asyncAssetLoadingContext.ResolveType != AsyncAssetLoadingResolve.ThroughAssets) { throw new InvalidOperationException("Found invalid ResolveType on context: " + asyncAssetLoadingContext.ResolveType); } request = new AssetBundleRequest(); if (!asyncAssetLoadingContext.SkipOriginalCall) { XuaLogger.ResourceRedirector.Warn("Resolving sync over async asset load, but 'SkipOriginalCall' was not set to true. Forcing it to true."); asyncAssetLoadingContext.SkipOriginalCall = true; } } } catch (Exception ex2) { XuaLogger.ResourceRedirector.Error(ex2, "An error occurred while invoking AsyncAssetLoading event."); } finally { _isFiringAsset = false; } return asyncAssetLoadingContext; } internal static void Hook_AssetLoaded_Postfix(AssetLoadingParameters parameters, AssetBundle parentBundle, ref Object asset) { Object[] assets = (Object[])(object)((!(asset == (Object)null)) ? new Object[1] { asset } : new Object[0]); Hook_AssetLoaded_Postfix(parameters, parentBundle, ref assets); if (assets == null || assets.Length == 0) { asset = null; } else if (assets.Length > 1) { XuaLogger.ResourceRedirector.Warn("Illegal behaviour by redirection handler in AssetLoaded event. Returned more than one asset to call requiring only a single asset."); asset = assets[0]; } else if (assets.Length == 1) { asset = assets[0]; } } internal static void Hook_AssetLoaded_Postfix(AssetLoadingParameters parameters, AssetBundle bundle, ref Object[] assets) { FireAssetLoadedEvent(parameters.ToAssetLoadedParameters(), bundle, ref assets); } internal static void Hook_ResourceLoaded_Postfix(ResourceLoadedParameters parameters, ref Object asset) { Object[] assets = (Object[])(object)((!(asset == (Object)null)) ? new Object[1] { asset } : new Object[0]); Hook_ResourceLoaded_Postfix(parameters, ref assets); if (assets == null || assets.Length == 0) { asset = null; } else if (assets.Length > 1) { XuaLogger.ResourceRedirector.Warn("Illegal behaviour by redirection handler in ResourceLoaded event. Returned more than one asset to call requiring only a single asset."); asset = assets[0]; } else if (assets.Length == 1) { asset = assets[0]; } } internal static void Hook_ResourceLoaded_Postfix(ResourceLoadedParameters parameters, ref Object[] assets) { FireResourceLoadedEvent(parameters, ref assets); } internal static void FireAssetLoadedEvent(AssetLoadedParameters parameters, AssetBundle assetBundle, ref Object[] assets) { Object[] array = assets?.ToArray(); try { AssetLoadedContext assetLoadedContext = new AssetLoadedContext(parameters, assetBundle, assets); if (_isFiringAsset && (_isRecursionDisabledPermanently || !RecursionEnabled)) { return; } _isFiringAsset = true; if (_logAllLoadedResources && assets != null) { for (int i = 0; i < assets.Length; i++) { Object val = assets[i]; if (val != (Object)null) { string uniqueFileSystemAssetPath = assetLoadedContext.GetUniqueFileSystemAssetPath(val); XuaLogger.ResourceRedirector.Debug("Loaded Asset: '" + ObjectExtensions.GetUnityType((object)val).FullName + "', Load Type: '" + parameters.LoadType.ToString() + "', Unique Path: (" + uniqueFileSystemAssetPath + ")."); } } } List<PrioritizedCallback<Action<AssetLoadedContext>>> postfixRedirectionsForAssetsPerCall = PostfixRedirectionsForAssetsPerCall; int count = postfixRedirectionsForAssetsPerCall.Count; for (int j = 0; j < count; j++) { PrioritizedCallback<Action<AssetLoadedContext>> prioritizedCallback = postfixRedirectionsForAssetsPerCall[j]; if (prioritizedCallback.IsBeingCalled) { continue; } try { prioritizedCallback.IsBeingCalled = true; prioritizedCallback.Callback(assetLoadedContext); if (assetLoadedContext.SkipRemainingPostfixes) { break; } } catch (Exception ex) { XuaLogger.ResourceRedirector.Error(ex, "An error occurred while invoking AssetLoaded event."); } finally { RecursionEnabled = true; prioritizedCallback.IsBeingCalled = false; } } assets = assetLoadedContext.Assets; if (assetLoadedContext.SkipRemainingPostfixes || assets == null) { return; } int num = assets.Length; for (int k = 0; k < num; k++) { Object val2 = assets[k]; if (val2 != (Object)null) { AssetLoadedContext assetLoadedContext2 = new AssetLoadedContext(parameters, assetBundle, val2); List<PrioritizedCallback<Action<AssetLoadedContext>>> postfixRedirectionsForAssetsPerResource = PostfixRedirectionsForAssetsPerResource; int count2 = postfixRedirectionsForAssetsPerResource.Count; for (int l = 0; l < count2; l++) { PrioritizedCallback<Action<AssetLoadedContext>> prioritizedCallback2 = postfixRedirectionsForAssetsPerResource[l]; if (prioritizedCallback2.IsBeingCalled) { continue; } try { prioritizedCallback2.IsBeingCalled = true; prioritizedCallback2.Callback(assetLoadedContext2); if (assetLoadedContext2.Asset != (Object)null) { assets[k] = assetLoadedContext2.Asset; } else { XuaLogger.ResourceRedirector.Warn($"Illegal behaviour by redirection handler in AssetLoaded event. You must not remove an asset reference when hooking with behaviour {HookBehaviour.OneCallbackPerResourceLoaded}."); } if (assetLoadedContext2.SkipRemainingPostfixes) { break; } } catch (Exception ex2) { XuaLogger.ResourceRedirector.Error(ex2, "An error occurred while invoking AssetLoaded event."); } finally { RecursionEnabled = true; prioritizedCallback2.IsBeingCalled = false; } } } else { XuaLogger.ResourceRedirector.Error("Found unexpected null asset during AssetLoaded event."); } } } catch (Exception ex3) { XuaLogger.ResourceRedirector.Error(ex3, "An error occurred while invoking AssetLoaded event."); } finally { _isFiringAsset = false; if (array != null) { Object[] array2 = array; for (int m = 0; m < array2.Length; m++) { ExtensionDataHelper.GetOrCreateExtensionData<ResourceExtensionData>((object)array2[m]).HasBeenRedirected = true; } } } } internal static void FireResourceLoadedEvent(ResourceLoadedParameters parameters, ref Object[] assets) { Object[] array = assets?.ToArray(); try { ResourceLoadedContext resourceLoadedContext = new ResourceLoadedContext(parameters, assets); if (_isFiringResource && (_isRecursionDisabledPermanently || !RecursionEnabled)) { return; } _isFiringResource = true; if (_logAllLoadedResources && assets != null) { for (int i = 0; i < assets.Length; i++) { Object val = assets[i]; if (val != (Object)null) { string uniqueFileSystemAssetPath = resourceLoadedContext.GetUniqueFileSystemAssetPath(val); XuaLogger.ResourceRedirector.Debug("Loaded Asset: '" + ObjectExtensions.GetUnityType((object)val).FullName + "', Load Type: '" + parameters.LoadType.ToString() + "', Unique Path: (" + uniqueFileSystemAssetPath + ")."); } } } List<PrioritizedCallback<Action<ResourceLoadedContext>>> postfixRedirectionsForResourcesPerCall = PostfixRedirectionsForResourcesPerCall; int count = postfixRedirectionsForResourcesPerCall.Count; for (int j = 0; j < count; j++) { PrioritizedCallback<Action<ResourceLoadedContext>> prioritizedCallback = postfixRedirectionsForResourcesPerCall[j]; if (prioritizedCallback.IsBeingCalled) { continue; } try { prioritizedCallback.IsBeingCalled = true; prioritizedCallback.Callback(resourceLoadedContext); if (resourceLoadedContext.SkipRemainingPostfixes) { break; } } catch (Exception ex) { XuaLogger.ResourceRedirector.Error(ex, "An error occurred while invoking ResourceLoaded event."); } finally { RecursionEnabled = true; prioritizedCallback.IsBeingCalled = false; } } assets = resourceLoadedContext.Assets; if (resourceLoadedContext.SkipRemainingPostfixes || assets == null) { return; } int num = assets.Length; for (int k = 0; k < num; k++) { Object val2 = assets[k]; if (val2 != (Object)null) { ResourceLoadedContext resourceLoadedContext2 = new ResourceLoadedContext(parameters, val2); List<PrioritizedCallback<Action<ResourceLoadedContext>>> postfixRedirectionsForResourcesPerResource = PostfixRedirectionsForResourcesPerResource; int count2 = postfixRedirectionsForResourcesPerResource.Count; for (int l = 0; l < count2; l++) { PrioritizedCallback<Action<ResourceLoadedContext>> prioritizedCallback2 = postfixRedirectionsForResourcesPerResource[l]; if (prioritizedCallback2.IsBeingCalled) { continue; } try { prioritizedCallback2.IsBeingCalled = true; prioritizedCallback2.Callback(resourceLoadedContext2); if (resourceLoadedContext2.Asset != (Object)null) { assets[k] = resourceLoadedContext2.Asset; } else { XuaLogger.ResourceRedirector.Warn($"Illegal behaviour by redirection handler in ResourceLoaded event. You must not remove an asset reference when hooking with behaviour {HookBehaviour.OneCallbackPerResourceLoaded}."); } if (resourceLoadedContext2.SkipRemainingPostfixes) { break; } } catch (Exception ex2) { XuaLogger.ResourceRedirector.Error(ex2, "An error occurred while invoking ResourceLoaded event."); } finally { RecursionEnabled = true; prioritizedCallback2.IsBeingCalled = false; } } } else { XuaLogger.ResourceRedirector.Error("Found unexpected null asset during ResourceLoaded event."); } } } catch (Exception ex3) { XuaLogger.ResourceRedirector.Error(ex3, "An error occurred while invoking ResourceLoaded event."); } finally { _isFiringResource = false; if (array != null) { Object[] array2 = array; for (int m = 0; m < array2.Length; m++) { ExtensionDataHelper.GetOrCreateExtensionData<ResourceExtensionData>((object)array2[m]).HasBeenRedirected = true; } } } } private static void LogEventRegistration(string eventType, IEnumerable callbacks) { XuaLogger.ResourceRedirector.Debug("Registered new callback for " + eventType + "."); LogNewCallbackOrder(eventType, callbacks); } private static void LogEventUnregistration(string eventType, IEnumerable callbacks) { XuaLogger.ResourceRedirector.Debug("Unregistered callback for " + eventType + "."); LogNewCallbackOrder(eventType, callbacks); } private static void LogNewCallbackOrder(string eventType, IEnumerable callbacks) { if (!LogCallbackOrder) { return; } XuaLogger.ResourceRedirector.Debug("New callback order for " + eventType + ":"); foreach (object callback in callbacks) { XuaLogger.ResourceRedirector.Debug(callback.ToString()); } } public static void RegisterAssetBundleLoadedHook(int priority, Action<AssetBundleLoadedContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PrioritizedCallback<Action<AssetBundleLoadedContext>> prioritizedCallback = PrioritizedCallback.Create(action, priority); if (PostfixRedirectionsForAssetBundles.Contains(prioritizedCallback)) { throw new ArgumentException("This callback has already been registered.", "action"); } Initialize(); ListExtensions.BinarySearchInsert<PrioritizedCallback<Action<AssetBundleLoadedContext>>>(PostfixRedirectionsForAssetBundles, prioritizedCallback); LogEventRegistration("AssetBundleLoaded", PostfixRedirectionsForAssetBundles); } public static void RegisterAssetBundleLoadedHook(Action<AssetBundleLoadedContext> action) { RegisterAssetBundleLoadedHook(0, action); } public static void UnregisterAssetBundleLoadedHook(Action<AssetBundleLoadedContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PostfixRedirectionsForAssetBundles.RemoveAll((PrioritizedCallback<Action<AssetBundleLoadedContext>> x) => object.Equals(x.Callback, action)); LogEventUnregistration("AssetBundleLoaded", PostfixRedirectionsForAssetBundles); } public static void RegisterAssetLoadingHook(int priority, Action<AssetLoadingContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PrioritizedCallback<Delegate> prioritizedCallback = PrioritizedCallback.Create((Delegate)action, priority); if (PrefixRedirectionsForAssetsPerCall.Contains(prioritizedCallback)) { throw new ArgumentException("This callback has already been registered.", "action"); } Initialize(); ListExtensions.BinarySearchInsert<PrioritizedCallback<Delegate>>(PrefixRedirectionsForAssetsPerCall, prioritizedCallback); LogEventRegistration("AssetLoading", PrefixRedirectionsForAssetsPerCall); } public static void RegisterAssetLoadingHook(Action<AssetLoadingContext> action) { RegisterAssetLoadingHook(0, action); } public static void UnregisterAssetLoadingHook(Action<AssetLoadingContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PrefixRedirectionsForAssetsPerCall.RemoveAll((PrioritizedCallback<Delegate> x) => object.Equals(x.Callback, action)); LogEventUnregistration("AssetLoading", PrefixRedirectionsForAssetsPerCall); } public static void RegisterAsyncAssetLoadingHook(int priority, Action<AsyncAssetLoadingContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PrioritizedCallback<Delegate> prioritizedCallback = PrioritizedCallback.Create((Delegate)action, priority); if (PrefixRedirectionsForAsyncAssetsPerCall.Contains(prioritizedCallback)) { throw new ArgumentException("This callback has already been registered.", "action"); } Initialize(); ListExtensions.BinarySearchInsert<PrioritizedCallback<Delegate>>(PrefixRedirectionsForAsyncAssetsPerCall, prioritizedCallback); LogEventRegistration("AsyncAssetLoading", PrefixRedirectionsForAsyncAssetsPerCall); } public static void RegisterAsyncAssetLoadingHook(Action<AsyncAssetLoadingContext> action) { RegisterAsyncAssetLoadingHook(0, action); } public static void UnregisterAsyncAssetLoadingHook(Action<AsyncAssetLoadingContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PrefixRedirectionsForAsyncAssetsPerCall.RemoveAll((PrioritizedCallback<Delegate> x) => object.Equals(x.Callback, action)); LogEventUnregistration("AsyncAssetLoading", PrefixRedirectionsForAsyncAssetsPerCall); } public static void RegisterAsyncAndSyncAssetLoadingHook(int priority, Action<IAssetLoadingContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PrioritizedCallback<Delegate> prioritizedCallback = PrioritizedCallback.Create((Delegate)action, priority); if (PrefixRedirectionsForAsyncAssetsPerCall.Contains(prioritizedCallback)) { throw new ArgumentException("This callback has already been registered.", "action"); } Initialize(); ListExtensions.BinarySearchInsert<PrioritizedCallback<Delegate>>(PrefixRedirectionsForAsyncAssetsPerCall, prioritizedCallback); LogEventRegistration("AsyncAssetLoading", PrefixRedirectionsForAsyncAssetsPerCall); ListExtensions.BinarySearchInsert<PrioritizedCallback<Delegate>>(PrefixRedirectionsForAssetsPerCall, prioritizedCallback); LogEventRegistration("AssetLoading", PrefixRedirectionsForAssetsPerCall); } public static void RegisterAsyncAndSyncAssetLoadingHook(Action<IAssetLoadingContext> action) { RegisterAsyncAndSyncAssetLoadingHook(0, action); } public static void UnregisterAsyncAndSyncAssetLoadingHook(Action<IAssetLoadingContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PrefixRedirectionsForAsyncAssetsPerCall.RemoveAll((PrioritizedCallback<Delegate> x) => object.Equals(x.Callback, action)); LogEventUnregistration("AsyncAssetLoading", PrefixRedirectionsForAsyncAssetsPerCall); PrefixRedirectionsForAssetsPerCall.RemoveAll((PrioritizedCallback<Delegate> x) => object.Equals(x.Callback, action)); LogEventUnregistration("AssetLoading", PrefixRedirectionsForAssetsPerCall); } public static void RegisterAssetLoadedHook(HookBehaviour behaviour, int priority, Action<AssetLoadedContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PrioritizedCallback<Action<AssetLoadedContext>> prioritizedCallback = PrioritizedCallback.Create(action, priority); if (PostfixRedirectionsForAssetsPerCall.Contains(prioritizedCallback) || PostfixRedirectionsForAssetsPerResource.Contains(prioritizedCallback)) { throw new ArgumentException("This callback has already been registered.", "action"); } Initialize(); switch (behaviour) { case HookBehaviour.OneCallbackPerLoadCall: ListExtensions.BinarySearchInsert<PrioritizedCallback<Action<AssetLoadedContext>>>(PostfixRedirectionsForAssetsPerCall, prioritizedCallback); LogEventRegistration("AssetLoaded (" + behaviour.ToString() + ")", PostfixRedirectionsForAssetsPerCall); break; case HookBehaviour.OneCallbackPerResourceLoaded: ListExtensions.BinarySearchInsert<PrioritizedCallback<Action<AssetLoadedContext>>>(PostfixRedirectionsForAssetsPerResource, prioritizedCallback); LogEventRegistration("AssetLoaded (" + behaviour.ToString() + ")", PostfixRedirectionsForAssetsPerResource); break; } } public static void RegisterAssetLoadedHook(HookBehaviour behaviour, Action<AssetLoadedContext> action) { RegisterAssetLoadedHook(behaviour, 0, action); } public static void UnregisterAssetLoadedHook(Action<AssetLoadedContext> action) { if (action == null) { throw new ArgumentNullException("action"); } if (PostfixRedirectionsForAssetsPerCall.RemoveAll((PrioritizedCallback<Action<AssetLoadedContext>> x) => x.Callback == action) > 0) { LogEventRegistration("AssetLoaded (" + HookBehaviour.OneCallbackPerLoadCall.ToString() + ")", PostfixRedirectionsForAssetsPerCall); } if (PostfixRedirectionsForAssetsPerResource.RemoveAll((PrioritizedCallback<Action<AssetLoadedContext>> x) => x.Callback == action) > 0) { LogEventRegistration("AssetLoaded (" + HookBehaviour.OneCallbackPerResourceLoaded.ToString() + ")", PostfixRedirectionsForAssetsPerResource); } } public static void RegisterAssetBundleLoadingHook(int priority, Action<AssetBundleLoadingContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PrioritizedCallback<Delegate> prioritizedCallback = PrioritizedCallback.Create((Delegate)action, priority); if (PrefixRedirectionsForAssetBundles.Contains(prioritizedCallback)) { throw new ArgumentException("This callback has already been registered.", "action"); } Initialize(); ListExtensions.BinarySearchInsert<PrioritizedCallback<Delegate>>(PrefixRedirectionsForAssetBundles, prioritizedCallback); LogEventRegistration("AssetBundleLoading", PrefixRedirectionsForAssetBundles); } public static void RegisterAssetBundleLoadingHook(Action<AssetBundleLoadingContext> action) { RegisterAssetBundleLoadingHook(0, action); } public static void UnregisterAssetBundleLoadingHook(Action<AssetBundleLoadingContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PrefixRedirectionsForAssetBundles.RemoveAll((PrioritizedCallback<Delegate> x) => object.Equals(x.Callback, action)); LogEventUnregistration("AssetBundleLoading", PrefixRedirectionsForAssetBundles); } public static void RegisterAsyncAssetBundleLoadingHook(int priority, Action<AsyncAssetBundleLoadingContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PrioritizedCallback<Delegate> prioritizedCallback = PrioritizedCallback.Create((Delegate)action, priority); if (PrefixRedirectionsForAsyncAssetBundles.Contains(prioritizedCallback)) { throw new ArgumentException("This callback has already been registered.", "action"); } Initialize(); ListExtensions.BinarySearchInsert<PrioritizedCallback<Delegate>>(PrefixRedirectionsForAsyncAssetBundles, prioritizedCallback); LogEventRegistration("AsyncAssetBundleLoading", PrefixRedirectionsForAsyncAssetBundles); } public static void RegisterAsyncAssetBundleLoadingHook(Action<AsyncAssetBundleLoadingContext> action) { RegisterAsyncAssetBundleLoadingHook(0, action); } public static void UnregisterAsyncAssetBundleLoadingHook(Action<AsyncAssetBundleLoadingContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PrefixRedirectionsForAsyncAssetBundles.RemoveAll((PrioritizedCallback<Delegate> x) => object.Equals(x.Callback, action)); LogEventUnregistration("AsyncAssetBundleLoading", PrefixRedirectionsForAsyncAssetBundles); } public static void RegisterAsyncAndSyncAssetBundleLoadingHook(int priority, Action<IAssetBundleLoadingContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PrioritizedCallback<Delegate> prioritizedCallback = PrioritizedCallback.Create((Delegate)action, priority); if (PrefixRedirectionsForAssetBundles.Contains(prioritizedCallback)) { throw new ArgumentException("This callback has already been registered.", "action"); } Initialize(); ListExtensions.BinarySearchInsert<PrioritizedCallback<Delegate>>(PrefixRedirectionsForAssetBundles, prioritizedCallback); LogEventRegistration("AssetBundleLoading", PrefixRedirectionsForAssetBundles); ListExtensions.BinarySearchInsert<PrioritizedCallback<Delegate>>(PrefixRedirectionsForAsyncAssetBundles, prioritizedCallback); LogEventRegistration("AsyncAssetBundleLoading", PrefixRedirectionsForAsyncAssetBundles); } public static void RegisterAsyncAndSyncAssetBundleLoadingHook(Action<IAssetBundleLoadingContext> action) { RegisterAsyncAndSyncAssetBundleLoadingHook(0, action); } public static void UnregisterAsyncAndSyncAssetBundleLoadingHook(Action<IAssetBundleLoadingContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PrefixRedirectionsForAssetBundles.RemoveAll((PrioritizedCallback<Delegate> x) => object.Equals(x.Callback, action)); LogEventUnregistration("AssetBundleLoading", PrefixRedirectionsForAssetBundles); PrefixRedirectionsForAsyncAssetBundles.RemoveAll((PrioritizedCallback<Delegate> x) => object.Equals(x.Callback, action)); LogEventUnregistration("AsyncAssetBundleLoading", PrefixRedirectionsForAsyncAssetBundles); } public static void RegisterResourceLoadedHook(HookBehaviour behaviour, int priority, Action<ResourceLoadedContext> action) { if (action == null) { throw new ArgumentNullException("action"); } PrioritizedCallback<Action<ResourceLoadedContext>> prioritizedCallback = PrioritizedCallback.Create(action, priority); if (PostfixRedirectionsForResourcesPerCall.Contains(prioritizedCallback) || PostfixRedirectionsForResourcesPerResource.Contains(prioritizedCallback)) { throw new ArgumentException("This callback has already been registered.", "action"); } Initialize(); switch (behaviour) { case HookBehaviour.OneCallbackPerLoadCall: ListExtensions.BinarySearchInsert<PrioritizedCallback<Action<ResourceLoadedContext>>>(PostfixRedirectionsForResourcesPerCall, prioritizedCallback); LogEventRegistration("ResourceLoaded (" + behaviour.ToString() + ")", PostfixRedirectionsForResourcesPerCall); break; case HookBehaviour.OneCallbackPerResourceLoaded: ListExtensions.BinarySearchInsert<PrioritizedCallback<Action<ResourceLoadedContext>>>(PostfixRedirectionsForResourcesPerResource, prioritizedCallback); LogEventRegistration("ResourceLoaded (" + behaviour.ToString() + ")", PostfixRedirectionsForResourcesPerResource); break; } } public static void RegisterResourceLoadedHook(HookBehaviour behaviour, Action<ResourceLoadedContext> action) { RegisterResourceLoadedHook(behaviour, 0, action); } public static void UnregisterResourceLoadedHook(Action<ResourceLoadedContext> action) { if (action == null) { throw new ArgumentNullException("action"); } if (PostfixRedirectionsForResourcesPerCall.RemoveAll((PrioritizedCallback<Action<ResourceLoadedContext>> x) => x.Callback == action) > 0) { LogEventRegistration("ResourceLoaded (" + HookBehaviour.OneCallbackPerLoadCall.ToString() + ")", PostfixRedirectionsForResourcesPerCall); } if (PostfixRedirectionsForResourcesPerResource.RemoveAll((PrioritizedCallback<Action<ResourceLoadedContext>> x) => x.Callback == action) > 0) { LogEventRegistration("ResourceLoaded (" + HookBehaviour.OneCallbackPerResourceLoaded.ToString() + ")", PostfixRedirectionsForResourcesPerResource); } } } internal static class GeneratedInfo { public const string PROJECT_VERSION = "2.1.0"; } } namespace XUnity.ResourceRedirector.Properties { [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [DebuggerNonUserCode] [CompilerGenerated] internal class Resources { private static ResourceManager resourceMan; private static CultureInfo resourceCulture; [EditorBrowsable(EditorBrowsableState.Advanced)] internal static ResourceManager ResourceManager { get { if (resourceMan == null) { resourceMan = new ResourceManager("XUnity.ResourceRedirector.Properties.Resources", typeof(Resources).Assembly); } return resourceMan; } } [EditorBrowsable(EditorBrowsableState.Advanced)] internal static CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static byte[] empty => (byte[])ResourceManager.GetObject("empty", resourceCulture); internal Resources() { } } } namespace XUnity.ResourceRedirector.Hooks { internal static class ResourceAndAssetHooks { public static readonly Type[] GeneralHooks = new Type[21] { typeof(AssetBundle_LoadFromFileAsync_Hook), typeof(AssetBundle_LoadFromFile_Hook), typeof(AssetBundle_LoadFromMemoryAsync_Hook), typeof(AssetBundle_LoadFromMemory_Hook), typeof(AssetBundle_LoadFromStreamAsync_Hook), typeof(AssetBundle_LoadFromStream_Hook), typeof(AssetBundle_mainAsset_Hook), typeof(AssetBundle_returnMainAsset_Hook), typeof(AssetBundle_Load_Hook), typeof(AssetBundle_LoadAsync_Hook), typeof(AssetBundle_LoadAll_Hook), typeof(AssetBundle_LoadAsset_Internal_Hook), typeof(AssetBundle_LoadAssetAsync_Internal_Hook), typeof(AssetBundle_LoadAssetWithSubAssets_Internal_Hook), typeof(AssetBundle_LoadAssetWithSubAssetsAsync_Internal_Hook), typeof(AssetBundleRequest_asset_Hook), typeof(AssetBundleRequest_allAssets_Hook), typeof(Resources_Load_Hook), typeof(Resources_LoadAll_Hook), typeof(Resources_GetBuiltinResource_Old_Hook), typeof(Resources_GetBuiltinResource_New_Hook) }; public static readonly Type[] SyncOverAsyncHooks = new Type[10] { typeof(AssetBundleCreateRequest_assetBundle_Hook), typeof(AssetBundleCreateRequest_DisableCompatibilityChecks_Hook), typeof(AssetBundleCreateRequest_SetEnableCompatibilityChecks_Hook), typeof(AsyncOperation_isDone_Hook), typeof(AsyncOperation_progress_Hook), typeof(AsyncOperation_priority_Hook), typeof(AsyncOperation_set_priority_Hook), typeof(AsyncOperation_allowSceneActivation_Hook), typeof(AsyncOperation_set_allowSceneActivation_Hook), typeof(AsyncOperation_Finalize_Hook) }; } internal static class AssetBundleCreateRequest_assetBundle_Hook { private delegate AssetBundle OriginalMethod(AssetBundleCreateRequest __instance); private static OriginalMethod _original; private static bool Prepare(object instance) { return UnityTypes.AssetBundleCreateRequest != null; } private static MethodBase TargetMethod(object instance) { TypeContainer assetBundleCreateRequest = UnityTypes.AssetBundleCreateRequest; return AccessToolsShim.Property((assetBundleCreateRequest != null) ? assetBundleCreateRequest.ClrType : null, "assetBundle")?.GetGetMethod(); } private static bool Prefix(AssetBundleCreateRequest __instance, ref AssetBundle __result, ref AsyncAssetBundleLoadInfo __state) { if (ResourceRedirection.TryGetAssetBundle(__instance, out __state)) { if (__state.ResolveType == AsyncAssetBundleLoadingResolve.ThroughBundle) { __result = __state.Bundle; return false; } return true; } return true; } private static void Postfix(ref AssetBundle __result, ref AsyncAssetBundleLoadInfo __state) { if (__state == null) { return; } if (!__state.SkipAllPostfixes) { ResourceRedirection.Hook_AssetBundleLoaded_Postfix(__state.Parameters, ref __result); } if ((Object)(object)__result != (Object)null && __state != null) { string path = __state.Parameters.Path; if (path != null) { ExtensionDataHelper.GetOrCreateExtensionData<AssetBundleExtensionData>((object)__result).Path = path; } } } private static void MM_Init(object detour) { _original = DetourExtensions.GenerateTrampolineEx<OriginalMethod>(detour); } private static AssetBundle MM_Detour(AssetBundleCreateRequest __instance) { AssetBundle __result = null; AsyncAssetBundleLoadInfo __state = null; if (Prefix(__instance, ref __result, ref __state)) { __result = _original(__instance); } Postfix(ref __result, ref __state); return __result; } } internal static class AssetBundleCreateRequest_DisableCompatibilityChecks_Hook { private delegate void OriginalMethod(AssetBundleCreateRequest __instance); private static OriginalMethod _original; private static bool Prepare(object instance) { TypeContainer assetBundleCreateRequest = UnityTypes.AssetBundleCreateRequest; return (object)AccessToolsShim.Method((assetBundleCreateRequest != null) ? assetBundleCreateRequest.ClrType : null, "SetEnableCompatibilityChecks", new Type[1] { typeof(bool) }) == null; } private static MethodBase TargetMethod(object instance) { TypeContainer assetBundleCreateRequest = UnityTypes.AssetBundleCreateRequest; return AccessToolsShim.Method((assetBundleCreateRequest != null) ? assetBundleCreateRequest.ClrType : null, "DisableCompatibilityChecks", new Type[0]); } private static bool Prefix(AssetBundleCreateRequest __instance) { return !ResourceRedirection.ShouldBlockAsyncOperationMethods(__instance); } private static void MM_Init(object detour) { _original = DetourExtensions.GenerateTrampolineEx<OriginalMethod>(detour); } private static void MM_Detour(AssetBundleCreateRequest __instance) { if (Prefix(__instance)) { _original(__instance); } } } internal static class AssetBundleCreateRequest_SetEnableCompatibilityChecks_Hook { private delegate void OriginalMethod(AssetBundleCreateRequest __instance, bool set); private static OriginalMethod _original; private static bool Prepare(object instance) { TypeContainer assetBundleCreateRequest = UnityTypes.AssetBundleCreateRequest; return (object)AccessToolsShim.Method((assetBundleCreateRequest != null) ? assetBundleCreateRequest.ClrType : null, "SetEnableCompatibilityChecks", new Type[1] { typeof(bool) }) != null; } private static MethodBase TargetMethod(object instance) { TypeContainer assetBundleCreateRequest = UnityTypes.AssetBundleCreateRequest; return AccessToolsShim.Method((assetBundleCreateRequest != null) ? assetBundleCreateRequest.ClrType : null, "SetEnableCompatibilityChecks", new Type[1] { typeof(bool) }); } private static bool Prefix(AssetBundleCreateRequest __instance, bool set) { return !ResourceRedirection.ShouldBlockAsyncOperationMethods(__instance); } private static void MM_Init(object detour) { _original = DetourExtensions.GenerateTrampolineEx<OriginalMethod>(detour); } private static void MM_Detour(AssetBundleCreateRequest __instance, bool set) { if (Prefix(__instance, set)) { _original(__instance, set); } } } internal static class AssetBundle_LoadFromFileAsync_Hook { private delegate AssetBundleCreateRequest OriginalMethod(string path, uint crc, ulong offset); private static OriginalMethod _original; private static bool Prepare(object instance) { return UnityTypes.AssetBundle != null; } private static MethodBase TargetMethod(object instance) { TypeContainer assetBundle = UnityTypes.AssetBundle; MethodInfo methodInfo = AccessToolsShim.Method((assetBundle != null) ? assetBundle.ClrType : null, "LoadFromFileAsync_Internal", new Type[3] { typeof(string), typeof(uint), typeof(ulong) }); if ((object)methodInfo == null) { TypeContainer assetBundle2 = UnityTypes.AssetBundle; methodInfo = AccessToolsShim.Method((assetBundle2 != null) ? assetBundle2.ClrType : null, "LoadFromFileAsync", new Type[3] { typeof(string), typeof(uint), typeof(ulong) }); } return methodInfo; } private static bool Prefix(ref string path, ref uint crc, ref ulong offset, ref AssetBundleCreateRequest __result, ref AsyncAssetBundleLoadingContext __state) { AssetBundleLoadingParameters parameters = new AssetBundleLoadingParameters(null, path, crc, offset, null, 0u, AssetBundleLoadType.LoadFromFile); __state = ResourceRedirection.Hook_AssetBundleLoading_Prefix(parameters, out __result); AssetBundleLoadingParameters parameters2 = __state.Parameters; path = parameters2.Path; crc = parameters2.Crc; offset = parameters2.Offset; return !__state.SkipOriginalCall; } private static void Postfix(ref AssetBundleCreateRequest __result, ref AsyncAssetBundleLoadingContext __state) { ResourceRedirection.Hook_AssetBundleLoading_Postfix(__state, __result); } private static void MM_Init(object detour) { _original = DetourExtensions.GenerateTrampolineEx<OriginalMethod>(detour); } private static AssetBundleCreateRequest MM_Detour(string path, uint crc, ulong offset) { AssetBundleCreateRequest __result = null; AsyncAssetBundleLoadingContext __state = null; if (Prefix(ref path, ref crc, ref offset, ref __result, ref __state)) { __result = _original(path, crc, offset); } Postfix(ref __result, ref __state); return __result; } } internal static class AssetBundle_LoadFromFile_Hook { private delegate AssetBundle OriginalMethod(string path, uint crc, ulong offset); private static OriginalMethod _original; private static bool Prepare(object instance) { return UnityTypes.AssetBundle != null; } private static MethodBase TargetMethod(object instance) { TypeContainer assetBundle = UnityTypes.AssetBundle; MethodInfo methodInfo = AccessToolsShim.Method((assetBundle != null) ? assetBundle.ClrType : null, "LoadFromFile_Internal", new Type[3] { typeof(string), typeof(uint), typeof(ulong) }); if ((object)methodInfo == null) { TypeContainer assetBundle2 = UnityTypes.AssetBundle; methodInfo = AccessToolsShim.Method((assetBundle2 != null) ? assetBundle2.ClrType : null, "LoadFromFile", new Type[3] { typeof(string), typeof(uint), typeof(ulong) }); } return methodInfo; } private static bool Prefix(ref string path, ref uint crc, ref ulong offset, ref AssetBundle __result, ref AssetBundleLoadingContext __state) { AssetBundleLoadingParameters parameters = new AssetBundleLoadingParameters(null, path, crc, offset, null, 0u, AssetBundleLoadType.LoadFromFile); __state = ResourceRedirection.Hook_AssetBundleLoading_Prefix(parameters, out __result); AssetBundleLoadingParameters parameters2 = __state.Parameters; path = parameters2.Path; crc = parameters2.Crc; offset = parameters2.Offset; return !__state.SkipOriginalCall; } private static void Postfix(ref AssetBundle __result, ref AssetBundleLoadingContext __state) { if (!__state.SkipAllPostfixes) { ResourceRedirection.Hook_AssetBundleLoaded_Postfix(__state.Parameters, ref __result); } if ((Object)(object)__result != (Object)null && __state.Parameters.Path != null) { ExtensionDataHelper.GetOrCreateExtensionData<AssetBundleExtensionData>((object)__result).Path = __state.Parameters.Path; } } private static void MM_Init(object detour) { _original = DetourExtensions.GenerateTrampolineEx<OriginalMethod>(detour); } private static AssetBundle MM_Detour(string path, uint crc, ulong offset) { AssetBundle __result = null; AssetBundleLoadingContext __state = null; if (Prefix(ref path, ref crc, ref offset, ref __result, ref __state)) { __result = _original(path, crc, offset); } Postfix(ref __result, ref __state); return __result; } } internal static class AssetBundle_LoadFromMemoryAsync_Hook { private delegate AssetBundleCreateRequest OriginalMethod(byte[] binary, uint crc); private static OriginalMethod _original; private static bool Prepare(object instance) { return UnityTypes.AssetBundle != null; } private static MethodBase TargetMethod(object instance) { TypeContainer assetBundle = UnityTypes.AssetBundle; MethodInfo methodInfo = AccessToolsShim.Method((assetBundle != null) ? assetBundle.ClrType : null, "LoadFromMemoryAsync_Internal", new Type[2] { typeof(byte[]), typeof(uint) }); if ((object)methodInfo == null) { TypeContainer assetBundle2 = UnityTypes.AssetBundle; methodInfo = AccessToolsShim.Method((assetBundle2 != null) ? assetBundle2.ClrType : null, "LoadFromMemoryAsync", new Type[2] { typeof(byte[]), typeof(uint) }); } return methodInfo; } private static bool Prefix(ref byte[] binary, ref uint crc, ref AssetBundleCreateRequest __result, ref AsyncAssetBundleLoadingContext __state) { AssetBundleLoadingParameters parameters = new AssetBundleLoadingParameters(binary, null, crc, 0uL, null, 0u, AssetBundleLoadType.LoadFromMemory); __state = ResourceRedirection.Hook_AssetBundleLoading_Prefix(parameters, out __result); AssetBundleLoadingParameters parameters2 = __state.Parameters; binary = parameters2.Binary; crc = parameters2.Crc; return !__state.SkipOriginalCall; } private static void Postfix(ref AssetBundleCreateRequest __result, ref AsyncAssetBundleLoadingContext __state) { ResourceRedirection.Hook_AssetBundleLoading_Postfix(__state, __result); } private static void MM_Init(object detour) { _original = DetourExtensions.GenerateTrampolineEx<OriginalMethod>(detour); } private static AssetBundleCreateRequest MM_Detour(byte[] binary, uint crc) { AssetBundleCreateRequest __result = null; AsyncAssetBundleLoadingContext __state = null; if (Prefix(ref binary, ref crc, ref __result, ref __state)) { __result = _original(binary, crc); } Postfix(ref __result, ref __state); return __result; } } internal static class AssetBundle_LoadFromMemory_Hook { private delegate AssetBundle OriginalMethod(byte[] binary, uint crc); private static OriginalMethod _original; private static bool Prepare(object instance) { return UnityTypes.AssetBundle != null; } private static MethodBase TargetMethod(object instance) { TypeContainer assetBundle = UnityTypes.AssetBundle; MethodInfo methodInfo = AccessToolsShim.Method((assetBundle != null) ? assetBundle.ClrType : null, "LoadFromMemory_Internal", new Type[2] { typeof(byte[]), typeof(uint) }); if ((object)methodInfo == null) { TypeContainer assetBundle2 = UnityTypes.AssetBundle; methodInfo = AccessToolsShim.Method((assetBundle2 != null) ? assetBundle2.ClrType : null, "LoadFromMemory", new Type[2] { typeof(byte[]), typeof(uint) }); } return methodInfo; } private static bool Prefix(ref byte[] binary, ref uint crc, ref AssetBundle __result, ref AssetBundleLoadingContext __state) { AssetBundleLoadingParameters parameters = new AssetBundleLoadingParameters(binary, null, crc, 0uL, null, 0u, AssetBundleLoadType.LoadFromMemory); __state = ResourceRedirection.Hook_AssetBundleLoading_Prefix(parameters, out __result); AssetBundleLoadingParameters parameters2 = __state.Parameters; binary = parameters2.Binary; crc = parameters2.Crc; return !__state.SkipOriginalCall; } private static void Postfix(ref AssetBundle __result, ref AssetBundleLoadingContext __state) { if (!__state.SkipAllPostfixes) { ResourceRedirection.Hook_AssetBundleLoaded_Postfix(__state.Parameters, ref __result); } if ((Object)(object)__result != (Object)null && __state.Parameters.Path != null) { ExtensionDataHelper.GetOrCreateExtensionData<AssetBundleExtensionData>((object)__result).Path = __state.Parameters.Path; } } private static void MM_Init(object detour) { _original = DetourExtensions.GenerateTrampolineEx<OriginalMethod>(detour); } private static AssetBundle MM_Detour(byte[] binary, uint crc) { AssetBundle __result = null; AssetBundleLoadingContext __state = null; if (Prefix(ref binary, ref crc, ref __result, ref __state)) { __result = _original(binary, crc); } Postfix(ref __result, ref __state); return __result; } } internal static class AssetBundle_LoadFromStreamAsync_Hook { private delegate AssetBundleCreateRequest OriginalMethod(Stream stream, uint crc, uint managedReadBufferSize); private static OriginalMethod _original; private static bool Prepare(object instance) { return UnityTypes.AssetBundle != null; } private static MethodBase TargetMethod(object instance) { TypeContainer assetBundle = UnityTypes.AssetBundle; MethodInfo methodInfo = AccessToolsShim.Method((assetBundle != null) ? assetBundle.ClrType : null, "LoadFromStreamAsyncInternal", new Type[3] { typeof(Stream), typeof(uint), typeof(uint) }); if ((object)methodInfo == null) { TypeContainer assetBundle2 = UnityTypes.AssetBundle; methodInfo = AccessToolsShim.Method((assetBundle2 != null) ? assetBundle2.ClrType : null, "LoadFromStreamAsync", new Type[3] { typeof(Stream), typeof(uint), typeof(uint) }); } return methodInfo; } private static bool Prefix(ref Stream stream, ref uint crc, ref uint managedReadBufferSize, ref AssetBundleCreateRequest __result, ref AsyncAssetBundleLoadingContext __state) { AssetBundleLoadingParameters parameters = new AssetBundleLoadingParameters(null, null, crc, 0uL, stream, managedReadBufferSize, AssetBundleLoadType.LoadFromMemory); __state = ResourceRedirection.Hook_AssetBundleLoading_Prefix(parameters, out __result); AssetBundleLoadingParameters parameters2 = __state.Parameters; stream = parameters2.Stream; crc = parameters2.Crc; managedReadBufferSize = parameters2.ManagedReadBufferSize; return !__state.SkipOriginalCall; } private static void Postfix(ref AssetBundleCreateRequest __result, ref AsyncAssetBundleLoadingContext __state) { ResourceRedirection.Hook_AssetBundleLoading_Postfix(__state, __result); } private static void MM_Init(object detour) { _original = DetourExtensions.GenerateTrampolineEx<OriginalMethod>(detour); } private static AssetBundleCreateRequest MM_Detour(Stream stream, uint crc, uint managedReadBufferSize) { AssetBundleCreateRequest __result = null; AsyncAssetBundleLoadingContext __state = null; if (Prefix(ref stream, ref crc, ref managedReadBufferSize, ref __result, ref __state)) { __result = _original(stream, crc, managedReadBufferSize); } Postfix(ref __result, ref __state); return __result; } } internal static class AssetBundle_LoadFromStream_Hook { private delegate AssetBundle OriginalMethod(Stream stream, uint crc, uint managedReadBufferSize); private static OriginalMethod _original; private static bool Prepare(object instance) { return UnityTypes.AssetBundle != null; } private static MethodBase TargetMethod(object instance) { TypeContainer assetBundle = UnityTypes.AssetBundle; MethodInfo methodInfo = AccessToolsShim.Method((assetBundle != null) ? assetBundle.ClrType : null, "LoadFromStreamInternal", new Type[3] { typeof(Stream), typeof(uint), typeof(uint) }); if ((object)methodInfo == null) { TypeContainer assetBundle2 = UnityTypes.AssetBundle; methodInfo = AccessToolsShim.Method((assetBundle2 != null) ? assetBundle2.ClrType : null, "LoadFromStream", new Type[3] { typeof(Stream), typeof(uint), typeof(uint) }); } return methodInfo; } private static bool Prefix(ref Stream stream, ref uint crc, ref uint managedReadBufferSize, ref AssetBundle __result, ref AssetBundleLoadingContext __state) { AssetBundleLoadingParameters parameters = new AssetBundleLoadingParameters(null, null, crc, 0uL, stream, managedReadBufferSize, AssetBundleLoadType.LoadFromMemory); __state = ResourceRedirection.Hook_AssetBundleLoading_Prefix(parameters, out __result); AssetBundleLoadingParameters parameters2 = __state.Parameters; stream = parameters2.Stream; crc = parameters2.Crc; managedReadBufferSize = parameters2.ManagedReadBufferSize; return !__state.SkipOriginalCall; } private static void Postfix(ref AssetBundle __result, ref AssetBundleLoadingContext __state) { if (!__state.SkipAllPostfixes) { ResourceRedirection.Hook_AssetBundleLoaded_Postfix(__state.Parameters, ref __result); } if ((Object)(object)__result != (Object)null && __state.Parameters.Path != null) { ExtensionDataHelper.GetOrCreateExtensionData<AssetBundleExtensionData>((object)__result).Path = __state.Parameters.Path; } } private static void MM_Init(object detour) { _original = DetourExtensions.GenerateTrampolineEx<OriginalMethod>(detour); } private static AssetBundle MM_Det
BepInEx/plugins/Hayrizan-RTLC_Russian_Translation_Mods/RTLC/RTLC.Mods.dll
Decompiled 4 days ago
The result has been truncated due to the large size, download it to view full contents!
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.InteropServices; using System.Runtime.Versioning; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using Patchers; using RTLC; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("RTLC.Mods")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RTLC.Mods")] [assembly: AssemblyCopyright("Copyright © 2024")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("64342b36-9220-4eea-9a8d-1d464e48ed8d")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = "")] [assembly: AssemblyVersion("1.0.0.0")] internal class BundleLoader { public static AssetBundle RTLCBundle; public static bool TryLoadBundle() { try { string text = Path.Combine(Paths.BepInExRootPath, "plugins", "Hayrizan-RTLC_Russian_Translation_Mods", "RTLC", "Bundles", "rtlc.mods"); string text2 = Path.Combine(Paths.BepInExRootPath, "plugins", "RTLC", "Bundles", "rtlc.mods"); if (File.Exists(text)) { RTLCBundle = AssetBundle.LoadFromFile(text); return true; } if (File.Exists(text2)) { RTLCBundle = AssetBundle.LoadFromFile(text2); return true; } return false; } catch (Exception value) { Console.WriteLine(value); return false; } } public static bool TrySetTexture(ref Texture2D originalTexture, string textureName) { try { if (textureName == "") { return false; } Texture2D val = RTLCBundle.LoadAsset<Texture2D>(textureName); if ((Object)(object)val == (Object)null) { return false; } ImageConversion.LoadImage(originalTexture, ImageConversion.EncodeToPNG(val)); ((Texture)originalTexture).mipMapBias = -1f; return true; } catch (Exception value) { Console.WriteLine(value); return false; } } } internal class Dictionaries { public static readonly Dictionary<string, string> Nodes = new Dictionary<string, string> { { "32451234556434356634313213", "32451234556434356634313213" } }; public static readonly Dictionary<string, string> TextPostProcess = new Dictionary<string, string> { { "The cost to route to (.+?) is (\\$[0-9]+). It is", "Стоимость маршрута до $1 составляет $2." }, { "currently (.+?) on this moon.", "На этой луне сейчас $1." }, { "Routing autopilot to (.+?)", "Направление автопилота на $1" }, { "Your new balance is (\\$[0-9]+).", "Оставшиеся кредиты $1." }, { "You have requested to order (.+?). Amount: ([0-9]+).", "Вы запросили: $1. Количество: $2." }, { "Total cost of items: (\\$[0-9]+).", "Стоимость: $1." }, { "Ordered (.+?)", "Вы заказали: x$1" }, { "Our contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.", "Наши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения." }, { "SCANNERS REQUIRE ([0-9]+) SECONDS TO COOLDOWN\n\n", "СКАНЕРАМ ТРЕБУЕТСЯ $1 СЕК ДЛЯ ОХЛАЖДЕНИЯ\n\n" }, { "SAVED TO CACHE\n", "СОХРАНЕНО В КЭШ\n" }, { "REPORT GENERATED FROM SHIPS SCANNERS\n", "ОТЧЕТ СФОРМИРОВАН С ПОМОЩЬЮ СКАНЕРОВ КОРАБЛЯ\n" }, { "do actions with the reactor", "Информация о реакторе." }, { "Reactor instability at ([0-9]+)%\n", "Нестабильность реактора $1%\n" }, { "The reactor is in good health. No caution is necessary.\n\n", "Реактор находится в хорошем состоянии. Осторожность не требуется." }, { "USING LAST CACHED REPORT\n", "ИСПОЛЬЗОВАНИЕ ПОСЛЕДНЕГО КЭШ-ОТЧЕТА\n" }, { "SHIPS SCANNERS ARE STILL COOLING DOWN\n\n", "СКАНЕРЫ КОРАБЛЯ ВСЕ ЕЩЕ ОСТЫВАЮТ\n\n" }, { "Approximately ([0-9]+) seconds left until catastrophic nuclear event.\n\n", "До разрушения объекта осталось примерно $1 сек.\n\n" }, { "The reactor is about to cause a catastrophic nuclear event. This is your last chance. Any remaining crew members have very little time before a massive reactor fail. If there are still in the facility they most likely are not making it out, on their own.", "До разрушения объекта остались считанные секунды. Это ваш последний шанс. У оставшихся членов экипажа остается крайне мало времени до взрыва реактора. Если они все еще внутри сооружения, вероятно, они не успеют выбраться самостоятельно." }, { "The reactor is failing. You have very little time remaining before a catastrophic nuclear event happens.", "Реактор выходит из строя. У вас осталось совсем мало времени до того, как произойдет разрушение объекта." }, { "The reactor is becoming more unstable, it is about to fail. Do not leave the ship or you risk company property. Any crew members still outside the ship are advised to return before the reactor completely fails.", "Реактор становится все более нестабильным, он собирается выйти из строя. Не покидайте корабль, чтобы не подвергать опасности имущество компании. Всем членам экипажа, находящимся снаружи корабля, рекомендуется вернуться, прежде чем реактор полностью выйдет из строя." }, { "The reactor is beginning to fail. It is recommened to finish up and get ready to leave.", "Реактор выходит из строя. Рекомендуется завершить текущие дела и быть готовыми к отлету." }, { "A button that when pressed teleports you and your loot back to the ship. Must have Ship Teleporter unlocked!!!", "Кнопка, которая при нажатии телепортирует вас, и вашу добычу обратно на корабль. Телепорт на корабле должен быть разблокирован!!!" }, { "Early hand-held teleportation device based on an invention incepted in 2391 with public money, which was then sold to a private company for manufacturing. Innovations present in the device allow the user to return to a designated 'home location' with any objects they possess once used. In 2406, a massive stock of liquidated TeleMax Teleportation Remotes was acquired by The Company in aftermarket following a battery-related recall. As a result, the Company is able to offer them to its employees for cheap, but they are prone to swelling and combustion. Handle with care.", "Раннее портативное устройство телепортации, основанное на изобретении, созданном в 2391 году на государственные деньги, которое затем было продано частной компании для производства. Инновации, присутствующие в устройстве, позволяют пользователю вернуться в назначенное 'домашнее место' с любыми предметами, которые у него были после использования. В 2406 году компания приобрела огромную партию ликвидированных пультов телепортации TeleMax на вторичном рынке после отзыва, связанного с батареями. В результате Компания имеет возможность предлагать их своим сотрудникам по дешёвке, но они склонны к разбуханию и возгоранию. Обращаться осторожно.\n" }, { "Has a ([0-9]+)% chance to self destruct on use.", "Имеет $1% шанса самоуничтожиться при использовании." }, { "A newer, ostensibly-safer Teleportation Remote made by PortaCorp. PortaCorp was a subsidiary of Shipping Solutions Interplanetary, which was acquired by The Company in 2420, along with their entire stock of PortaCorp Teleportation Remotes. Looking to distance itself from the many safety scandals incurred by earlier adopters of the 'Remote Teleportation' technology, PortaCorp marketed its line of Teleportation Remotes with claims of their comparative ruggedness and reliability.", "Новый, якобы более безопасный пульт для телепортации, созданный PortaCorp. PortaCorp была дочерней компанией Shipping Solutions Interplanetary, которая была приобретена Компанией в 2420 году вместе со всеми её запасами Teleportation Remotes PortaCorp. Стремясь дистанцироваться от многочисленных скандалов, связанных с безопасностью, возникших среди первых пользователей технологии 'дистанционной телепортации', компания PortaCorp продавала свою линейку пультов для телепортации, заявляя об их сравнительной прочности и надежности.\n" }, { "Grants night vision, pick up and left click to equip. This will grant night vision for one players and will be lost on death.", "Предоставляет ночное видение, возьмите прибор и щёлкните ЛКМ, чтобы экипировать. Работает только на одном игроке и будет утеряно при смерти." }, { "Type `info nv headset batteries` for info on upgrading headset.", "Введите `info nv headset batteries` для получения информации об улучшения прибора." }, { "Very old military surplus phosphor lens modules, retrofitted for compatibility with modern Company-issued helmets and offered to employees of The Company on a subscription plan. The base package comes with cheap batteries, but premium subscriptions offer regular issuances of higher-quality energy solutions, ranging from hobby grade to industrial application power banks. The modules also come with DRM that prevents the user from improvising with other kinds of batteries.", "Очень старые армейские люминофорные линзовые модули, модернизированные для совместимости с современными шлемами, выпускаемыми Компанией, и предлагаемые сотрудникам Компании по подписке. Базовый пакет поставляется с дешёвыми батареями, но премиальные подписки предлагают регулярные выпуски более качественных энергетических решений, начиная от хобби-класса и заканчивая банками мощности промышленного применения. Модули также оснащены системой DRM, которая не позволяет пользователю импровизировать с другими типами батарей.\n" }, { "MEDKIT - (.+?)\n\n", "АПТЕЧКА - $1\n\n" }, { "Left click to heal yourself for (.+?) health.\n", "ЛКМ чтобы подлечить себя на $1 очков здоровья.\n" }, { "Can be used (.+?) times.", "Можно использовать $1 раз.\n" }, { "Looks at coil heads, don't lose it", "Следит за Пружиноголовыми, не теряй\n" }, { "Blocks all incoming damage, has (.+?) durability.", "Блокирует весь получаемый урон, имеет $1 прочности." }, { "DIVING KIT - (\\$[0-9]+)\n\nBreath underwater.\nWeights ([0-9]+) lbs and is two handed.", "ТРЁХБОЛТОВКА - $1\n\nДышите под водой.\nВесит $2 фунтов и занимает обе руки.\n" }, { "A portable container which has a maximum capacity of (.+?) and reduces the effective weight of the inserted items by (.+?) %.\n", "Переносная тачка с максимальной вместимостью $1 предмета. Уменьшает вес лежащих в ней предметов на $2 %.\n" }, { "It weighs (.+?) lbs", "Она весит $1 фунтов\n" }, { ">LATEGAME\nDisplays information related with Lategame-Upgrades mod\n\n", ">LATEGAME\nОтображает информацию, связанную с модом Lategame-Upgrades\n\n" }, { "Late Game Upgrades\n\nType `lategame store` or `lgu` to view upgrades.\n\nMost of the mod is configurable via the config file in `BepInEx/config/`.", "Late Game Upgrades\n\nВведите `lategame store` или `lgu` для получения списка улучшений.\n\nПочти всё в моде можно настроить через файл конфигурации в `BepInEx/config/`." }, { "Use the info command to get info about an item. EX: `info beekeeper`.", "Используйте команду `info` для получения информации о чём либо. НАПРИМЕР: `info beekeeper`." }, { "You must type the exact name of the upgrade \\(case insensitve\\).", "Вы должны вводить точное название улучшения. нечувствителен к регистру." }, { "To force wipe an lgu save file type `reset lgu`. \\(will only wipe the clients save\\).", "Чтобы стереть файл сохранения lgu, введите `reset lgu`. Стирает только сохранение клиента." }, { "To reapply any upgrades that failed to apply type `load lgu`.", "Чтобы повторно применить улучшения, которые не удалось загрузить, введите `load lgu`." }, { "In the case of credit desync to force an amount of credits type `forceCredits 123`", "В случае рассинхронизации кредитов, чтобы принудительно указать кол-во кредитов, введите `forceCredits 123`" }, { ">LGU / LATEGAME STORE\nDisplays the purchaseable upgrades from Lategame store.\n\n", ">LGU / LATEGAME STORE\nОтображает прокачки, которые можно приобрести в магазине Lategame.\n\n" }, { "You Upgraded (.+?) to level ([0-9]+)", "Вы Прокачали $1 до $2 уровня" }, { "You Purchased (.+?)", "Вы Приобрели $1" }, { "This upgrade is already max level", "Это улучшение уже максимального уровня" }, { "You already unlocked this upgrade.", "Вы уже разблокировали это улучшение." }, { "You can't afford this item.", "Вы не можете позволить себе это." }, { "LVL ([0-9]+) - (\\$[0-9]+): Carry weight becomes ([0-9]+)% of original.", "LVL $1 - $2: Вес предметов будет $3% от оригинала." }, { "Company-issued hydraulic girdles which are only awarded to high-performing (.+?) who can afford to opt in. Highly valued by all employees of The Company for their combination of miraculous health-preserving benefits and artificial, intentionally-implemented scarcity. Sardonically called the 'Back Muscles Upgrade' by some. Comes with a user manual, which mostly contains minimalistic ads for girdle maintenance contractors. Most of the phone numbers don't work anymore.\n\n", "Гидравлические пояса, выпускаемые компанией, вручаются только высокоэффективным $1, которые могут позволить себе подписаться. Высоко ценятся всеми сотрудниками Компании за сочетание чудесных преимуществ для сохранения здоровья и искусственного, намеренно созданного дефицита. Некоторые саркастически называют это упражнение 'модернизацией мышц спины'. Поставляется с руководством пользователя, который в основном содержит минималистическую рекламу подрядчиков по техническому обслуживанию поясов. Большинство телефонных номеров больше не работают.\n\n" }, { "LVL ([0-9]+) - (\\$[0-9]+) - Increases the amount of items that can be on sale by ([0-9]+)", "LVL $1 - $2 - Увеличивает количество предметов, которые можно сложить на продажу, на $3" }, { "LVL ([0-9]+) - (\\$[0-9]+):\nCircuit bees do ([0-9]+)% of their base damage.", "LVL $1 - $2:\nЭлектропчёлы наносят $3% от своего базового урона." }, { "On-the-job training package that teaches (.+?) proper Circuit Bee Nest handling techniques. Also comes with a weekly issuance of alkaline pills to partially inoculate (.+?) against Circuit Bee Venom.\n\n", "Пакет обучения на рабочем месте, который обучает $1 правильным приёмам обращения с гнездом Электропчёл. Также в комплект поставки входят еженедельные щёлочные таблетки для частичной инокуляции $2 от заражения Электропчёл.\n\n" }, { "LVL ([0-9]+) - (\\$[0-9]+): General scan distance increased by ([0-9]+) units. Ship and Entrance scan distance increased by ([0-9]+) units.", "LVL $1 - $2: Общее расстояние сканирования увеличится на $3 единиц. Расстояние сканирования Корабля и Входа в объект увеличится на $4 единиц." }, { "LVL ([0-9]+) - (\\$[0-9]+): Unlocks the `scan hives`, `scan scrap`, `scan doors`, `scan enemies` and `scan player` terminal scan command.", "LVL $1 - $2: Разблокирует команды `scan hives`, `scan scrap`, `scan doors`, `scan enemies` и `scan player` в терминале." }, { "LVL ([0-9]+) - (\\$[0-9]+): Scanner can scan scrap through the walls.\nhives and scrap command display the location of the most valuable hives and scrap on the map.", "LVL $1 - $2: У сканера появляется способность сканировать лом сквозь стены.\nКоманды hives и scrap отображают на карте наиболее ценные ульи и лом." }, { "A serialized Company-Issue Magazine subscription, called 'Stuff Finders'. Uniquely, (.+?) must subscribe to each issue of 'Stuff Finders' individually. Each separate subscription promises and delivers a weekly issuance of a magazine with the exact same information in it as last time, organized in a different order and with slightly different printing qualities each time. There are only three 'unique' issues, and each issue only has one or two pieces of actual useful information in it. The rest of the magazine is just ads for The Company's other offerings. There is an extra fee for cancelling a subscription of 'Stuff Finders' before terminating your employment. The useful information always comes in the form of an unlabelled service key or Ship terminal hyperlink.\n\n", "Подписка на серийный журнал Company-Issue Magazine под названием 'Искатели Хлама'. Уникально то, что $1 должен подписаться на каждый выпуск 'Искатели Хлама' индивидуально. Каждая отдельная подписка обещает и обеспечивает еженедельный выпуск журнала с той же информацией, что и в прошлый раз, организованных в разном порядке и каждый раз с немного разным качеством печати. Есть только три 'уникальных' выпуска, и каждый выпуск содержит только одну или две части действительно полезной информации. Остальная часть журнала представляет собой просто рекламу других предложений Компании. За отмену подписки на 'Искатели Хлама' до увольнения взимается дополнительная плата. Полезная информация всегда приходит в виде немаркированного сервисного ключа или гиперссылки на корабельный терминал.\n\n" }, { "LVL ([0-9]+) - (\\$[0-9]+): Stamina Time is (.+?) units longer", "LVL $1 - $2: Время Выносливости на $3 единиц дольше" }, { "Service package for (.+?). Opting into every maintenance procedure will arrange for your suit's pipes to be cleaned and repaired, filters re-issued, and DRM removed from the integrated air conditioning system.\n\n", "Пакет услуг для $1. Согласившись на каждую процедуру технического обслуживания, вы обеспечите очистку и ремонт труб вашего костюма, замену фильтров и удаление DRM из встроенной системы кондиционирования воздуха.\n\n" }, { "LVL ([0-9]+) - (\\$[0-9]+): Stun enemies around your ship for (.+?) seconds.", "LVL $1 - $2: Оглушает врагов вокруг корабля на $3 секунд." }, { "Service key for the Ship's terminal which allows your crew to legally use the Ship's 'Discombobulator' module. Comes with a list of opt-in maintenance procedures that promise to optimize the discharge and refractory of the system. Said document contains no mention of whatever it might be that it was included in the Ship's design to discombobulate.\n\n", "Сервисный ключ для корабельного терминала, позволяющий вашему экипажу легально использовать корабельный модуль 'Дискомбобулятор'. Поставляется со списком дополнительных процедур технического обслуживания, которые обещают оптимизировать слив и огнеупорность системы. В указанном документе не содержится никаких упоминаний о том, что это могло быть включено в конструкцию Корабля с целью сбить с толку.\n\n" }, { "Service key for the Ship's terminal which allows your crew to legally use the Ship's 'Static Attraction Field' module. Comes with a list of opt-in maintenance procedures that promise to optimize the module's function and field of influence. This Company-issued document is saddled with the uniquely-awkward task of having to ransom a safety feature back to the employee in text while not also admitting to the existence of an occupational hazard that was previously denied in court.\n\n", "Сервисный ключ для корабельного терминала, позволяющий вашему экипажу легально использовать корабельный модуль 'Поле статического притяжения'. Поставляется со списком дополнительных процедур обслуживания, которые обещают оптимизировать функцию и сферу влияния модуля. Этот документ, выпущенный Компанией, обременён уникальной неловкой задачей: необходимо вернуть сотруднику выкуп за функцию безопасности в текстовом виде, при этом не признавая при этом существование профессиональных рисков, которые ранее отрицались в суде.\n\n" }, { "The transmitter will write the letters faster and the restriction of characters will be lifted.", "Передатчик будет писать буквы быстрее, и ограничение на количество символов будет снято." }, { "LVL ([0-9]+) - (\\$[0-9]+): Collect samples from:\nHoarding Bug, Snare Flea", "LVL $1 - $2: Собирайте образцы с:\nЖуков-собирателей, Удушающих многоножек" }, { "LVL ([0-9]+) - (\\$[0-9]+): Collect samples from:\nBunker Spider, Baboon Hawk", "LVL $1 - $2: Собирайте образцы с:\nБункерных пауков, Бабуиновых ястребов" }, { "LVL ([0-9]+) - (\\$[0-9]+): Collect samples from:\nBracken, Eyeless Dog, Half/Thumper", "LVL $1 - $2: Собирайте образцы с:\nБрэкена, Слепой собаки, Половинчатого/Тампера" }, { "On-the-job training program that teaches your crew how to properly collect lab-ready samples of blood, skin, and organ tissue from entities found within the facility. These samples are valuable to The Company. Used to be a part of the standard onboarding procedure, but was made opt-in only in 2005 to cut onboarding costs.\n\n", "Программа обучения на рабочем месте, которая научит вашу команду правильно собирать готовые для лаборатории образцы крови, кожи и тканей органов у существ, обнаруженных в объекте. Эти образцы представляют ценность для Компании. Раньше это была часть стандартной процедуры адаптации, но её включили только в 2005 году, чтобы сократить расходы на регистрацию.\n\n" }, { "Guarantees at least one item will be on sale in the store.", "Гарантирует, что хотя бы один товар будет продаваться в магазине." }, { "Allows you to pick door locks by completing a minigame.", "Позволяет взламывать закрытые двери, проходя мини-игру." }, { "On-the-job training package that supplies (.+?) with proprietary knowledge of the 'Ram, Scan, Bump' technique for bypassing The Company's proprietary Low-Tech Manual Security Doors' security system. Comes with an 'all-nines-notched' key, a rubber gasket, and a plastic handle on a metal rod (.+?).\n\n", "Пакет обучения на рабочем месте, который даёт $1 собственные знания о технике 'Ram, Scan, Bump' для обхода собственной системы безопасности низкотехнологичных ручных защитных дверей компании. В комплект поставки входит ключ с насечкой 'девятки', резиновая прокладка и пластиковая ручка на металлическом стержне $2.\n\n" }, { "Broadcasted codes now explode map hazards.", "Распространяющиеся коды теперь взрывают опасности на карте." }, { "LVL ([0-9]+) - (\\$[0-9]+) - Guarantees the item sales' percentage to be at least ([0-9]+)%", "LVL $1 - $2 - Гарантирует, что процент продаж товаров будет не ниже $3%." }, { "LVL ([0-9]+) - (\\$[0-9]+):\nDrain time: (.+?) seconds // Regen time: (.+?) seconds", "LVL $1 - $2:\nВремя работы: $3 секунд // Время восст.: $4 секунд" }, { "(\\$[0-9]+):\nLightning has an effective distance of ([0-9]+) units\n\nThe closer you are to the ship the more likely it will be to attract lightning and keep you safe.", "$1: Громоотвод имеет $2 единиц расстояния работы\n\nЧем ближе вы к кораблю, тем больше вероятность, что он привлечёт молнию и обеспечит вам безопасность." }, { "LVL ([0-9]+) - (\\$[0-9]+):\nIncrease damage done with shovels by ([0-9]+)", "LVL $1 - $2: Увеличивает урон лопатами на $3" }, { "Multivitamins, creatine, and military surplus stimulants blended together and repackaged, then offered on subscription. Known to be habit-forming. The label includes a Company Surgeon General's warning about increased aggression.\n\n", "Мультивитамины, креатин и армейские излишки стимуляторов были смешаны и переупакованы, а затем проданы по подписке. Известно, что он вызывает привыкание. На этикетке имеется предупреждение главного хирурга роты о повышенной агрессии.\n\n" }, { "LVL ([0-9]+) - (\\$[0-9]+) - Decreases the landed moon's rotation force \\(time passing\\) by ([0-9]+)%", "LVL $1 - $2 - Уменьшает силу вращения луны на которую вы приземлились (время идёт медленнее) на $3%." }, { "LVL ([0-9]+) - (\\$[0-9]+): You can run (.+?) units faster", "LVL $1 - $2: Вы можете бежать на $3 единиц быстрее" }, { "A new pair of boots (.+?) a whole new lease on life. In this instance, it might also result in fewer wet sock incidents and consequent trenchfoot. After all, who knows how many people have walked in (.+?) shoes?\n\n", "Новая пара ботинок $1\u00a0— совершенно новая жизнь. В данном случае это также может привести к меньшему количеству случаев мокрых носков и, как следствие, траншейной стопы. В конце концов, кто знает, сколько людей ходили в $2 ботинках?\n\n" }, { "LVL ([0-9]+) - (\\$[0-9]+) - Increases the door's hydraulic capacity to remain closed by ([0-9]+) units", "LVL $1 - $2: Увеличивает способность шлюза корабля оставаться закрытым на $3 единиц" }, { "Sick Beats - (\\$[0-9]+)\nPlayers within a (.+?) unit radius from an active boombox will have the following effects:\n\nMovement speed increased by (.+?)\nDamage inflicted increased by (.+?)", "Биты Боли - $1\nИгроки в радиусе $2 единиц от играющего бумбокса будут иметь следующие эффекты:\n\nСкорость передвижения увеличивается на $3\nНаносимый урон увеличивается на $4" }, { "LVL ([0-9]+) - (\\$[0-9]+): Increases max health by ([0-9]+).", "LVL $1 - $2: Увеличивает максимальное здоровье на $3." }, { "An experimental Company-offered 'health treatment' program advertised only on old, peeling Ship posters, which are themselves only present in about 40% of all Company-issued Ships. Some Ships even have multiple. Nothing is known from the outside about how it works, and in order to be eligible for the program, (.+?) must sign an NDA.\n\n", "Экспериментальная программа 'оздоровительного лечения', предлагаемая Компанией, рекламируется только на старых, облупившихся плакатах Кораблей, которые сами присутствуют только примерно на 40% всех Кораблей, выпущенных Компанией. У некоторых кораблей их даже несколько. Извне ничего не известно о том, как это работает, и чтобы иметь право на участие в программе, $1 должен подписать соглашение о неразглашении.\n\n" }, { "LVL ([0-9]+) - (\\$[0-9]+): Jump (.+?) units higher.", "LVL $1 - $2: Прыжок на $3 единицы выше." }, { "One-time issuance of (.+?). Comes with a vague list of opt-in maintenance procedures offered by The Company, which includes such gems as 'actuation optimization', 'weight & balance personalization', and similar nigh-meaningless corpo-tech jargon. All of it is expensive.\n\n", "Единовременная выдача $1. Поставляется с расплывчатым списком процедур технического обслуживания, предлагаемых Компанией, который включает в себя такие жемчужины, как 'оптимизация срабатывания', 'персонализация веса и баланса' и подобный почти бессмысленный жаргон корпоративных технологий. Всё это дорого.\n\n" }, { "Displays your location and time when holding a walkie talkie.\nEspecially useful for fog.", "Отображает ваше местоположение и время, когда вы держите рацию.\nОсобенно полезно в туманную погоду." }, { ">EXTEND DEADLINE <DAYS>\nExtends the deadline by specified amount. Consumes ([0-9]+) for each day extended.\n\n", ">EXTEND DEADLINE <ДНЕЙ>\nПродлевает срок на указанное кол-во дней. Стоимость за каждый день для продления составляет $1.\n\n" }, { "You need to specify how many days you wish to extend the deadline for: \"extend deadline <days>\"", "Вам необходимо указать, на сколько дней вы хотите продлить срок: \"extend deadline <дней>\"" }, { "Not enough credits to purchase the proposed deadline extension.\n Total price: ([0-9]+)\n Current credits: ([0-9]+)", "Недостаточно кредитов для покупки предлагаемого продления срока.\n Цена: $1\n Ваши кредиты: $2" }, { "Invalid value \\((.+?)\\) inserted to extend the deadline.", "Вставлено недопустимое значение \"$1\" для продления крайнего срока." }, { "Extended the deadline by 1 day.", "Продление срока на 1 день." }, { "Extended the deadline by ([2,3,4]) days.", "Продление срока на $1 дня." }, { "Extended the deadline by ([0,5,6,7,8,9]) days.", "Продление срока на $1 дней." }, { ">INTERNS / INTERN\nRevives the selected player in radar with a new employee. Consumes ([0-9]+) credits for each revive.\n\n", ">INTERNS / INTERN\nВоскрешает выбранного на радаре игрока. Стоимость составляет $1 кредитов за каждое воскрешение.\n\n" }, { "(.+?) is still alive, they can't be replaced with an intern.", "$1 всё ещё жив, воскрешение невозможно." }, { "Interns cost ([0-9]+) credits and you have ([0-9]+) credits.", "Воскрешение стоит $1 кредитов, а вы имеете всего $2." }, { ">CONTRACT \\[moon\\]\n", ">CONTRACT [луна]\n" }, { "Gives you a random contract for a scrap item with considerable value and lasts til you leave from assigned planet.\nConsumes ([0-9]+) credits for each contract and will be unable to get another contract til current has expired.\nIf a moon is specified, it will generate a contract for that moon for the cost of ([0-9]+) Company credits instead.\n\n", "Даёт вам случайный контракт на лом, имеющий значительную ценность, и действует до тех пор, пока вы не покинете назначенную луну.\nСтоимость составляет $1 кредитов за каждый контракт. Вы не сможете получить другой контракт, пока не истечёт текущий.\nЕсли луна будет указана, вместо этого будет сгенерирован контракт для этой луны стоимостью $1 кредитов.\n\n" }, { "Type CONFIRM if you wish to have a contract on (.+?) for the cost of ([0-9]+) Company credits.", "Подтвердите `CONFIRM` что вы хотите заключить контракт на луну $1 за $2 кредитов Компании." }, { "Failed to confirm user's input. Invalidated specified moon contract request.", "Не удалось подтвердить ввод пользователя. Недействительный запрос для лунного контракта." }, { "A extraction contract has been accepted for (.+?)!", "Был заключён контракт по спасательной операции на $1!" }, { "You currently have a extraction contract on (.+?)!", "В настоящее время у вас заключён контракт по спасательной операции на $1!" }, { "Crew number 5339 have reported that one of their operatives was lost on this moon and left behind. You will have to find or bring a medkit to heal and extract the lost operative.", "Экипаж номер 5339 сообщил, что один из их сотрудников пропал на этой луне и остался там. Вам придётся найти его. Не забудьте взять аптечку, чтобы вылечить и спасти потерявшегося сотрудника." }, { "A defusal contract has been accepted for (.+?)!", "Был заключён контракт по обезвреживанию на $1!" }, { "You currently have a defusal contract on (.+?)!", "В настоящее время у вас заключён контракт по обезвреживанию на $1!" }, { "YOU MUST BE IN A DEFUSAL CONTRACT TO USE THIS COMMAND!", "ДЛЯ ИСПОЛЬЗОВАНИЯ ЭТОЙ КОМАНДЫ ВЫ ДОЛЖНЫ ВЫПОЛНЯТЬ КОНТРАКТ ПО ОБЕЗВРЕЖИВАНИЮ!" }, { "YOU MUST ENTER A SERIAL NUMBER TO LOOK UP!", "ДЛЯ ИНСТРУКЦИИ НЕОБХОДИМО ВВЕСТИ СЕРИЙНЫЙ НОМЕР!" }, { "CUT THE WIRES IN THE FOLLOWING ORDER:", "РАЗРЕЗАЙТЕ ПРОВОДА В СЛЕДУЮЩЕМ ПОРЯДКЕ:" }, { "red\n\ngreen\n\nblue", "красный\n\nзелёный\n\nсиний" }, { "red\n\nblue\n\ngreen", "красный\n\nсиний\n\nзелёный" }, { "green\n\nred\n\nblue", "зелёный\n\nкрасный\n\nсиний" }, { "green\n\nblue\n\nred", "зелёный\n\nсиний\n\nкрасный" }, { "blue\n\nred\n\ngreen", "синий\n\nкрасный\n\nзелёный" }, { "blue\n\ngreen\n\nred", "синий\n\nзелёный\n\nкрасный" }, { "An unknown party has planted a bomb at an integral point in this facility.\nYou must find the bomb and work together to defuse it.\nUse the `Lookup` command with the bombs serial number to get defusal instructions.", "Неизвестные лица заложили бомбу в важной точке этого объекта.\nВы должны найти бомбу и работать сообща, чтобы обезвредить её.\nИспользуйте команду `Lookup` с серийным номером бомбы, чтобы получить инструкции по обезвреживанию." }, { "A exorcism contract has been accepted for (.+?)!", "Был заключён контракт экзорцизма на $1!" }, { "You currently have a exorcism contract on (.+?)!", "В настоящее время у вас заключён контракт экзорцизма на $1!" }, { "Unusual activity in the spirit world has been reported at this facility.\nFind the ritual site to determine what type of demon it is, enter `demon DemonName` in the terminal to get the ritual instructions. Find ritual items and banish the demon.", "На этом объекте сообщалось о необычной активности в духовном мире.\nНайдите место проведения ритуала, чтобы определить, что это за демон; Введите в терминале `demon ИмяДемона`, чтобы получить инструкции по ритуалу. Найдите ритуальные предметы и изгоните демона." }, { "There is no known data on (.+?). Known spirits are:", "Никаких известных данных о $1 нет. Известные духи:" }, { "To banish this spirit you must assemble the following items:", "Чтобы изгнать этого духа, вам необходимо расставить на алтаре следующие предметы:" }, { "Teddy Bear", "Плюшевый мишка" }, { "Crucifix", "Распятие" }, { "Candelabra", "Канделябр" }, { "Bones", "Кости" }, { "Heart", "Сердце" }, { "A exterminator contract has been accepted for (.+?)!", "Был заключён контракт дезинсектора на $1!" }, { "You currently have a exterminator contract on (.+?)!", "В настоящее время у вас заключён контракт дезинсектора на $1!" }, { "It's been reported that the population of hoarder bugs on this moon have skyrocketed and become aggressive. You must destroy their nest at all costs.", "Сообщалось, что популяция Жуков-собирателей на этой луне резко возросла и стала агрессивной. Вы должны уничтожить их гнездо любой ценой." }, { "A data contract has been accepted for (.+?)!", "Был заключён контракт данных на $1!" }, { "You currently have a data contract on (.+?)!", "В настоящее время у вас заключён контракт данных на $1!" }, { "Our systems have detected an active PC somewhere in the facility.\nFind it, use the bruteforce command on the ship terminal with the devices IP to get login credentials, then use the cd, ls, and mv commands to find the .db file \\(enter `mv survey.db` in the containing folder\\).", "Наши системы обнаружили активный компьютер где-то на объекте.\nНайдите его, используйте команду `bruteforce` на корабельном терминале с IP-адресом устройства, чтобы получить учётные данные для входа, затем используйте команды cd, ls и mv, чтобы найти .db файл \"(введите `mv survey.db` в содержащейся папке)\"." }, { "Enter a valid address for a device to connect to!", "Введите действительный адрес устройства для подключения!" }, { "CONNECTION FAILED -- INVALID ADDRESS?", "СОЕДИНЕНИЕ НЕ УДАЛОСЬ – НЕВЕРНЫЙ АДРЕС?" }, { "CONNECTION ESTABLISHED --- RETRIEVING CREDENTIALS...\n\nUSER: (.+?)\nPASSWORD: (.+?)", "СОЕДИНЕНИЕ УСТАНОВЛЕНО --- ПОЛУЧЕНИЕ УЧЁТНЫХ ДАННЫХ...\n\nИМЯ ПОЛЬЗОВАТЕЛЯ: (.+?)\nПАРОЛЬ: (.+?)" }, { ">CONTRACT INFO\nDisplays all information related to each contract and how to complete it.\n\n", ">CONTRACT INFO\nОтображает всю информацию, относящуюся к каждому контракту и способам его выполнения.\n\n" }, { "Type `contract` into the terminal to start a contract on a random moon.", "Введите `contract` в терминал, чтобы заключить контракт на случайной луне." }, { "EXTRACTION CONTRACT: An injured NPC scavenger will spawn in the facility. You must find or bring them a medkit then carry them out of the facility and back to the ship.", "КОНТРАКТ СПАСЕНИЯ: На объекте появится раненый NPC-мусорщик. Вы должны найти его захватив с собой аптечку, вылечить его, а затем вынести из объекта на корабль." }, { "EXTERMINATOR CONTRACT: A hoarder bug nest and many angry hoarder bugs will spawn in the facility. You must find and destroy the next bringing an egg back to the ship as proof.", "КОНТРАКТ ДЕЗИНСЕКТОРА: На объекте появится гнездо Жуков-собирателей и большое, злое их множество. Вы должны найти и собрать их яйцо, а затем вернуть его на корабль в качестве доказательства." }, { "DATA CONTRACT: You must find a PC in the facility, enter its IP address into the ship terminal to get login credentials, then find the `survey.db` file to get a valuable floppy disc. EX: `cd Documents` `ls` `mv survey.db`", "КОНТРАКТ ДАННЫХ: Вы должны найти на объекте компьютер, ввести его IP-адрес в корабельный терминал, чтобы получить учётные данные для входа, затем найти файл `survey.db`, \u200b\u200bчтобы получить ценную дискету. ПРИМЕР: `cd Documents` `ls` `mv survey.db`" }, { "EXORCISM CONTRACT: You must find a ritual site in the facility, determine the ghost type, enter `demon ghostType` into the terminal, then conduct the correct ritual.", "КОНТРАКТ ЭКЗОРЦИЗМА: Вы должны найти место проведения ритуала внутри объекта, определить тип призрака, ввести в терминал `demon типДемона`, а затем провести правильный ритуал." }, { "BOMB DEFUSAL CONTRACT: You must find a bomb in the facility, enter `lookup SerialCode` into the terminal, then cut the correct wires in time.", "КОНТРАКТ ОБЕЗВРЕЖИВАНИЯ БОМБЫ: Вы должны найти бомбу внутри объекта, ввести `lookup СерийныйНомер` в терминал, а затем вовремя перерезать правильные провода." }, { ">ATK / INITATTACK\nStuns nearby enemies for a set period of time. Only applicable when Discombobulator has been purchased\n\n", ">ATK / INITATTACK\nОглушает ближайших врагов на определённый период времени. Применимо только когда Discombulator приобретён.\n\n" }, { "Discombobulate is ready, Type 'initattack' or 'atk' to execute.", "Дискомбобулятор готов; Для оглушения введите `initattack` или `atk`." }, { "You can discombobulate again in ([0-9]+) seconds.", "Вы сможете дискомбобуляторнуть снова через $1 секунд." }, { "No stunned enemies detected.", "Оглушённых врагов не обнаружено." }, { "Discombobulator hit ([0-9]+) enemies.", "Дискомбобулятор задел $1 врагов." }, { ">CD / COOLDOWN\nShows the current cooldown of the ship stun ability. Only applicable when Discombobulator has been purchased\n\n", ">CD / COOLDOWN\nПоказывает текущее время восстановления способности оглушения вокруг корабля. Применимо только когда Discombulator приобретён.\n\n" }, { ">SCRAP INSURANCE\nActivates an insurance policy on scrap stored in the ship incase of a team wipe occurs.\nCan only be bought while in orbit and will only apply in the next moon land after purchase.\nConsumes ([0-9]+) credits for each activation of insurance.\n\n", ">SCRAP INSURANCE\nАктивирует страховой полис на лом, хранящийся на корабле, в случае потери всего экипажа.\nМожно купить только на орбите и применимо только при следующей посадке на луне после покупки.\nСтоимость составляет $1 кредитов за каждую активацию страховки.\n\n" }, { "Scrap Insurance has been activated.\nIn case of a team wipe in your next trip, your scrap will be preserved.", "Страховка лома активирована.\nВ случае потери всего экипажа в вашей следующей поездке, весь ваш лом на корабле сохранится." }, { "You already purchased insurance to protect your scrap belongings.", "Вы уже приобрели страховку лома." }, { "You can only acquire insurance while in orbit.", "Вы можете приобрести страховку только на орбите." }, { "Not enough credits to purchase Scrap Insurance.\nPrice: ([0-9]+)\nCurrent credits: ([0-9]+)", "Недостаточно кредитов для покупки Страховки Лома.\nЦена: $1\nВаши кредиты: $2" }, { "\\[TooManyEmotes\\]\nType \"Emotes\" for a list of commands.", "[TooManyEmotes]\nВведите \"Emotes\" для получения списка команд." }, { "For a list of Emote commands.", "Магазин эмоций." }, { "\\[TooManyEmotes\\]\n\nStore\n------------------------------", "Добро пожаловать в магазин эмоций.\nКупите понравившуюся эмоцию, введя её название.\n------------------------------" }, { "Remaining emote credit balance:", "Оставшийся баланс кредитов эмоций:" }, { "New emote credit balance:", "Новый баланс кредитов эмоций:" }, { "Emote credit balance:", "Баланс кредитов эмоций:" }, { "Remaining group credit balance:", "Оставшийся баланс кредитов группы:" }, { "New group credit balance:", "Новый баланс кредитов группы:" }, { "Group credit balance:", "Баланс кредитов группы:" }, { "\\[Purchased\\]", "[Куплено]" }, { "You have requested to order a new emote.", "Вы запросили: новая эмоция." }, { "You have already purchased this emote!", "Вы уже приобрели эту эмоцию!" }, { "You have successfully purchased a new emote!", "Вы успешно приобрели новую эмоцию!" }, { "Your new emote is registered in your emote menu.", "Новая эмоция зарегистрирована в вашем меню эмоций." }, { "Page:", "Страница:" }, { "Slot:", "Слот:" }, { "KNIGHT\n\nScientific name: Armoricus Rubr.\n\nThe Armoricus Rubr serves as an atypical defensive mechanism within the mansion. Their physical composition resembles traditional medieval knight armour, hence the colloquial term \"Knights\" to describe them. Intriguingly, examinations have failed to reveal any internal organs, machinery, or wiring within the armour, suggesting a mechanism seemingly governed by mystical forces.\n\nThe manner in which they initiate movement upon encountering an observer, cease motion upon scrutiny, and emulate the behaviors of Coil-heads alludes to a deliberate and seemingly orchestrated nature. This has lend to an unsettling impression that we are being toyed with by some greater, more terrifying being.\n\n", "РЫЦАРЬ\n\nНаучное название: Armoricus Rubr.\n\nArmoricus Rubr служит нетипичным защитным механизмом внутри особняка. Их физический состав напоминает традиционные средневековые рыцарские доспехи, отсюда и разговорный термин \"рыцари\" для их описания. Любопытно, что обследования не выявили никаких внутренних органов, механизмов, или проводов внутри брони, что позволяет предполагать, что механизм, по-видимому, управляется мистическими силами.\n\nТо, как они начинают движение при встрече с наблюдателем, прекращают движение при внимательном рассмотрении и имитируют поведение Пружиноголовых, намекает на преднамеренное и, по-видимому, организованное поведение. Это создаёт тревожное впечатление, что с нами играет какое-то более великое и устрашающее существо.\n\n" }, { "There are no missions at the moment...", "На данный момент миссий нет..." }, { "Status: Incomplete", "Статус: Не выполнено" }, { "Status: Complete", "Статус: Выполнено" }, { "Reward: ([0-9]+)", "Награда: $1" }, { "Name: Lightning rod", "Название: Громоотвод" }, { "Name: Witness a Celestial Event", "Название: Свидетель трагического события" }, { "Name: Retrieve Your Pal's Corpse", "Название: Возврат трупа вашего приятеля" }, { "Name: Get a beehive!", "Название: Добыча Улья!" }, { "Name: Preserve the Group's Life", "Название: Сохранение жизни экипажа" }, { "Name: Defeat the Monster", "Название: Победа над монстром" }, { "Name: Obtaining the Apparatus", "Название: Извлечение Реактора" }, { "Name: Find Scrap", "Название: Поиск лома" }, { "Name: Repair the Valves", "Название: Починка клапанов" }, { "Objective: Become the human lightning rod, stop a lightning with style", "Цель: Станьте человеческим громоотводом, остановите молнию со стилем" }, { "Objective: Witness the dramatic farewell of a fellow crewmate", "Цель: Станьте свидетелем драматической смерти товарища по команде" }, { "Objective: Because being a hero also means playing space undertaker", "Цель: Потому что быть героем — это ещё и быть личным гробовщиком друзей" }, { "Objective: Because even in space, we all need some honey and laughter", "Цель: Потому что даже в космосе нам всем нужны мёд и смех." }, { "Objective: Make sure at least ([0-9]+) crewmates survive the space odyssey!", "Цель: Убедитесь, что хотя бы $1 из членов экипажа выжили в этой вылазке!" }, { "Objective: Embark on a daring mission to eliminate a menacing creature", "Цель: Отправьтесь на смелую миссию по уничтожению грозного существа" }, { "Objective: Take the Generator from the factory to the ship.", "Цель: Добудьте Реактор в объекте, и принесите его на корабль." }, { "Objective: Find the next scrap: (.+?)", "Цель: Найдите следующий лом: $1" }, { "Objective: As broken as your heart, show your skills and fix at least ([0-9]+) of them.", "Цель: Столь же разбитые, как и ваше сердце, покажите свои навыки и исправьте хотя бы $1 из них." }, { "The cost to route to (.+?) is (.+?). It is currently (.+?) on this moon.", "Стоимость маршрута до $1 составляет $2. На этой луне сейчас $3." }, { "The cost to route to (.+?) is (.+?). It is\ncurrently (.+?) on this moon.", "Стоимость маршрута до $1 составляет $2. На этой луне сейчас $3." }, { "\\[DATA CORRUPTED OR OVERWRITTEN\\]", "[ДАННЫЕ ПОВРЕЖДЕНЫ ИЛИ ПЕРЕЗАПИСАНЫ]" }, { "POPULATION: Abandoned.\nCONDITIONS: Thousands of deep, industrial mining pits litter the surface of the moon. Frequent earthquakes and tremors.\nHISTORY: 13-Kast was found to have rich deposits of precious metals deep beneath the surface, begining a rush of mass-scale industrial quarries all around the moon. Soon after the initial rush, the crust of the moon was destabilized and all mining operations were ceased.\nFAUNA: A wide variety of fauna was harbored to the moon, supporting particularly fauna which could thrive off the multituteds of abandoned equipment.", "НАСЕЛЕНИЕ: Заброшено.\nУСЛОВИЯ: Тысячи глубоких промышленных карьеров разбросаны по поверхности Луны. Частые землетрясения и толчки.\nИСТОРИЯ: Было обнаружено, что 13-Kast имеет богатые залежи драгоценных металлов глубоко под поверхностью, что положило начало массовым промышленным карьерам по всей Луне. Вскоре после первоначального натиска кора Луны была дестабилизирована, и все операции по добыче полезных ископаемых были прекращены.\nФАУНА: На Луне обитало большое разнообразие фауны, которая могла процветать за счёт множества заброшенного оборудования." }, { "A small civilization recently abandoned this moon. When asked for the reason why, the only response was \"moon's haunted.\"", "Небольшая цивилизация недавно покинула эту луну.\nКогда её спросили о причине, единственным ответом было: \"Луна преследует.\"" }, { "A warm, temperate moon, once frozen but now warmed by intense industrial exploitation to harvest a bacterial strain from its ice.\nIt was named for its active tectonic plates that created magnificent mountains of pure, incandescent ice under the sun's rays in a clear, carbon-free atmosphere.\nThough the atmosphere became breathable after it's pollution, it was at the cost of its solid surface.\nTectonic plates and water did not get along well during the early melting of the moon, which is why the majority of the population left the planet.\nBut there are no more plates anymore, the remaining population eventually left as a result of the numerous space travels that brought various stowaway megafaunas to the remaining floating platforms on the Moon.", "Тёплая, умеренная луна, когда-то замёрзшая, но теперь нагретая в результате интенсивной промышленной эксплуатации с целью сбора изо льда штамма бактерий.\nЛуна была названа в честь своих активных тектонических плит, которые создали под солнечными лучами великолепные горы чистого, раскалённого льда в чистой, свободной от углерода атмосфере.\nХотя после загрязнения атмосфера стала пригодной для дыхания, это произошло за счет её твёрдой поверхности.\nТектонические плиты и вода плохо ужились во время раннего таяния Луны, из-за чего большая часть населения покинула планету.\nНо плит больше нет, оставшееся население в конечном итоге покинуло Луну в результате многочисленных космических путешествий, которые завезли на оставшиеся плавучие платформы на Луне различную безбилетную мегафауну." }, { "A water heavy planet that is capable of supporting life. \n\nDanger levels are minimal.", "Тяжёлая водная планета, способная поддерживать жизнь.\n\nУровни опасности минимальны." }, { "Enviromental dangers are low. Reports indicated that multiple dangerous creatures roam the surface. \nExplore carefully.", "Экологическая опасность низкая. В сообщениях указывается, что по поверхности бродит множество опасных существ.\nИсследуйте внимательно." }, { "WARNING: Danger levels are High.\nThis planet has reportedly sustained complex life. An advanced civilization was detected. Current status is unknown.", "ВНИМАНИЕ: Уровень опасности Высокий.\nСообщается, что на этой планете существует сложная для понимания науке жизнь. Обнаружена развитая цивилизация. Текущий статус неизвестен." }, { "An abandoned castle from years passed. A renowned ruler once lived here.", "Заброшенный замок прошедших лет. Когда-то здесь жил известный правитель." }, { "The old abandoned spring and coil factory.", "Старый заброшенный завод по производству пружин и катушек." }, { "Do you remember slinkys?", "Помните слинкуса?" }, { "ROLLING-GIANTS", "КАТЯЩИЕСЯ-ГИГАНТЫ" }, { "Rolling Giant's danger level: 80%", "Уровень опасности Катящихся Гигантов: 80%" }, { "We're back.", "Мы вернулись." }, { "Created by La Reunion TX artists and volunteers who care about West Dallas, the oversized puppets of Bridge-o-Rama's Parade of Giants nearly stole the show during the opening weekend of the Margaret Hunt Hill Bridge.", "Созданные художниками и волонтёрами La Reunion TX, которые заботятся о Западном Далласе, огромные марионетки из «Парада гигантов» Bridge-o-Rama чуть не затмили всех в первые выходные на мосту Маргарет Хант-Хилл." }, { "See them again. Learn their stories.", "Увидев их снова. Узнайте их истории." }, { "Bridge-o-Rama's Parade of Giants at Dallas City Hall.", "Парад гигантов Bridge-o-Rama в мэрии Далласа." }, { "Opening reception 6 p.m., Tuesday, June 19, 1500 Marilla St.", "Приём по случаю открытия в 18:00, вторник, 19 июня, Ул. 1500 Марилла." }, { "86 Ether - \\(Downtown\\)", "86 Ether - (Центр города)" }, { "\\**Objective:\\**", "**ЗАДАНИЕ:**" }, { "Secure valuable scraps, Investigate remains of the city.", "Соберите ценные обломки, Исследуйте остатки города." }, { "Data suggests previous enhabitants of the planet fonded largerly over tokens of value which led to there demise. Previous scrap retrival teams led by Lethal Moon Company have attempted to navigate Ethers abandonded terrain however the rival company has a survival rating of 3% on this moon.", "Данные свидетельствуют о том, что предыдущие жители планеты в основном любили ценные знаки, что и привело к их гибели. Предыдущие команды по поиску лома во главе с Lethal Moon Company пытались перемещаться по заброшенной местности Ether, однако конкурирующая компания имеет рейтинг выживаемости на этой луне 3%." }, { "The COMPANY has gracefully provided your crew the coordinates of Ether. Try to inflitrate the VAULT located in downtown Ether.", "КОМПАНИЯ любезно предоставила вашему экипажу координаты Ether. Попытайтесь проникнуть в ХРАНИЛИЩЕ, расположенное в центре города." }, { "Sigurd’s Danger Level: 60%", "(Креветка)\n\nУровень опасности по шкале Сигурда: 60%" }, { "Scientific name: Canispiritus-Artemus", "Научное название: Canispiritus-Artemus" }, { "Shrimps are dog-like creatures, known to be the first tenant of the Upturned Inn. For the most part, he is relatively friendly to humans, following them around, curiously stalking them. Unfortunately, their passive temperament comes with a dangerously vicious hunger.\r\nDue to the nature of their biology, he has a much more unique stomach organ than most other creatures. The stomach lining is flexible, yet hardy, allowing a Shrimp to digest and absorb the nutrients from anything, biological or not, so long as it isn’t too large.", "Креветки — существа, похожие на собак, которые, как известно, были первыми обитателями перевёрнутой гостиницы. По большей части они относительно дружелюбны к людям, преследуя повсюду и с любопытством выслеживая их. К сожалению, их пассивный темперамент сопровождается опасно жестоким голодом.\r\nИз-за особенностей биологии у них гораздо более уникальный желудок, чем у большинства других существ. Слизистая оболочка желудка гибкая, но прочная, что позволяет Креветкам переваривать и усваивать питательные вещества из чего угодно, биологического или нет, при условии, что он не слишком велик." }, { "However, this evolutionary adaptation was most likely a result of their naturally rapid metabolism. He uses nutrients so quickly that he needs to eat multiple meals a day to survive. The time between these meals are inconsistent, as the rate of caloric consumption is variable. This can range from hours to even minutes and causes the shrimp to behave monstrously if he has not eaten for a while.", "Однако эта эволюционная адаптация, скорее всего, была результатом их естественного быстрого метаболизма. Они используют питательные вещества так быстро, что им приходится есть несколько раз в день, чтобы выжить. Время между этими приёмами пищи не является постоянным, поскольку уровень потребления калорий варьируется. Это может длиться от нескольких часов до даже минут и заставляет креветку вести себя чудовищно, если она какое-то время не ела." }, { "Known to live in abandoned buildings, shrimp can often be seen in large abandoned factories or offices scavenging for scrap metal, to eat. That isn’t to say he can’t be found elsewhere. He is usually a lone hunters and expert trackers out of necessity.", "Креветки, как известно, живут в заброшенных зданиях, их часто можно увидеть на крупных заброшенных фабриках или в офисах в поисках лома, чтобы поесть. Это не значит, что его нельзя найти где-то еще. Обычно он охотник-одиночка и опытный следопыт по необходимости." }, { "Sigurd’s Note:", "Примечание Сигурда:" }, { "If this guy spots you, you’ll want to drop something you’re holding and let him eat it. It’s either you or that piece of scrap on you.", "Если этот дружок вас заметит, вам захочется бросить то, что вы держите, и позволить ему съесть это. Либо ты, либо твой лом." }, { "it’s best to avoid letting him spot you. I swear… it’s almost like his eyes are staring into your soul.", "лучше не позволять ему вас заметить. Клянусь… его глаза как будто смотрят тебе в душу." }, { "I never want to see one of these guys behind me again.", "Я больше никогда не хотел бы видеть позади себя одного из этих дружочков." }, { "IK: <i>Sir, don't be sad! Shrimp didn't hate you.\r\nhe was just... hungry.</i>", "ИК: <i>Сэр, не грустите! Креветка не ненавидела вас.\r\nона просто была... голодна.</i>" }, { "Run and hide.", "Беги и прячься." }, { "Skibidi toilet to you too!", "Скибиди туалетов и тебе!\n\n" }, { "BEAR WITNESS TO THE SKULL", "СВИДЕТЕЛЬСТВО ЧЕРЕПА\n\n" }, { "Sigurd's danger level: 5%", "(Пиперы)\n\nУровень опасности по шкале Сигурда: 5%" }, { "Scientific name: Pestiferous-oculus", "Научное название: Pestiferous-oculus" }, { "Commonly referred to as Peepers, Pestiferous-oculus is a species of parasite that can survive in almost any environment. They have a star-shaped body composed of 5 stubby limbs, a singular central eye, and are coated in a layer of dark, sticky mucus.", "Pestiferous-oculus, которого обычно называют Пиперами, — это вид паразита, который может выжить практически в любой среде. У них звездообразное тело покрытое слоем тёмной липкой слизи; их тело состоит из пяти коротких конечностей и одним глазом в центре." }, { "When they spot a potential host, they will relentlessly launch themselves at it, attempting to wrap themselves around a head or appendage. Despite their small size, they are surprisingly dense, so while they are not much of a threat on their own, they can become a heavy burden if enough of them are stuck to a single host. It is currently unknown how this situation benefits them in any way.", "Когда они замечают потенциального хозяина, они безжалостно бросаются на него, пытаясь обернуться вокруг его головы и частей тела. Несмотря на свой небольшой размер, они на удивление плотные, поэтому, хотя сами по себе они не представляют большой угрозы, они могут стать тяжёлым бременем, если достаточное их количество прилипнет к одному своему хозяину. На данный момент неизвестно, какую пользу им приносят эти действия." }, { "Peepers are small and weak, and can be dealt with easily with most equipment. If their host receives damage, they will detach and be vulnerable for a short time. While other creatures tend to ignore them, peepers sometimes make noise when threats to their host are nearby.", "Пиперы маленькие и слабые, с ними легко справиться с помощью большинства инструментов. Если их хозяин получит повреждения, они отделятся от него и на короткое время станут уязвимыми. В то время как другие существа склонны игнорировать их, Пиперы иногда издают шум, если поблизости находится угроза их хозяину." }, { "A terrifying and elusive creature, the Demogorgon is a name that instills fear in those who know of it. This bipedal entity, named after the demon prince from ancient mythology, is characterized by its humanoid form, towering stature, and a face that opens up into petal-like flaps, revealing rows of sharp teeth. Its skin resembles a dark, rough hide, enhancing its intimidating presence.", "(Демогоргон)\n\nУжасающее и неуловимое существо, Демогоргон — это имя, которое вселяет страх в тех, кто о нём знает. Это двуногое существо, названное в честь принца демонов из древней мифологии, характеризуется гуманоидной формой, высоким ростом и лицом, которое раскрывается в форме лепестков, обнажая ряды острых зубов. Его кожа напоминает тёмную, грубую шкуру, усиливая его устрашающий вид." }, { "The Demogorgon is primarily a solitary hunter, known for its remarkable agility and strength. It exhibits a blend of animalistic instincts and near-human intelligence, making it a formidable predator. Its hunting strategy is unique, often involving stealth and sudden bursts of speed to ambush its prey. Unlike many predators, the Demogorgon shows a curious affinity for areas with electromagnetic anomalies.", "Демогоргон — прежде всего охотник-одиночка, известный своей замечательной ловкостью и силой. Он демонстрирует смесь животных инстинктов и интеллекта, близкого к человеческому, что делает его грозным хищником. Его охотничья стратегия уникальна, часто она включает в себя скрытность и внезапные скачки скорости, чтобы застать жертву в засаде. В отличие от многих хищников, Демогоргон проявляет любопытную привязанность к областям с электромагнитными аномалиями." }, { "One of the most chilling aspects of the Demogorgon is its method of attack. It is known to capture prey alive, often dragging them into an alternate dimension, a parallel reality shrouded in mystery. This alternate dimension, often referred to as the 'Upside Down', is a dark, desolate mirror of our world, where the Demogorgon is at its most powerful.", "Одним из самых пугающих аспектов Демогоргона является его метод атаки. Известно, что они ловят добычу живой, часто утаскивая её в альтернативное измерение, параллельную реальность, окутанную тайной. Это альтернативное измерение, часто называемое 'Изнанка'; представляет собой тёмное, пустынное зеркало нашего мира, где Демогоргон наиболее силён." }, { "Though reports vary, survivors describe the Demogorgon's roar as a blood-curdling sound that can paralyze its prey with fear. Its presence is often marked by flickering lights and a drop in temperature, indicating its ability to affect the environment around it.", "Хотя сообщения разнятся, выжившие описывают рёв Демогоргона как леденящий кровь звук, который может парализовать жертву от страха. Его присутствие часто отмечается мерцанием света и падением температуры, что указывает на его способность влиять на окружающую среду." }, { "While the Demogorgon is typically reclusive and avoids human contact, it becomes fiercely aggressive if provoked or when hunting. It has been observed to have a heightened sense of smell and can track its prey with relentless determination.", "Хотя Демогоргон обычно ведёт затворнический образ жизни и избегает контактов с людьми, он становится очень агрессивным если его спровоцировать, во время охоты он также очень агрессивен. Было замечено, что у него обострённое обоняние, и он может выслеживать свою добычу с неустанной решимостью." }, { "Due to the enigmatic nature of the Demogorgon and its ties to the Upside Down, much about this creature remains a subject of speculation and fear among researchers and adventurers alike.", "Из-за загадочной природы Демогоргона и его связи с Изнанкой, многое в этом существе остаётся предметом спекуляций и опасений как среди исследователей, так и среди искателей приключений.\n\n" }, { "ROUTE TABLE OFFSET: NAVIGATION ERROR\n\nIT IS ADVISED TO LAND THE SHIP TO ALLOW RECALIBRATION OF SYSTEMS AND RESTORATION OF FUNCTIONALITY\n\n", "СМЕЩЕНИЕ ТАБЛИЦЫ МАРШРУТА: ОШИБКА НАВИГАЦИИ\n\nРЕКОМЕНДУЕТСЯ ПОСАДИТЬ СУДНО ДЛЯ ПЕРЕКАЛИБРОВКИ СИСТЕМ И ВОССТАНОВЛЕНИЯ ФУНКЦИОНАЛЬНОСТИ\n\n" }, { "POPULATION: Deceased/Mutated\nCONDITIONS: Cold, hard rocky terrain, no surface plant life detected.\nFAUNA: A dead ecosystem.", "НАСЕЛЕНИЕ: Погибло/Мутировало\nУСЛОВИЯ: Холодная, твёрдая каменистая местность, наземная растительность не обнаружена.\nФАУНА: Мёртвая экосистема." }, { "POPULATION: Drowned.\nCONDITIONS: Cold wet terrain, supports aquatic plant life.\nFAUNA: A healthy ecosystem, fauna supports neutral behaviour.", "НАСЕЛЕНИЕ: Утопленники.\nУСЛОВИЯ: Холодная влажная местность, поддерживает жизнь водных растений.\nФАУНА: Здоровая экосистема, фауна поддерживает нейтральное поведение." }, { "POPULATION: Transformed.\nCONDITIONS: Warm, Dry sandy terrain, supports plant life such as cactaceae and rarely polypodiophyta.\nFAUNA: A thriving ecosystem, creatures support agressive behaviour.", "НАСЕЛЕНИЕ: Преобразовано.\nУСЛОВИЯ: Тёплая сухая песчаная местность поддерживает жизнь таких растений, как кактусы и редко полиподиофиты.\nФАУНА: Процветающая экосистема, существа поддерживают агрессивное поведение." }, { "POPULATION: Killed.\nCONDITIONS: Warm, Dry dirt terrain, supports plant life such as Fabaceae.\nFAUNA: A thriving Avian ecosystem, creatures support agressive behaviour.", "НАСЕЛЕНИЕ: Убито.\nУСЛОВИЯ: Тёплая, сухая грунтовая местность поддерживает жизнь растений, таких как Fabaceae.\nФАУНА: Процветающая птичья экосистема, существа поддерживают агрессивное поведение." }, { "POPULATION: Deceased.\nCONDITIONS: Extremely hot, Dry dusty terrain, Rarely supports living plant life due to recent volcanic activity.\nFAUNA: A desperate ecosystem, remaining creatures support agressive behaviour.", "НАСЕЛЕНИЕ: Покойное.\nУСЛОВИЯ: Чрезвычайно жаркая, сухая пыльная местность, редко поддерживает живую растительную жизнь из-за недавней вулканической активности.\nФАУНА: Отчаянная экосистема, оставшиеся существа поддерживают агрессивное поведение." }, { "POPULATION: Sacrificed/Deceased.\nCONDITIONS: Cold, wet snowy terrain, supports plant life.\nFAUNA: A balanced ecosystem, creatures support very agressive behaviour.", "НАСЕЛЕНИЕ: Принесли в жертву/погибло.\nУСЛОВИЯ: Холодная, влажная снежная местность, поддерживает жизнь растений.\nФАУНА: Сбалансированная экосистема, существа поддерживают очень агрессивное поведение." }, { "POPULATION: Lost.\nCONDITIONS: Warm lush terrain, supports pleny of flora, acidic pools present.\nFAUNA: A healthy ecosystem, fauna supports neutral behaviour.", "НАСЕЛЕНИЕ: Утеряно.\nУСЛОВИЯ: Тёплая, пышная местность, богатая флора, присутствует ядовитая вода.\nФАУНА: Здоровая экосистема, фауна поддерживает нейтральное поведение." }, { "Routing to the Bio Spheres", "Направляемся к Био Сферам" }, { "Routing to the Sinking City", "Направляемся к Затонувшему Городу" }, { "Routing to the Death Lab", "Направляемся к Лаборатории Смерти" }, { "Routing to the Mountain Factories", "Направляемся к Фабрикам в Горах" }, { "Routing to the desolated mines.", "Направляемся к заброшенным шахтам." }, { "Routing to the Polar Vaults", "Направляемся к Полярным Хранилищам" }, { "Routing to the Halls of The Lost.", "Направляемся к Залам Потерянных." }, { "POPULATION: Abandoned.", "НАСЕЛЕНИЕ: Заброшено." }, { "CONDITIONS: Jagged and dry, it is a old mine.", "УСЛОВИЯ: Зубчатая и сухая поверхность, это старая шахта." }, { "FAUNA: A great variety of aggressive and dangerous lifeforms inhabits this moon.", "ФАУНА: На этой луне обитает множество агрессивных и опасных форм жизни." }, { "To sell items on the ship.", " [ВСЁ|КВОТА|<КОЛ-ВО>] - Продать лом с корабля." }, { ">LAUNCH\nTo launch or land the ship. Host needs to do the very first launch.", ">LAUNCH\nПосадить или заставить взлететь корабль. Самый первый запуск делает хост." }, { ">DOOR\nToggle the ship door.", ">DOOR\nОткрыть/закрыть шлюз корабля." }, { ">LIGHTS\nToggle the lights.", ">LIGHTS\nВкл/выкл свет." }, { ">TP\nTeleport the currently active player on the view monitor to the ship. Must have a teleporter.", ">TP\nТелепортируйте выбранного игрока на мониторе к себе на корабль. Телепортер должен быть куплен." }, { ">TIME\nGet the current time whilst on a moon.", ">TIME\nУзнать текущее время на Луне." }, { ">TARGET <AMOUNT>\nSet a target sell requirement for the target monitor.", ">TARGET <КОЛ-ВО>\nУстановите требуемую цель продажи для монитора с целями." }, { "I finally found a backdoor to the logs system in order to add new information for future employees.", "Я наконец-то нашёл лазейку в системе журналов, чтобы добавить новую информацию для будущих сотрудников." }, { "This is my first entry, I hope it will save some lives.", "Это моя первая запись, надеюсь, она спасёт несколько жизней." }, { "Danger level: 30%", "(Бумбы)\n\nУровень опасности: 30%" }, { "If you're reading this, that means you met one of those things.", "Если вы читаете это, значит, вы уже встретили одну из этих штук." }, { "Yes I called them Boombas, considering they are somewhat reminiscent of those ancient cleaning robots, and one of them blew up in my face.", "Да, я назвал их Бумбами, поскольку они чем-то напоминают тех древних роботов-уборщиков, и один из них взорвал мне лицо." }, { "They do not seem to be living organisms but rather some kind of old security devices powered by god knows what.", "Они не кажутся живыми организмами, а скорее какими-то старыми охранными устройствами, работающими бог знает от чего." }, { "I witnessed my guys explode when they attempted to take a screw off one of those things so I ain't touching it.", "Я был свидетелем того, как мои напарники взорвались, когда они попытались отвинтить одну из этих штук, поэтому я к ней не прикасаюсь." }, { "Here is what I do know:", "Вот что я знаю:" }, { "They are not very fast, and not very smart.", "Они не очень быстры и не очень умны." }, { "When they lose line of sight they seem to forget you exist, but they do have some kind of hearing ability and will investigate noises.", "Когда они теряют линию видимости, они, кажется, забывают о вашем существовании, но у них есть что-то вроде слуха, поэтому они будут исследовать различные шумы." }, { "Most importantly, they love blowing up when you touch them.", "Самое главное - они просто обожают взрываться когда к ним дотрагиваются." }, { "It is like a magic wand, for cool people.", "Ракетомёт\n\nЭто как волшебная палочка, для крутых чуваков." }, { "Shoots flares which light up areas, attract monsters, and can be used for signalling.", "Сигнальный пистолет\n\nВыпускает сигнальные ракеты, которые освещают области, привлекают монстров и могут использоваться для подачи сигналов." }, { "Ammo for Flareguns", "Аварийный сигнал (патрон)\n\nПатрон для Сигнального пистолета" }, { "A remote radar tablet, for easy remote access to your ship's radar.", "Радар-усилитель\n\nПланшет с удалённым радаром для удобного удалённого доступа к радару вашего корабля." }, { "\\*Slaps utility belt\\* This bad boy can fit so much scrap in it.", "Универсальный пояс\n\n*Шлепок поясом* Этот плохой мальчик может вместить в себя столько лома." }, { "A hacking tool for opening gates and disabling turrets/mines", "Хакерский инструмент\n\nПригодится для открытия больших дверей и отключения турелей/мин" }, { "When used requires the user to solve several math problems in order to obtain the password.", "При использовании, пользователю необходимо решить несколько математических примеров, чтобы обойти систему." }, { "Example:", "Например:" }, { "then we do 14 mod 10, which is 4.", "тогда делаем 14 по модулю 10, то есть ответ будет 4." }, { "If a result is positive, we just take the last number of the result.", "Если результат положительный, мы просто берём последнее число результата." }, { "If a result is negative, we first get the absolute value, so if the result is -14, then the actual result is 14.", "Если результат отрицательный, мы сначала получаем абсолютное значение, то-есть если результат равен -14, фактический результат равен 14." }, { "More examples:", "Больше примеров:" }, { "Scans a surface or object, and sends out a ping to nearby employees marking the location.", "Сканирует поверхность или объект и отправляет сигнал ближайшим сотрудникам, отмечая местоположение." }, { "No info about this moon can be found.", "Не удалось найти никакой информации об этой луне." }, { "Please enjoy your flight.", "Пожалуйста, наслаждайтесь полётом." }, { "Danger level: 50%", "(Бессмертная Улитка)\n\nУровень опасности: 50%" }, { "The following is a recitation of the events that transpired on \\[REDACTED\\] to the best of my memory. This is my experience with the entity and I swear to do right by the company and describe it as best I can. There were four of us out on a routine scrap-job, absolutely nothing was out of the ordinary before \\[REDACTED\\] spotted it. We laughed our asses off. Half the things in here will make you soil your hazmat suit on the spot, and then there's this thing, moving at, well you know. We had our fun, but ultimately moved on and forgot about the thing. Me and the boys went our separate ways and decided to rendezvous at the ship. Three of us returned, but \\[REDACTED\\] was missing. We all decided to go back in and investigate. The place was silent. We thought things might have taken a turn for the worse, so we decided to split up and either guide \\[REDACTED\\] back to ship, or at least recover his remains. As often happens, I found myself lost. Turning the corners of this elaborate labyrinth, I finally found what was left of \\[REDACTED\\]. It was unusual, I'd never seen a coworker left in such a state. Reality struck as I turned a corner and found another comrade waiting on the ground for me, and then another. I made the heartbreaking decision to leave my comrades behind. I was almost free, when I find staring at me from the front entrance the same snail I'd seen before. I saw red. I beat that thing as ruthlessly as I could \\(with my shovel\\), entirely imprinting my rage on its presumably fragile shell. I expected to find a small puddle where the snail once stood, but the it was unaffected. It moved towards me at the same agitating pace it did before. The aftermath is a blur. Sometimes I wonder if I even made it back to the ship at all.", "Ниже приводится изложение событий, произошедших на [УДАЛЕНО], насколько я помню. Это мой опыт работы с этим существом, и я клянусь поступать правильно по отношению к компании и оставлять её как можно в лучшем свете. Нас было четверо на обычной работе по поиску лома, и до того, как [УДАЛЕНО] заметил её, не было абсолютно ничего необычного. Мы ржали до упаду. Половина вещей здесь и так заставляет вас испачкать свой защитный костюм, а тут ещё эта штука движется, ну, вы знаете. Мы посмеялись, но в конце концов пошли дальше и забыли об этом. Мы с парнями разошлись и решили встретиться на корабле. Трое из нас вернулись, но [УДАЛЕНО] пропал. Мы все решили вернуться и хорошенько его поискать. Место было тихим. Мы подумали, что ситуация могла измениться к худшему, поэтому мы решили разделиться и либо унести [УДАЛЕНО] обратно на корабль, либо, по крайней мере, забрать его останки. Как обычно это и бывает, я заблудился. Поворачивая углы этого сложного лабиринта, я наконец нашёл то, что осталось от [УДАЛЕНО]. Это было необычно, я никогда не видел, чтобы коллега оставался в таком состоянии. Реальность поразила меня, когда я завернул за угол и обнаружил, что на земле меня ждёт ещё один товарищ, а затем ещё другой. Я принял душераздирающее решение оставить своих товарищей здесь. Я был почти свободен, когда обнаружил, что с главного входа на меня смотрит та самая улитка, которую я видел раньше. Она меня очень разозлила. Я избил эту штуку так безжалостно, как только мог (своей лопатой), полностью отпечатав всю свою ярость на её предположительно хрупкой оболочке. Я ожидал увидеть небольшую лужу на том месте, где была улитка, но она не пострадала. Она двинулся ко мне с той же волнующей скоростью, что и раньше. Последствия — помнятся очень мутно. Иногда я задаюсь вопросом, добрался ли я тогда вообще до корабля." }, { "PREVIEW:", " ПРЕВЬЮ:" }, { "SORT:", "СОРТ:" }, { "FILTER:", "ФИЛЬТР:" }, { "Simulating arrival to (.+?)", "Симуляция прибытия на $1" }, { "Analyzing potential remnants found on surface.", "Анализ обнаруженных на поверхности остатков." }, { "Listing generated probabilities below.", "Ниже приведён список сгенерированных вероятностей." }, { "POSSIBLE STRUCTURES:", "ВОЗМОЖНЫЕ СТРУКТУРЫ:" }, { "Chance: (.+?)", "Шанс: $1" }, { "Facility", "Объект" }, { "Haunted Mansion", "Особняк с привидениями" }, { "To level up your character leave this terminal and get out your handy portable terminal \\(default key X\\).", "Чтобы повысить уровень своего персонажа, покиньте этот терминал и возьмите удобный портативный терминал (клавиша по умолчанию X)." }, { "Sponsored by", "Спонсировано" }, { "Advancing mankind!", "Развиваем человечество!" }, { "AdvancedTech is not responsible for any damages that may occur in connection with items sponsored by AdvancedTech for evaluation purposes. AdvancedTech reserves the right to take legal action against any statements to the contrary.", "AdvancedTech не несёт ответственности за любой ущерб, который может возникнуть в связи с предметами, спонсируемыми AdvancedTech для целей оценки. AdvancedTech оставляет за собой право подать в суд на любые заявления об обратном." }, { "This entity can detect fear.", "(ВУДУ)\n\nЭта сущность может обнаруживать страх." }, { "Upon sensing a lifeform experiencing fear, it will chase it, transmitting its soul to some area close by before the lifeform can act upon the fear; therefore protecting itself from harm.", "Почувствовав, что форма жизни испытывает страх, она будет преследовать её, передавая свою душу в какую-то область поблизости, прежде чем форма жизни сможет воздействовать на страх; таким образом защищая себя от вреда." }, { "The namesake comes from the rumor passed between crewmates that this entity acts as a voodoo doll for something. Better researchers than you have tried and failed to figure out for what.", "Тёзка возникла из слухов, распространившихся среди членов экипажа, о том, что это существо по какой то причине действует как кукла вуду. Лучшие исследователи, чем вы, пытались, но не смогли понять, почему." }, { "Don't try to be a hero.", "Не пытайтесь быть героями." }, { "Sigurd's danger level: 80%", "(Футбол)\n\nУровень опасности по шкале Сигурда: 80%" }, { "Scientific name: Canis Lupus Thea", "Научное название: Canis Lupus Thea" }, { "At first glance, Football exudes an aura of innocence and amiability, her golden fur and playful demeanor reminiscent of a beloved pet. However, beneath this charming facade lies the essence of an untamed wilderness, her eyes betraying secre
BepInEx/plugins/Hayrizan-RTLC_Russian_Translation/RTLC/RTLC.dll
Decompiled 4 days ago
The result has been truncated due to the large size, download it to view full contents!
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.InteropServices; using System.Runtime.Versioning; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using Patchers; using RTLC; using TMPro; using UnityEngine; using UnityEngine.EventSystems; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("RTLC")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RTLC")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("2ddf3c2e-6fb0-41ec-85e1-affd1baa8e5e")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] internal class BundleLoader { public static AssetBundle RTLCBundle; public static bool TryLoadBundle() { try { string text = Path.Combine(Paths.BepInExRootPath, "plugins", "Hayrizan-RTLC_Russian_Translation", "RTLC", "Bundles", "rtlc.main"); string text2 = Path.Combine(Paths.BepInExRootPath, "plugins", "RTLC", "Bundles", "rtlc.main"); if (File.Exists(text)) { RTLCBundle = AssetBundle.LoadFromFile(text); return true; } if (File.Exists(text2)) { RTLCBundle = AssetBundle.LoadFromFile(text2); return true; } return false; } catch (Exception value) { Console.WriteLine(value); return false; } } public static bool TrySetTexture(ref Texture2D originalTexture, string textureName) { try { if (textureName == "") { return false; } Texture2D val = RTLCBundle.LoadAsset<Texture2D>(textureName); if ((Object)(object)val == (Object)null) { return false; } ImageConversion.LoadImage(originalTexture, ImageConversion.EncodeToPNG(val)); ((Texture)originalTexture).mipMapBias = -1f; return true; } catch (Exception value) { Console.WriteLine(value); return false; } } } internal class Dictionaries { public static readonly Dictionary<string, string> Nodes = new Dictionary<string, string> { { "AlreadyOnThisPlanet", "Корабль уже находится на орбите этой луны!\n\n" }, { "AlreadyUnlocked", "Это уже разблокировано для вашего корабля!\n\n" }, { "0_Bestiary", "BESTIARY\n\nДля доступа к файлу существа введите \"INFO\" после его имени.\n---------------------------------\n\n[currentScannedEnemiesList]\n\n" }, { "0_StoreHub", "Добро пожаловать в магазин Компании. \nВведите \"BUY\" или \"INFO\" для любого товара. \nЗакажите инструменты оптом, введя количество.\n____________________________\n\n[buyableItemsList]\n\nУЛУЧШЕНИЯ КОРАБЛЯ:\n* Loud horn // Цена: $100\n* Signal Translator // Цена: $255\n* Teleporter // Цена: $375\n* Inverse Teleporter // Цена: $425\n\nВыбор декора корабля меняется в зависимости от квоты. Обязательно загляните на следующей неделе:\n------------------------------\n[unlockablesSelectionList]\n\n" }, { "CancelPurchase", "Отмена заказа.\n\n" }, { "CancelRoute", "Отмена маршрута.\n\n" }, { "CompanyMoonroute", "Компания скупает за [companyBuyingPercent] от стоимости. \n\nХотите направить автопилот к зданию Компании?\n\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "CompanyMoonRouteConfirm", "Направление автопилота к зданию Компании.\n\nПриятного полёта\n\n" }, { "ConfirmEject", "Вы хотите катапультировать всех членов экипажа, включая себя? Вы должны находиться на орбите вокруг луны.\n\nВНИМАНИЕ!: Данное действие может привести к непредвиденным последствиям. Действуйте с осторожностью.\n\nВведите \"CONFIRM\"(Принять) или \"DENY\"(Отмена).\n\n" }, { "DenyEject", "Катапультирование отменено.\n\n" }, { "EjectPlayers", "Катапультирование экипажа.\n\n" }, { "FlashedRadarBooster", "Произведена вспышка радар-усилителя.\n\n" }, { "HelpCommands", ">MOONS\nУзнать список лун, к которым автопилот может проложить маршрут\n\n>STORE\nФирменный магазин компании.\n\n>BESTIARY\nЗаписи о существах, добавленные в базу.\n\n>STORAGE\nПолучить доступ к объектам, помещенным на склад.\n\n>OTHER\nУвидеть список других команд.\n\n[numberOfItemsOnRoute]\n\n" }, { "ItemsInStorage", "При перемещении объектов с помощью [B] вы можете нажать [X], чтобы отправить их на склад. Здесь вы можете вызвать их обратно.\n\nСписок объектов на складе:\n\n[storedUnlockablesList]\n\n" }, { "ParserError1", "[Команда была предоставлена без указания какого-либо действия.]\n\n" }, { "ParserError2", "[В действии не было объекта, возможно слово было набрано неправильно, или его не существует.]\n\n" }, { "ParserError3", "[Это действие несовместимо с данным объектом.]\n\n" }, { "SendSignalTranslator", "Сообщение транслировано.\n\n" }, { "Start", "Добро пожаловать в FORTUNE-9 ОС\n\tПредоставлено компанией\n\n[currentDayRussian].\n\nВведите \"Help\" для получения списка команд.\n\n" }, { "StartFirstTime", " __ _____ _ ___ ___ __ __ ___ \n \\ \\ / | __| | / __/ _ \\| \\/ | __|\n \\ \\/\\/ /| _|| |_| (_| (_) | |\\/| | _| \n \\_/\\_/ |___|____\\___\\___/|_| |_|___|\n\nДобро пожаловать в FORTUNE-9 ОС\n\tПредоставлено компанией\n\nВведите \"Help\" для получения списка команд.\n\n" }, { "SwitchedCam", "Переключение камеры.\n\n" }, { "SwitchRadarCamPlayer 1", "Переключение камеры.\n\n" }, { "SwitchRadarCamPlayer", "Переключение камеры.\n\n" }, { "ViewInsideShipCam 1", "Переключение камеры\n\n" }, { "WelcomeNode", "BG IG, Системный помощник.\nКопирайт (C) 2084-2108, Halden Electronics Inc.\nПредоставлено компанией.\n\n\n\nБиос для FORTUNE-9 87.7 Система 10 МГц\n\nТекущая дата - Вторник 3-7-2532\nТекущее время - 8:03:32.15\n\nПожалуйста, введите любимое животное: " }, { "WelcomeNode2", "\nПожалуйста, опишите свою роль в команде: " }, { "BaboonHawkFile", "Бабуиновый ястреб (Baboon hawk)\n\nУровень опасности по шкале Сигурда: 75%\n\nНаучное название: Papio - volturius\nБабуиновые ястребы — это приматы из семейства Cercopithecidae. Они горбатые, но в среднем могут вставать на ноги примерно до 2.5 метров. Их головы костлявые, с клювом и длинными рогами, которые они используют как шампуры, чтобы пронзать и питаться добычей. Их рога состоят из кератина, в отличие от костей остальной части черепа, и не содержат нервов или кровеносных сосудов. В результате бабуиновые ястребы часто могут сломать свои рога от приложенной силы, затем полностью восстанавливают их в том же сезоне. Бабунные ястребы частично задолжены своим названием их большим крыльям, которые никогда не смогут поднять их большую массу тела и используются вместо этого для устрашения и защиты от непогоды.\n\nСамый большой отряд бабуиновых ястребов, который когда-либо наблюдали, состоял из 18 особей. Они слабо территориальны, и большая часть их поведения обусловлена запугиванием и демонстрацией. Они могут стать коллекционерами, используя любой броский или красочный предмет, чтобы пометить свою территорию. Как одинокие разведчики, бабуиновые ястребы обычно робки и не нападают, если их не спровоцировать. В больших количествах они могут представлять большую опасность; держаться поближе к другим и создавать впечатление, что вы опасны - лучший способ предотвратить нападение. Они предпочитают мелких млекопитающих, но в случае отчаяния, как известно, могут напасть на животных даже вдвое крупнее себя, например на слепых собак. ОНИ ЗАБРАЛИ М О И ОГУРЦЫ\n\n" }, { "BrackenFile", "Брэкен (Bracken) — Или цветочный человек!\n\nЭто был цветочный человек, по-другому не скажешь! Я хотел найти его тело. Мы были трусами.\n\nНаучное название: Rapax-folium\nИдут дебаты относительно того рода, к которому относится Брэкен. Это двуногий позвоночный с кожей цвета и текстуры красной свеклы. Название было придумано из-за того, что кажется, будто листья выступают из его верхней части позвоночника. Считается, что их целью является запугивание, однако о многих аспектах поведения Брэкена мало известно из-за его уклончивости и низкой популяции.\n\nМы знаем немного из отчетов экологов, которые сталкивались с ним. Это одинокий охотник с высоким интеллектом. Его поведение может показаться равнодушным; он проявляет высокую агрессию даже без провокации, но быстро отступает при столкновении. Однако Брэкены известны своей враждебностью, когда их загоняют в угол или просто долго наблюдают за ними. По этой причине рекомендуется держать его в поле зрения, но не пялиться на него. Ни один экземпляр не был собран мёртвым или живым. Существует теория, что после смерти их тела подвергаются быстрому процессу разложения, уникальному для других крупных животных.\n\n" }, { "BunkerSpiderFile", "Бункерные Пауки (Bunker Spiders)\n\nУровень опасности по шкале Сигурда: 20%\n\nНаучное название: Mutinum-ficedula\nБункерные Пауки рода Theraphosa являются крупнейшими арахнидами, найденными в Тистельной Туманности и вторыми по когда-либо открытым размерам. Считается, что они эволюционировали для охоты на крупных млекопитающих в течение нескольких жалких сотен лет после того, как Корабль совершил своё путешествие вокруг Тистельной Туманности. (Смотрите также: Предположение об Увеличении Видового Разнообразия Вокруг Угасающих Туманностей)\n\nБункерные Пауки производят шёлк и раскладывают его вокруг выбранной зоны гнездования, затем ждут, чтобы кто-то на него наступил. Их можно увидеть, ожидающих на стенах, часто над дверными проемами, где добыча может войти, ничего не подозревая. Если вы обнаружили Паука будучи в \"неподготовленном\" состоянии, он может застыть в качестве защитной реакции. В этом случае лучше оставить его в покое. Если Бункерный Паук реагирует агрессивно, лучше не сражаться обычными инструментами. Они используют свои паутины, чтобы компенсировать своё довольно медленное передвижение, поэтому обратите внимание на окружающую среду. Их паутины можно легко разорвать любым тупым инструментом.\n\nБункерные Пауки могут представлять большую опасность для людей и особенно для городских жителей, не принося особой пользы экосистемам. Приказ уничтожать их при первой возможности был неформально согласован между многими государствами, где встречаются Бункерные Пауки, и сейчас одобрен Международным Обществом Охраны Дикой Природы с 10/6/2497.\n\n" }, { "CircuitBeeFile", "Электропчёлы (Circuit Bees)\n\nУровень опасности по шкале Сигурда: 90%\n\nНаучное название: Crabro-coruscus\nЭлектропчела, также известная как красная пчела, — это социальное летающее насекомое рода Apis, потомок медоносной пчелы. Их внешность легко узнаваема благодаря волосатым красным телам и двум комплектам крыльев. Как и их предки, они известны своим умным социальным поведением, большим размером колонии, строением восковых гнёзд, которые они используют для хранения мёда, а также важной ролью в опылении. В отличие от медоносной пчелы, которая часто выбирает высокие места, такие как деревья, для строительства улья, электропчёлы создают свои ульи на земле.\n\nКрасные пчёлы хорошо защищены. Они покидают улей, чтобы атаковать любое существо, находящееся в пределах нескольких метров, оставляя за собой только королеву и трутней. Это смелое поведение обеспечивается их наиболее характерной особенностью, которая заключается в их электростатическом заряде. Красные пчёлы создают трение в воздухе, а также и друг с другом, находясь в улье. То, что позволяет им создавать такой избыток электрического поля по сравнению с медоносной пчелой, всё еще находится в исследовании, поскольку они генерируют более сильное электрическое поле в состоянии паники или гнева. Эта особенность особенно полезна для них вблизи воды.\n\n\nЛучше держаться на безопасном расстоянии. Если украден улей, рой красных пчёл полетит в наступление, в ходе которого они атакуют любое живое существо. Это разрушительное поведение продлится до тех пор, пока они не обнаружат улей или полностью не истощат себя, что может занять от нескольких часов до нескольких дней. Известно, что они оставляют за собой поля тел мелких грызунов, насекомых и даже некоторых крупных млекопитающих, а в редких случаях могут вызывать пожары. Их сильные преимущества и недостатки для экосистемы широко обсуждается. ПЧЕЛУждаются!! - непокорный Сигурд.\n\n" }, { "CoilHeadFile", "COIL-HEADS - Пружиноголовый\n\nУровень опасности по шкале Сигурда: 80%\n\nНаучное название: Vir colligerus\nVir colligerus, или пружиноголовые, не были широко изучены из-за их чрезвычайной непредсказуемости и опасных свойств. Известно, что они воспламеняются при разделении или деактивации, а также содержат чрезвычайно высокий уровень радиоактивных частиц. Из-за этого и других причин существует вероятность того, что они были созданы как биологическое оружие, однако это не было доказано.\n\nВизуально пружиноголовые представляют собой кровавый манекен с головой, соединенной пружиной. Их определяющей характеристикой поведения является остановка при прямом взгляде. Однако, кажется, что это не является строгим правилом. Когда они сталкиваются с громким или ярким светом, они входят в долгий режим перезагрузки.\nПросто смотрите на них или используйте шумовую гранату! - Сигурд\n\n" }, { "EarthLeviathanFile", "ЗЕМНОЙ ЛЕВИАФАН (Earth Leviathan)\n\nУровень опасности по шкале Сигурда: 2%, потому что они не могут скрыться от камер корабля!!\n\nНаучное название: Hemibdella-gigantis\nПочтительно названный Земной Левиафан, из семьи Писцколиколидов, является одним из самых беспозвоночных, найденных вокруг Тистельной Туманности. Ни один из них ещё не был пойман, поэтому об их биологии известно немного.\n\nПохоже, они ведут себя как хищники. Предполагается, что они могут зарываться под землю на 40 метров, судя по невероятным раскопкам, которые они оставляют после себя. Они способны улавливать даже малейшие вибрации, поэтому не рекомендуется замирать, если они находятся поблизости; это миф. Вместо этого, если вы чувствуете вибрации, бегите со всех ног.\n\n" }, { "EyelessDogFile", "СЛЕПАЯ СОБАКА (EYELESS DOG)\n\nНаучное название: Leo caecus\nКрупное млекопитающее класса Saeptivus. Они социальные, потому охотятся в очень больших стаях. Их также называют \"дышащими львами\" из-за узнаваемого звука и большой пасти. Они являются выносливыми охотниками и пытаются компенсировать своё отсутствие зрения чувствительным слухом. Популярен миф, что они часто ошибочно принимают звуки своего собственного вида за добычу, вступая в борьбу внутри своих стай.\n\nИх поведение уникально среди других стаевых животных своей тенденцией распространяться на большие расстояния. Когда Слепая Собака находит добычу, она рычит, чтобы предупредить других поблизости, которые также поднимут тревогу, иногда вызывая своего рода цепную реакцию. Слепые Собаки могут быть опасными в стае. Тем не менее, характерно, что они неуклюжи, делая предположения о точном местоположении своей добычи, которые часто оказываются неверными.\n\n" }, { "ForestKeeperFile", "ХРАНИТЕЛЬ ЛЕСА (FOREST KEEPER)\n\nУровень опасности по шкале Сигурда: 50%\n\nНаучное название: Satyrid-proceritas\nВерится, что эти гиганты имеют общего предка с rapax-folium, их называют Хранителями Леса из-за биомов, которые они часто заселяют. Их тела украшают метки на передней и задней частях, имитирующие глаза -- этот признак более полезен в их юности, так как они неуклюжиe. Их кожа представляет собой уникальный, плотный материал, который уплотняется еще больше на протяжении их жизни; большие шипы и бугры по всему их телу формируются в результате старения.\n\nГоворят, что Хранители Леса проявляют интересное поведение, схожее с поведением человеческого ребенка возрастом 5-6 лет. Они съедят всё, что им покажется интересным. На самом деле Хранителям Леса не нужно ничего класть в рот, и теоретически их основным источником энергии является процесс, аналогичный фотосинтезу. Тем не менее, это делает их относительно опасными для наблюдения. Они способны видеть объекты на больших расстояниях, поэтому важно не высовываться и использовать укрытия. Они не могут проникать в узкие пространства, и как правило, не разрушительны, поэтому держитесь близко к укрытиям или навесам.\n\n" }, { "HoardingBugFile", "HOARDING BUG - Жук собиратель\n\nУровень опасности по шкале Сигурда: 0%\n\nНаучное название: Linepithema-crassus\nЖуки собиратели (отряд Hymenoptera) - это крупные социальные насекомые. Хотя их часто можно встретить, живущими в одиночестве, было установлено, что они делят свои гнезда с представителями своего вида. Средняя высота их тел составляет примерно 1 метр, их тела округлые. Тонкость их жидкости и крови, а также материал панцирей, способствуют их низкому весу, что делает их способными к полету на мембранных крыльях. Это также делает их тела отчасти прозрачными.\n\nЖуки собиратели получили свое название из-за своей территориальной природы. Как только они выбирают место для своего гнезда, они стремятся украсить его любыми предметами, которые они могут найти, и будут защищать эти предметы как часть гнезда. Жуки собиратели не так опасны в одиночку, как в больших ульях. Тем не менее, если их оставить в покое, жуки собиратели удивительно нейтральны и представляют мало опасности. Мы любим этих глупых и ласковых жуков!! - это была заметка от непокорного Сигурда.\n\n" }, { "HygrodereFile", "ГИДРОДЕР (HYGRODERE)\n\nУровень опасности по шкале Сигурда: 0%, если вы быстрее улитки!\n\nНаучное название: Hygrodere\nЭукариотический организм, классифицированный в пафилетической группе Prostita. С невероятной скоростью размножения, эти мелкие организмы могут умножаться до миллионов. Гидродеры редко расщепляются, вместо этого предпочитая формировать большие вязкие массы, которые могут занимать большие пространства и становиться опасностью, требующей применения крупных инструментов или приманок для перемещения.\n\nГигродеры тянутся к теплу и кислороду, они могут обнаруживать его практически откуда угодно. Почти нет ничего органического, что они не смогли бы преобразовать в собственную массу тела. Ничего не найдено, что могло бы их отравить. Постоянно заменяя себя, они могут существовать сотни тысяч лет. Если вы когда-либо окажетесь в тупике, найдите высокий объект, чтобы встать на него; Гидродерам трудно подниматься. У них отличный вкус! Потому что я как-то подружился с одним из них, и мы думаем, что это благодаря моей музыке.\n\n" }, { "JesterFile", "ДЖЕСТЕР (JESTER)\n\nУровень опасности по шкале Сигурда: 90% Бегите оттуда, пока не стало ПОЗДНО!! Вы не можете спрятаться от него, просто эвакуируйтесь\n\nНаучное название: БЕЗУМНИУС ШТУКУС\nНЕТ ТУТ НИКАКИХ НАУЧНЫХ ЗАПИСЕЙ! Удачи, вы знаете столько же, сколько и мы. Мы просто называем его Джестером.\n\n" }, { "LassoManFile", "ЛАССО (LASSO)\n\nУровень опасности по шкале Сигурда: 30%, но оно меня немного пугает\n\nНаучное название:\n\n" }, { "LocustFile", "Блуждающая саранча (Roaming Locusts)\n\nУровень опасности по шкале Сигурда: 0%\n\nНаучное название: Anacridium-vega\n\nИзвестная как блуждающая саранча, это вид кузнечиков. В отличие от некоторых видов, которые более склонны прыгать или летать, блуждающая саранча практически никогда не приземляется и держится близко друг к другу, даже когда их немного. Они быстро рассеются, если хищник нарушит их личное пространство. Саранчу очень сильно привлекает свет.\n\n" }, { "ManticoilFile", "Мантикоилы (Manticoils)\n\nУровень опасности по шкале Сигурда: 0%\n\nНаучное название: Quadrupes-manta\nМантикоилы - это певчие птицы из семейства Corvidae. Их тела довольно крупные по сравнению с их древними потомками, а размах их крыльев составляет от 140 до 163 сантиметров. Их самой характерной чертой является четыре крыла. Задние крылья в основном используются для стабилизации при низкой скорости, в то время как передние два крыла создают основную поддержку. Их круглые тела поражают своим ярко-жёлтым окрасом, с чёрными контурами или полосами вдоль основных (задних) перьев.\n\nМантикоилы в основном питаются мелкими насекомыми, но также не брезгуют и грызунами. Умны и общительны. Они не представляют большой угрозы и, как правило, имеют обще-пассивное отношение к людям, хотя они могут передавать Бешенство, Рубенхлорию и вирус Питта.\n\n" }, { "NutcrackerFile", "Щелкунчик\n\nОхранники дома.\n\nОни наблюдают одним неустанным глазом, который пристально следит за двигающимися объектами; он помнит последнее существо, которое заметил, независимо от того, двигается оно или нет.\n\n" }, { "PufferFile", "Споровик (Spore lizard)\n\nУровень опасности по шкале Сигурда: я не знаю, наверное, 5%? Я просто ненавижу эту пухлоногую маленькую дрянь\n\nНаучное название: Lacerta-glomerorum\nИменуемые Пухляшами или Споровиками, Lacerta-glomerorum (из семейства аллигаторовых) является одним из самых крупных и тяжёлых рептилий. Несмотря на их крупную пасть, они являются травоядными и не способны сильно укусить. Считается, что луковицы на их хвостах вырабатывают химическое вещество, которое привлекает и ускоряет рост грибного вида Lycoperdon perlatum, который затем они могут трясти, чтобы высвободить споры в качестве защитного механизма - уникальный пример взаимовыгодных симбиотических отношений.\n\nСпоровики обладают очень покладистым нравом и, по возможности, избегают всевозможной конфронтации. Если их попытки угрозы не оказывают эффекта, они могут предпринять попытку нападения, поэтому не рекомендуется загонять их в угол или преследовать. Имеются исторические записи о том, что Споровики были по меньшей мере частично одомашнены сотни лет назад, однако эти усилия были приостановлены в рамках инициативы по сбору их хвостов в медицинских целях.\n\n" }, { "SnarefleaFile", "УДУШАЮЩАЯ МНОГОНОЖКА (SNARE FLEA)\n\nУровень опасности по шкале Сигурда: 30%\n\nНаучное название: Dolus-scolopendra. \nОчень крупное членистоногое из класса Chilopoda. Его тело вырабатывает шёлк, который в основном используется им для передвижения в места, где можно спрятаться. Экзоскелет многоножки довольно хрупок; она может погибнуть при падении с большой высоты. Удушающая многоножка не вырабатывает яд и не обладает сильным укусом. Эту слабость она компенсирует способностью стягиваться вокруг крупной добычи, чтобы задушить её.\n\nУдушающая многоножка процветает в тёплых и тёмных местах. Она не может выжить при низких температурах и вообще избегает открытого воздуха и солнца; вынесите её на улицу или просто избейте! Я думаю, что из их внутренностей вышел бы хороший милкшейк.\n\n" }, { "ThumperFile", "Тамперы (Thumpers)\n\nУровень опасности по шкале Сигурда: 90%\n\nНаучное название: Pistris-saevus\nПоловинчатые, или Тамперы, представляют собой высокоагрессивный, плотоядный вид из отряда Chondrichthyes. Их скелет состоит из хрящевой ткани, придающей их телам упругость и резиновость. Их название произошло от того факта, что им приходится съедать свои задние ноги, чтобы выбраться из скорлупы своего яйца; их задние ноги изначально слабо функциональны. Их руки, или передние ноги, очень крепкие, и время от времени они используют их, чтобы топтать добычу. Они способны развивать высокие скорости на прямой линии.\n\nОни беспощадные охотники, обычно находясь на вершине своей пищевой цепи. Их основные слабости — это их интеллект и полное отсутствие слуха. Если вы столкнулись с Тампером, лучший способ выживания — оставить его поле зрения, так как он медленннно поворачивается и не может легко преследовать добычу.\n\nИз-за быстрой и нестабильной эволюции этого вида, некоторые теоретики считают, что Тамперы – это один из примеров увеличенного количества мутаций, вызывающих более высокие уровни видообразования на планетах вокруг Тистельной Туманности.\n\n" }, { "ButlerFile", "ДВОРЕЦКИЙ\n\nУровень опасности по шкале Сигурда: 70%\n\nПо поводу этого типа файла нет, поэтому я СДЕЛАЮ его сам. мы постоянно находим этих вонючих уродов в объектах, они не хотят с нами разговаривать, даже не обращают на нас внимания и выглядят как сдутые воздушные шары. запах гнилого мяса, настолько неприятный, что у Ричарда от него начинаются рвотные позывы. я слышу, как мухи жужжат внутри их тел. Джесс сказала, что видела, как что-то вылезло из его глазницы и вернулось обратно. \n\nЯ не знаю, что делать с этим человеком\n\nони просто ходят и подметают пол, думаю, поэтому в особняке так чисто. По крайней мере, они выполняют свою работу. Но клянусь, эти вонючие уроды смотрят на меня, когда я отвёрнут от них.\n\nобновление: Они преследовали Рича с ножом. мы этого не видели, но он говорит, что когда он вошёл в комнату, дворецкий просто достал метлу и начал подметать, как ни в чём не бывало. Так что с этого момента мы все держимся вместе. К чёрту этих дворецких! Теперь мне нужно держаться ближе к Ричу, а он, наверняка, обоссался в свой костюм от страха\n\n" }, { "TulipSnakeFile", "Тюльпановые змеи\n\nУровень опасности по шкале Сигурда: 1%\n\nНаучное название: Draco tulipa\nТюльпановые змеи, или тюльпановые ящерицы, представляют собой тип летающих ящериц, которых легко отличить по длинным рукам и крыльям, которые могут достигать вдвое больше других представителей своего рода (Драко) и имеют необычно яркие цвета и узоры. Их название происходит от клапанов под шеей и за головой, которые напоминают большие лепестки цветов. (К другим их необычным характеристикам относятся дополнительная пара глаз и глубоко раздвоенный хвост.)\n\nИх поведение упрямо и бесстрашно. Действительно, тюльпановые змеи редко убегают от хищника. Но по иронии судьбы многие биологи предполагают, что их цветочный внешний вид помогает им скорее в качестве камуфляжа, чем для демонстрации устрашения. Он также играет важную роль в их тщательно продуманных ритуалах ухаживания, которые больше похожи на ритуалы ухаживания птиц. \n\nПримечательно, что подъём тяжелых и больших предметов в воздух часто наблюдался как часть брачного процесса тюльпановой змеи; они способны нести камни и растения как минимум в два раза больше своего размера, чтобы произвести впечатление на своего потенциального партнёра. Защищающие, ревнивые и впадающие в ярость самцы могут в конечном итоге вступить в перетягивание каната из-за предметов, которые им нравятся, включая даже других живых существ.\n\n" }, { "RadMechFile", "СТАРИННЫЕ ПТИЦЫ\n\n \"Старинная птица\" — автономное наступательное оружие войны гуманоидной конструкции. При росте 5,7м. и ширине 3,3м. две его наиболее характерные визуальные особенности — это прожектор, расположенный на его голове, способный излучать 100 000 люмен, и акустическое устройство дальнего действия на его груди, иногда называемое звуковой пушкой. На его плечах расположены дополнительные динамики, используемые для трансляции звука на большое расстояние. Левая рука Старинной птицы представляет собой коготь, а правая — сопло, способное как запускать реактивные гранаты, так и поджигать на близком расстоянии очень горячим пламенем. Старинная птица — одно из первых вне орбитальных вооружений, которые будут использоваться и производиться серийно.\r\n Тема о том, кто разработал Старинную птицу, вызвала интенсивные споры с момента их первого появления на канале\n\nКонструкция Старинной птицы, вплоть до закалки металлов, по-видимому, призвана скрыть её происхождение. Его назвали \"ходячим письмом с требованием выкупа.\" \r\n Ноги Старинных птиц функционируют как ракеты, что позволяет им преодолевать большие расстояния и эффективно находить цели. Но наиболее вероятная причина существования этой функции — помочь им войти и приземлиться с орбиты. Материалы и топливо, на которые полагаются Старинные птицы, аналогичны материалам и топливу пассажирских космических кораблей примерно из 2130 года.\r\nСтаринные птицы приземляются и навсегда остаются на своей целевой планете. Хотя топлива у них зачастую более чем достаточно только на одну поездку, в их программах не обнаружено никакого поведения, которое бы предполагало, что они могут выбрать \"миграцию\". Тем не менее, существуют непроверенные сведения о том, что Старинные птицы самостоятельно путешествовали на новую планету после сотен лет покоя. \r\nСтаринную птицу исторически называли \"Ал\", исходя из кодового названия, присвоенного ей английскими военными, \"A16-L31\". Однако в 2384 году пост-панк-проект Under Remora выпустил песню \"Старинные Птицы\" как культовый хит; всего три года спустя, в своём самом известном одноименном произведении,уличный художник Лэнд Эйри изобразил автоматонов, прилетающих и приземляющихся между планетами с расположением, похожим на стаю гусей - это обычно считается одним из самых знаковых и влиятельных образов современной культуры и укрепило современное прозвище.\r\n В 2356 году, луна 5-Embrion была классифицирована как Отверженная для целей путешествия или поселения на Лодке; По словам очевидцев, Старинные птицы \"выстилают горизонт\". Хотя по сей день они кажутся неработоспособными, существует разумный риск того, что многие из них все еще находятся в спящем режиме, поэтому планета, скорее всего, сохранит свой статус. Маленькая луна, вероятно, использовалась в качестве испытательного полигона для лётных и приземляющихся возможностей Старинной птицы.\n\n" }, { "AutopickerInfo", "Отмычка раскроет ваш безграничный потенциал эффективности в работе. Благодаря запатентованному программному обеспечению с искусственным интеллектом, она откроет вам доступ к любой запертой двери.\n\n" }, { "BBbulbInfo", "Самый доступный источник света. Он ещё и водонепроницаемый!\n\n" }, { "BoomboxInfo", "Музыка отлично поднимет боевой дух вашего экипажа!\n\n" }, { "ExtensionLadderInfo", "Выдвижная лестница может подниматься на высоту до девяти метров! С её помощью можно преодолеть любой обрыв и дотянуться до звёзд! Для экономии энергии в батарейках, автоматически сдвигается обратно через 18 секунд\n\n" }, { "FlashlightInfo", "Благодаря увеличенному времени автономной работы и ещё более яркой лампе, ваши коллеги никогда больше не оставят вас в темноте!\n\n" }, { "JetpackInfo", "Это устройство доставит вас куда угодно! Только используйте его ответственно!\n\n" }, { "MapperInfo", "Совершенное картографическое устройство, использующее функцию обнаружения света и дальности, чтобы предоставить вам обзор местности над головой.\n\n" }, { "RadarInfo", "Радар-усилители имеют много применений! \n\nВведите команду \"SWITCH\" перед именем радар-усилителя, чтобы просмотреть его на основном мониторе. Он должен быть активирован.\n\nВведите команду \"PING\" перед именем радар-усилителя, чтобы воспроизвести с него специальный звук.\n\n" }, { "ShovelInfo", "Для самозащиты!\n\n" }, { "SignalTranslatorInfo", "Транслятор сигналов\n\nВведите команду \"transmit\", для передачи текстового сообщения всем членам экипажа. Сообщение не должно превышать 10 букв.\n\n" }, { "SurvivalKitInfo", "Набор для выживания включает в себя всё, что необходимо в удобной упаковке! :\n\n* Фонарик x4 \n* Рация x4\n* Лопата x2\n\n" }, { "TZPChemicalInfo", "Этот безопасный и законный препарат может быть принят для получения значительных преимуществ в вашей работоспособности! Ваша способность перемещаться на БОЛЬШИЕ расстояния, несмотря на ТЯЖЁЛЫЕ объекты, будет непревзойденной! Предупреждение: ТЗП-Ингалятор может воздействовать на мозг при длительном воздействии. Следуйте инструкциям, предоставленным в руководстве по использованию баллона \nНе забудьте поделиться!\n\n" }, { "WalkieTalkieInfo", "Полезно для поддержания связи! Слышно других игроков, когда рация в вашем инвентаре. Для передачи голоса нужно держать в руке и удерживать кнопку.\n\n" }, { "ZapGunInfo", "Самое специализированное средство самозащиты, способное посылать до 80 000 вольт! \n\nЧтобы как можно дольше держать кого-либо на прицеле, тяните пистолет из стороны в сторону, чтобы противостоять изгибу и бороться с притяжением электрического луча. Электрошокер может оглушать только до тех пор, пока в нём есть заряд.\n\n" }, { "LoudHornInfo", "Громкий гудок\n\nИспользуется для связи с любым членом экипажа на любом расстоянии, рация не требуется! Гудение слышно откуда угодно. Но что это значит? Это зависит от вас!\n\n" }, { "RadarBoosterInfo", "Радары-усилители имеют множество применений!\n\nИспользуйте команду \"SWITCH\" перед названием радар-усилителя, чтобы начать наблюдение за ним на главном мониторе. Он должен быть активен.\n\nИспользуйте команду \"PING\" перед названием радар-усилителя, чтобы устройство проиграло специальный звук.\n\n" }, { "TeleporterInfo", "Телепортер\n\nНажмите кнопку, чтобы активировать телепортер. Он телепортирует любого, за кем в данный момент ведётся наблюдение на главном мониторе корабля. Тот, кого телепортируют, не сможет сохранить ни один из своих предметов. Перезарядка занимает около десяти секунд.\n\n" }, { "InverseTeleporterInfo", "\nОбратный телепортер — это модифицированный телепорт, который телепортирует вас в случайное место за пределами корабля. Все ваши предметы будут выброшены перед транспортировкой. Обратный телепортер может использоваться всеми сотрудниками одновременно, его время восстановления составляет 3,5 минуты.\n\nОТКАЗ ОТ ОТВЕТСТВЕННОСТИ: Обратный телепортер может переносить вас только наружу, а не внутрь, и вы можете оказаться в ловушке. Компания не несёт ответственности за травмы или замену голов и конечностей, вызванные квантовой запутанностью или невезением.\n\n" }, { "AssInfo", "220-Assurance\n----------------------\n\nУСЛОВИЯ: Похожа на её луну-близняшку, 41-Experimentation, но с более неровным и высушенным рельефом. \n\nИСТОРИЯ: 220-Assurance гораздо моложе своей коллеги. Обнаружена незадолго до 41-Experimentation.\n\nФАУНА: Неизвестно\n\n" }, { "DineInfo", "7-Dine\n----------------------\n\nУСЛОВИЯ: Эта луна является орбитой белой карликовой звезды, делая её необитаемой. Холодные условия. Постоянные вьюги понижают видимость.\n\nИСТОРИЯ: Несколько известных путешественников пропали здесь без вести, придавая луне опредёленную репутацию. Их тела вряд ли найдут, учитывая погодные условия луны.\n\nФАУНА: Очень низкий шанс существования сложной жизни.\n\n" }, { "ExpInfo", "41-Experimentation\n----------------------\n\nУСЛОВИЯ: Засушливость. Низкая обитаемость, ухудшенная промышленными отходами.\n\nИСТОРИЯ: Не была открыта в течение некоторого времени из-за того, что была близка к орбите газового гиганта Big Grin. Однако, похоже, что эту луну секретно использовали.\n\nФАУНА: Неизвестно\n\n" }, { "MarchInfo", "61-March\n----------------------\n\nУСЛОВИЯ: На луне March проходят постоянные дожди. Её рельеф является более экспансивным.\n\nИСТОРИЯ: Эта луна часто упускается из виду из-за её близняшки, Vow. \n\nФАУНА: Неизвестно\n\n" }, { "OffenseInfo", "21-Offense\n----------------------\n\nУСЛОВИЯ: Считается, что эта луна откололась от своей сестры Assurance. Особенности Offense схожи, неровный ландшафт и сухие условия, но отличия кроются в её экосистеме.\n\nИСТОРИЯ: 21-Offense категоризирована как луна-астероид, и кажется, что не существовала сама по себе уже более нескольких сотен лет. Промышленные постройки здесь сильно пострадали; считается что они были построены задолго до того, как 21-Offense откололась.\n\nФАУНА: Конкурентная и закалённая экосистема, поддерживающая агрессивные формы жизни. Путешественники, отправляющиеся на 21-Offense, должны знать, что эта луна не для слабонервных.\n\n" }, { "RendInfo", "85-Rend\n----------------------\n\nУСЛОВИЯ: Эта луна является орбитой белой карликовой звезды, делая её необитаемой. Холодные условия. Постоянные вьюги понижают видимость. \n\nИСТОРИЯ: Несколько известных путешественников пропали здесь без вести, придавая планете опредёленную репутацию. Их тела вряд ли найдут, учитывая погодные условия луны. \n\nФАУНА: Очень низкий шанс существования сложной жизни.\n\n" }, { "TitanInfo", "8-Titan\n----------------------\n\nУСЛОВИЯ: Замёрзший, плоский ландшафт.\n\nИСТОРИЯ: Кажется, что на этой луне добывали ресурсы. Очень просто потеряться среди гигантского промышленного комплекса. Существует много входов в него, которые разбросаны по ландшафту.\n\nФАУНА: Опасные существа, по слухам, проживающие в огромной системе туннелей.\n\n" }, { "VowInfo", "56-Vow\n----------------------\n\nУСЛОВИЯ: Влажные.\n\nИСТОРИЯ: Кажется, что Vow была заселена несколькими колониями в течение её континента, но на данный момент нет никаких признаков жизни, поэтому они стали загадкой.\n\nФАУНА: Разнообразна, кишит растительной жизнью.\n\n" }, { "AdamanceInfo", "20-Adamance\n----------------------\n\nУСЛОВИЯ: Эрозия и географические силы довели луну до образования глубоких долин и гор.\n\nИСТОРИЯ: Adamance - самая большая и старейшая из тех, кого в просторечии называют \"Зелёными Ведьмами\": Луны Vow, March и Adamance, которые вращаются вокруг Не Обслуживается.\n\nФАУНА: Луна \"Adamance\" является домом для живой и разнообразной экосистемы мелких всеядных животных.\n\n" }, { "ArtificeInfo", "68-Artifice\n----------------------\n\nУСЛОВИЯ: Заброшенные объекты разбросаны по территории, которая когда-то кипела жизнью. \n\nИСТОРИЯ: Оружие и секретные технологии были найдены в различных местах на поверхности этой луны; дата изготовления не менее двухсот лет.\n\nФАУНА: Ходят слухи, что действующая техника осталась позади.\n\n" }, { "EmbrionInfo", "5-Embrion\n----------------------\n\nУСЛОВИЯ: Пустынная и плоская, с непригодным для дыхания воздухом, поверхностный слой луны Embrion почти полностью состоит из аметистового кварца, что стало возможным благодаря расстоянию луны Embrion до ближайшей звезды и связанной с этим геотермальной активности. Поверхность луны Embrion очень горячая.\n\nИСТОРИЯ: Луна Embrion была открыта всего в прошлом веке. Судя по всему, она использовалась в качестве испытательного полигона для \"Старых Птиц\" задолго до того, как была официально обнаружена. В результате этой опасности ей был присвоен статус \"Забракована\". Существуют теории, что разнообразная геотермальная экосистема может процветать в обширной сети пещер под поверхностью этой луны.\n\nФАУНА: Луна Embrion лишена биологической жизни.\n\n" }, { "buyBoombox", "Вы запросили: Бумбокс. Количество: [variableAmount]. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "buyBoombox2", "Вы заказали: Бумбокс х[variableAmount]. Оставшиеся кредиты: [playerCredits].\n\nНаши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения.\n\n" }, { "buyExtensLadder", "Вы запросили: Выдвижная лестница. Количество: [variableAmount]. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "buyExtensLadder2", "Вы заказали: Выдвижная лестница х[variableAmount]. Оставшиеся кредиты: [playerCredits].\n\nНаши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения.\n\n" }, { "buyFlash", "Вы запросили: Фонарик. Количество: [variableAmount]. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "buyFlash2", "Вы заказали: Фонарик х[variableAmount]. Оставшиеся кредиты: [playerCredits].\n\nНаши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения.\n\n" }, { "buyJetpack", "Вы запросили: Реактивный ранец. Количество: [variableAmount]. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "buyJetpack2", "Вы заказали: Реактивный ранец х[variableAmount]. Оставшиеся кредиты: [playerCredits].\n\nНаши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения.\n\n" }, { "buyLockpickers", "Вы запросили: Отмычка. Количество: [variableAmount]. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "buyLockpickers2", "Вы заказали: Отмычка х[variableAmount]. Оставшиеся кредиты: [playerCredits].\n\nНаши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения.\n\n" }, { "buyMapper", "Вы запросили: Картограф. Количество: [variableAmount]. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "buyMapper2", "Вы заказали: Картограф х[variableAmount]. Оставшиеся кредиты: [playerCredits].\n\nНаши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения.\n\n" }, { "buyProFlashlight1", "Вы запросили: PRO-фонарик. Количество: [variableAmount]. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "buyProFlashlight2", "Вы заказали: PRO-фонарик х[variableAmount]. Оставшиеся кредиты: [playerCredits].\n\nНаши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения.\n\n" }, { "buyRadarBooster", "Вы запросили: Радар-усилитель. Количество: [variableAmount]. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "buyRadarBooster2", "Вы заказали: Радар-усилитель х[variableAmount]. Оставшиеся кредиты: [playerCredits].\n\nНаши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения.\n\n" }, { "buyShovel", "Вы запросили: Лопата. Количество: [variableAmount]. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "buyShovel2", "Вы заказали: Лопата х[variableAmount]. Оставшиеся кредиты: [playerCredits].\n\nНаши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения.\n\n" }, { "buySpraypaint", "Вы запросили: Баллончик с краской. Количество: [variableAmount].\nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "buySpraypaint2", "Вы заказали: Баллончик с краской х[variableAmount]. Оставшиеся кредиты: [playerCredits].\n\nНаши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения.\n\n" }, { "buyStunGrenade", "Вы запросили: Шумовая граната. Количество: [variableAmount]. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "buyStunGrenade2", "Вы заказали: Шумовая граната х[variableAmount]. Оставшиеся кредиты: [playerCredits].\n\nНаши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения.\n\n" }, { "buySurvivalKit", "Вы запросили: Набор для выживания:\n* Фонарик х4\n* Рация x4\n* Лопата х1\n\nКоличество: [variableAmount]. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "buySurvivalKit2", "Вы заказали: Набор для выживания х[variableAmount]. Оставшиеся кредиты: [playerCredits].\n\nНаши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения.\n\n" }, { "buyTZP", "Вы запросили: ТЗП-ингалятор. Количество: [variableAmount]. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "buyTZP2", "Вы заказали: ТЗП-ингалятор х[variableAmount]. Оставшиеся кредиты: [playerCredits].\n\nНаши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения.\n\n" }, { "buyWalkieTalkie", "Вы запросили: Рация. Количество: [variableAmount]. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "buyWalkieTalkie2", "Вы заказали: Рация х[variableAmount]. Оставшиеся кредиты: [playerCredits].\n\nНаши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения.\n\n" }, { "buyZapGun", "Вы запросили: Электрошокер. Количество: [variableAmount]. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "buyZapGun2", "Вы заказали: Электрошокер х[variableAmount]. Оставшиеся кредиты: [playerCredits].\n\nНаши сотрудники пользуются быстрой и бесплатной доставкой во время работы! Все приобретённые товары будут доставлены в течение часа до вашего приблизительного местоположения.\n\n" }, { "FishBowlBuy", "Вы запросили: Золотая рыбка, аквариум в подарок.\nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "FishBowlBuyConfirm", "Вы заказали: Золотая рыбка! Оставшиеся кредиты [playerCredits].\nЗажмите [B], чтобы переставить рыбку на корабле, и [V] для подтверждения.\n\n" }, { "PlushiePajamaManBuy", "Вы запросили: Плюшевая игрушка.\nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "PlushiePajamaManBuyConfirm", "Вы заказали: Плюшевая игрушка! Оставшиеся кредиты [playerCredits].\nЗажмите [B], чтобы переставить игрушку на корабле, и [V] для подтверждения.\n\n" }, { "SignalTranslatorBuy", "Вы запросили улучшение корабля: Транслятор сигналов.\nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "SignalTranslatorBuyConfirm", "Вы заказали улучшение корабля: Транслятор сигналов! Оставшиеся кредиты [playerCredits].\nЗажмите [B], чтобы переставить транслятор на корабле, и [V] для подтверждения.\n\nТранслятор сигналов можно активировать командой \"transmit\", за которой следует любое сообщение длиной до 10 символов.\n\n" }, { "LoudHornBuy1", "Вы запросили улучшение корабля: Громкий гудок.\nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "LoudHornBuyConfirm", "Вы заказали улучшение корабля: Громкий гудок! Оставшиеся кредиты [playerCredits].\nЗажмите [B], чтобы переставить стойку с шнуром, и [V] для подтверждения.\n\nТяните за шнур, чтобы активировать громкий звуковой сигнал.\n\n" }, { "TeleporterBuy1", "Вы запросили улучшение корабля: Телепортер.\nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "TeleporterBuyConfirm", "Вы заказали улучшение корабля: Телепортер! Оставшиеся кредиты [playerCredits].\nНажмите кнопку, чтобы активировать телепортер. Он телепортирует любого, за кем в данный момент ведётся наблюдение на главном мониторе корабля. Тот, кого телепортируют, не сможет сохранить ни один из своих предметов. Перезарядка занимает около десяти секунд.\n\nЗажмите [B], чтобы переставить телепортер на корабле, и [V] для подтверждения.\n\n" }, { "InverseTeleporterBuy", "Вы запросили улучшение корабля: Обратный телепортер.\nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "InverseTeleporterBuyConfirm", "Вы заказали улучшение корабля: Обратный телепортер! Оставшиеся кредиты [playerCredits].\nЗажмите [B], чтобы переставить обратный телепортер на корабле, и [V] для подтверждения.\n\nНажмите кнопку и встаньте внутрь обратного телепортера, пока он начинает активацию.\n\n" }, { "WelcomeMatBuy", "Вы запросили: Входной коврик, благодаря которому каждый может почувствовать себя как дома.\nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "WelcomeMatBuyConfirm", "Вы заказали: Входной коврик! Оставшиеся кредиты [playerCredits].\nЗажмите [B], чтобы переложить коврик на корабле, и [V] для подтверждения.\n\n" }, { "CozyLightsBuy1", "Вы запросили: Гирлянду. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "CozyLightsBuyConfirm", "Вы заказали: Гирлянду! Оставшиеся кредиты [playerCredits].\nВыключите свет на корабле чтобы гирлянда заработала.\n\n" }, { "GreenSuitBuy1", "Вы запросили: Зелёные костюмы. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "GreenSuitBuyConfirm", "Вы заказали: Зелёные костюмы! Оставшиеся кредиты [playerCredits].\n\n" }, { "HazardSuitBuy1", "Вы запросили: Защитные костюмы. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "HazardSuitBuyConfirm", "Вы заказали: Защитные костюмы! Оставшиеся кредиты [playerCredits].\n\n" }, { "PajamaSuitBuy1", "Вы запросили: Пижамные костюмы. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "PajamaSuitBuyConfirm", "Вы заказали: Пижамные костюмы! Оставшиеся кредиты [playerCredits].\n\n" }, { "JackOLanternBuy", "Вы запросили: Хэллоуинскую тыкву. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "JackOLanternBuyConfirm", "Вы заказали: Хэллоуинскую тыкву! Оставшиеся кредиты [playerCredits].\nЗажмите [B], чтобы переставить тыкву на корабле, и [V] для подтверждения.\n\n" }, { "TelevisionBuy1", "Вы запросили: Телевизор. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "TelevisionBuyConfirm", "Вы заказали: Телевизор! Оставшиеся кредиты [playerCredits].\nЗажмите [B], чтобы переставить телевизор на корабле, и [V] для подтверждения.\n\n" }, { "RecordPlayerBuy", "Вы запросили: Граммофон. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "RecordPlayerBuyConfirm", "Вы заказали: Граммофон! Оставшиеся кредиты [playerCredits].\nЗажмите [B], чтобы переставить граммофон на корабле, и [V] для подтверждения.\n\n" }, { "RomTableBuy1", "Вы запросили: Романтический стол. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "RomTableBuyConfirm", "Вы заказали: Романтический стол! Оставшиеся кредиты [playerCredits].\nЗажмите [B], чтобы переставить романтический стол на корабле, и [V] для подтверждения.\n\n" }, { "ShowerBuy1", "Вы запросили: Душевую кабину. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "ShowerBuyConfirm", "Вы заказали: Душевую кабину! Оставшиеся кредиты [playerCredits].\nЗажмите [B], чтобы переставить душ на корабле, и [V] для подтверждения.\n\n" }, { "TableBuy1", "Вы запросили: Стол. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "TableBuyConfirm", "Вы заказали: Стол! Оставшиеся кредиты [playerCredits].\nЗажмите [B], чтобы переставить стол на корабле, и [V] для подтверждения.\n\n" }, { "ToiletBuy1", "Вы запросили: Унитаз. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "ToiletBuyConfirm", "Вы заказали: Унитаз! Оставшиеся кредиты [playerCredits].\nЗажмите [B], чтобы переставить унитаз на корабле, и [V] для подтверждения.\n\n" }, { "BunnySuitBuy", "Вы запросили: Костюмы кролика. \nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "BunnySuitBuyConfirm", "Вы заказали: Костюмы кролика! Оставшиеся кредиты [playerCredits].\n\n" }, { "DiscoBallBuy", "Вы запросили: Диско шар.\nСтоимость: [totalCost].\n\nВведите \"CONFIRM\" или \"DENY\".\n\n" }, { "DiscoBallBuyConfirm", "Вы заказали: Диско шар! Оставшиеся кредиты [playerCredits].\nИспользуйте выключатель света, чтобы начать дискотеку.\n" }, { "LogFile1", "Дата: 22 августа 1968 года\nЗдравствуйте. Я пишу этот журнал, чтобы не сойти с ума. До сих пор я просто добавлял в бестиарий всё, что знал. Мой брат сказал, что я должен вести дневник, так что я делаю то, что могу! Я пишу профессионально, так как эти записи могут стать исторической справкой, и они, вероятно, будут храниться здесь годами, пока не произойдет чистка. Так сказал Десмонд.\n\nЕсли вы читаете это в будущем, вы, вероятно, из другой команды. Текучесть кадров здесь огромная, может быть, потому, что эта работа - отстой, и каждый переворачивается замертво! Может быть, я смогу помочь, когда у меня будет опыт. Конец журнала.\nАх да, наши имена: Сигурд (я), Ричард, Десмонд и Джесс. \n\n" }, { "LogFile2", "О боже, этот костюм давит на меня, словно я проклятая мумия! Я взрослый мужчина, дайте ему немного пространства между ног! Это меня убивает, я просто умираю! Надеюсь, ты счастлив, папа, Я НАКОНЕЦ-ТО нашел работу. К чёрту тебя! Здесь всё воняет. Особенно Рич. Я собираюсь бросить его в озеро, и мне без разницы из чего оно там состоит. Мне нравится дежурить на камерах. Ох\nя забыл дату - 24 августа 1968 года. Эта клавиатура может выфвошдафыйе..а/п;\n\n\nСегодня мы нашли пару сковородок и большой болт. Почти ничего не стоит. Для чего компания вообще их использует.\n\n" }, { "LogFile3", "последние несколько дней мы попали в \"качели событий\". Вот что постоянно говорит Рич: от него пахнет прогорклой банкой тунца. Худший летний лагерь, в котором я когда-либо был. Дата - 27 августа 1968 года. \r\nмы следим за тем, чтобы у кого-то всегда была лопата, чтобы бить всё, что движется, и всегда поручаем кому-то \"дежурить камерой\", чтобы он мог открыть эти большие защитные двери с буквами и цифрами. Cпроси волшебника Десмонда, как это работает, я думаю, он просто вводит код, который указан на двери\r. Вот и всё\n\r\nсегодня мы продали компании некоторые товары по ставке 70%. У меня нервы похолодели, слушая чёртовы ПСИХОТИЧЕСКИЕ звуки за стойкой. Только у меня так. ?? \r\nНе могу это игнорировать! Мой фонарик даже не просвечивает туда, луч просто погас.\n\n" }, { "LogFile4", "Дата - 31 августа 1968 года. Я снова дежурю у камеры, ненавижу ходить на этой луне. Ахах, шучу над ними, только что начался дождь!!! Я просто сижу. Не могу спать на этих крошечных кроватях для муравьёв. \n\n\nЭта работа подозрительная. Если вы читаете это, то, скорее всего, попали сюда так же, как и я. Зарплата хорошая, контракт рассчитан только на сезон. Они прогнали вас через свой \"оценочный экзамен\" по телефону со странным голосом. Вы подписали контракт на шаттле вместе с остальными членами вашей команды. Но всё это время вы ни с кем не разговаривали. Шаттл был на автопилоте и, я думаю, что голос в телефоне был фальшивым. Мне снятся странные сны, я думаю, что просто хочу вернуться домой. Но я не собираюсь ползти домой, плача и царапая входную дверь отца. Это не его сын. Это не Сигурд!\n\n" }, { "LogFile5", "Сегодня утром меня разбудили рано, потому что мы собирались в здание компании, чтобы продать наш бесполезный мусор. Ставка составила 120%, что, по словам Десмонда, редкость, и он не хотел пропустить это, он следил за этим, как за дурацкими акциями. \n\nЗдесь по-прежнему паршиво. Рич продолжает пахнуть, как кусок дерьма. Я едва могу уснуть. Я услышал ужасный звук за стеной здания компании. Он звучал так, словно плачущие красные лица были размазаны по бетону, как ступа и пестик, в которых моя мама измельчает семена и специи. Этот кошмар не покидает меня. Никто другой не слышал этого. Они не знают, что делать. Джесс думает, что меня \"тошнит от дома\". Нет, меня тошнит от этого дешёвого костюма.\r\nДата: 4 сентября 1968 года\n\n" }, { "LogFile6", "Мы оставили Рича. Нам нужно было проверить только одну комнату, а потом мы могли бы закончить на сегодня. Я не смог открыть дверь. А потом я посмотрел, и Рича там не было. Это был грёбаный человек с морщинистой кожей и цветочной головой, который ходит на двух ногах! Это существо свернуло ему шею. Я услышал треск, но его там не было. Я хотел найти Рича, даже если бы он был мёртв, но они трусы! Их лица пусты, как у идиотов, в их тупых черепах ничего не двигается. Все, что они хотели сделать, это уйти. Они собирались бросить и меня тоже. Мы все ненавидели Рича, но мы не хотели этого. Это того не стоит, оно просто того не стоит. У нас есть пара ножниц, коробка с марками и связка шнуров, которые мы продаем за бесценок. Дело не в этом, зачем это вообще нужно компании?\n\n\nДата, когда мы последний раз видели Рича: 7 сентября 1968 года.\n\n" }, { "LogFile7", "Дата: 13 сентября 1968 года\n\nПо какой-то причине именно мне пришлось позвонить на номер компании, чтобы сообщить о происшествии. Они были слишком напуганы, чтобы сделать это. Голос был тот же, что я запомнил с телефонного собеседования дома и глупых обучающих видео. Но он услышал, что я сказал, я думаю, потому что он сказал, что они свяжутся с семьей и найдут замену, и что-то в этом роде. Он говорил так быстро\n\n\nЯ узнал, что крики можно постоянно слышать по рации, когда находишься у стены здания Компании. Они мне не поверили. Ну, теперь верят. Это звучит точно так же, как когда я слышал это пару недель назад. Они хотят уволиться. Я сказал, что я не трус. Я только что получил эту работу\n\n" }, { "LogFile8", "Я разговаривал с голосом по рации, это было как часть криков. Он сказал мне, что Золотая планета действительно существует, это не легенда. И он сказал мне, что это было не просто столкновение с метеоритом. Он сказал, что планета была поглощена \"зверем\", и они находились внутри его тела, подвергаясь перевариванию. Я спросил, что это за зверь, и он сказал, что не знает! Он сказал, что зверь съел планету, и они забыли всё.\n\nЯ не мог заставить его перестать говорить. Но я сказал ему, что он на другой стороне большой стены, и я могу его вытащить. Я сказал, что он внутри здания. И вот тогда он начал паниковать. Я не мог разобрать ни слова, но, кажется, он сказал что-то о \"выплёвывании кожуры\". Так что я просто выключил его. Какая дикая история.\n\nДжесс говорит, что Золотая планета - всего лишь рассказ. Я сказал, Я ЗНАЮ, я не идиот. Ну, она сказала, что мне следует прекратить, и она прекратит, если я прекращу. ну она и успокоилась\n\n" }, { "LogFile9", "Дата - 18 сентября 1968 года\nВ прошлые выходные казалось, что Десмонд и Джесс пришли в себя. Через несколько дней к нам присоеденится четвёртый член команды. Мы больше не рискуем, хотя и получаем меньше, но это кажется безопаснее, и я лучше сплю. Но это всё равно грустно. Я всё ещё чувствую запах Рича, клянусь, он так вонял.\n\nЯ говорил о том, как голос по телефону звучал поддельно. Тогда Десмонд придумал эту странную идею. Он - волшебник и всё такое, поэтому он думает, что есть способ использовать звонок, который я сделал на номер компании, чтобы выяснить, откуда идёт этот голос. Не знаю, почему ему это нужно, но он кажется серьезным. Он много времени проводит за терминалом.\n\n" }, { "LogFile10", "27 сентября 1968 года\n\nДесмонд хочет, чтобы я записал, что мы выяснили, и держал свой \"бред на минимуме\". Так что я собираюсь добавить очень много своего бреда. На него плевать. Новый член экипажа по имени Лукас такой сбитый и испуганный всё время, что за младенец, ну хоть не воняет как монстр.\n\nБыло так солнечно, хотя сейчас сентябрь, и эти костюмы не очень хорошо переносят это. Итак, Десмонд \"проследил звонок\" и выяснил, что есть группа людей где-то ещё, которая притворяется, будто звонит нам из здания компании. Они на другом конце солнечной системы!! Почему они так далеко?\n\nДесмонд говорит, что не знает, но я думаю. А вдруг в здании компании действительно есть большой монстр, как голос сказал мне по рации? Они его заперли, и мы его кормим, чтобы держать под контролем. Я просто хотел тупую работу!!!!!\n\n" }, { "LogFile11", "30 сентября 1968 года\r\n\r\nЯ постоянно вижу кошмары о здании Компании, где Компания выбирается из этой гигантской бетонной стены. Но я не знаю, выглядит ли оно как-то определенно, мне просто кажется, что оно огромное и быстрое. Мы не можем понять, как узнать, реальные ли голоса по телефону, Десмонд говорит, что это слишком далеко. Я спросил его, не мог бы он взять под контроль автопилот, и он сказал, что я с ума сошел, и это может нас убить. Да, я с ума сошел, Десмонд.\r\n\r\nОн говорит, что нам пришлось бы взять свой собственный частный рейс, чтобы добраться до координат, и кто знает, что там на самом деле будет. Так что, а вдруг там ничего нет? \r\nЯ стал задумываться, как я не могу вспомнить, как мы на самом деле сюда попали. Я помню только мелочи, как полет на шаттле к зданию, где мы подписали контракты. Но я не помню, как мы сели на шаттл, я даже не помню, как я попрощался с папой. В моих снах кажется, что Компания вовсе не заперта там, она просто прячется. Я не знаю, попаду ли я домой\n\n" }, { "LogFile12", "дата : 1-ое октября, 1968 года\nCнова закончились закуски и пакеты с лимонадом. Десмонд считает, что светошумовые гранаты \"более выгодны\", ну, если он отложит заказ моих вещей на другой день, я насру на рычаг управления и спрошу его, что он думает о своих светошумовых гранатах. Десмонд не читай это\n\n\nЯ знаю, что я не волшебник, но, думаю, сегодня я снова за компьютером. Каждый раз, когда я выхожу на улицу на Vow, они говорят, что я бледнею, как будто мёртвый, поэтому меня поставили дежурить у экрана. Они думают, что я стал мягким или что-то в этом роде. Неважно, Лукас напуган. Удачи, не дай ему сойти с ума. Я мог бы прогуляться ночью, как будто это мой задний двор! Просто я видел Рича на холме. Он был на другом берегу реки. Но это было три дня назад. Мне не страшно, просто на улице становится холодно. Я думаю, они просто хотят, чтобы я каждый день дежурил у экрана, и у них у всех есть оправдание\n\nЯ скучаю по папе. Надеюсь, он не останется на Титане. Люди говорят, что через два года всё будет выглядеть по-другому. Джесс сказала нам, что они собираются начать войну, и все её только и ждут. Каждый раз, когда мы идём продавать лом, здание компании трясется, как будто внутри шумит печь. Они слишком боятся выходить. Мы едва можем спать, чтобы выполнить квоту, и с каждым разом становится хуже. Боже, у меня такое ощущение, будто меня проткнули иглой. Мне бы хотелось, чтобы мы могли вернуться. Лучше было работать на папу, даже когда я ничего не получал, кроме ежедневных содержаний. Мне нравилось, когда он вывозил нас из города посмотреть водопад, и мы поднимались по старой деревянной лестнице. Я просто хотел настоящую работу\n\n" }, { "LogFile13", "Десмонд. 15 октября 1968 года\n\nЯ шифрую эти записи, чтобы сохранить их в тайне, так как боюсь, что система будет стёрта, если их найдут. Это всё обман. Мы должны думать, что это всего лишь операция, но на самом деле мы работаем над тем, чтобы поддерживать невероятный ужас. Как скоро его сытость закончится, а голод станет
BepInEx/plugins/Hayrizan-RTLC_Russian_Translation/RTLC/RTLC.Font.dll
Decompiled 4 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyCompany("RTLC.Font")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Replace in-game font with other things")] [assembly: AssemblyFileVersion("1.1.5.0")] [assembly: AssemblyInformationalVersion("1.1.5")] [assembly: AssemblyProduct("RTLC.Font")] [assembly: AssemblyTitle("RTLC.Font")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.5.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; } } } internal class ResourcePath { public const string FontPath = "Bundles"; public const string NormalFont = "3270_font"; public const string TransmitFont = "eduline_font"; } [HarmonyPatch(typeof(HUDManager))] internal class HUDManagerPatch { [HarmonyPostfix] [HarmonyPatch("OnEnable")] private static void PostfixOnEnable() { ((UnityEvent<string>)(object)HUDManager.Instance.chatTextField.onSubmit).AddListener((UnityAction<string>)OnSubmitChat); } [HarmonyPostfix] [HarmonyPatch("OnDisable")] private static void PrefixOnDisable() { ((UnityEvent<string>)(object)HUDManager.Instance.chatTextField.onSubmit).RemoveListener((UnityAction<string>)OnSubmitChat); } private static void OnSubmitChat(string chatString) { //IL_0064: 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) PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; if (!string.IsNullOrEmpty(chatString) && chatString.Length < 50) { HUDManager.Instance.AddTextToChatOnServer(chatString, (int)localPlayerController.playerClientId); } for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { if (StartOfRound.Instance.allPlayerScripts[i].isPlayerControlled && Vector3.Distance(((Component)GameNetworkManager.Instance.localPlayerController).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position) > 24.4f && (!GameNetworkManager.Instance.localPlayerController.holdingWalkieTalkie || !StartOfRound.Instance.allPlayerScripts[i].holdingWalkieTalkie)) { HUDManager.Instance.playerCouldRecieveTextChatAnimator.SetTrigger("ping"); break; } } localPlayerController.isTypingChat = false; HUDManager.Instance.chatTextField.text = ""; EventSystem.current.SetSelectedGameObject((GameObject)null); HUDManager.Instance.PingHUDElement(HUDManager.Instance.Chat, 2f, 1f, 0.2f); ((Behaviour)HUDManager.Instance.typingIndicator).enabled = false; } [HarmonyPrefix] [HarmonyPatch("SubmitChat_performed")] private static void PrefixSubmitChat_performed(ref bool __runOriginal) { __runOriginal = false; } } namespace RTLC.Font { public static class MyPluginInfo { public const string PLUGIN_GUID = "RTLC.Font"; public const string PLUGIN_NAME = "RTLC.Font"; public const string PLUGIN_VERSION = "1.1.5"; } } namespace FontPatcher { [HarmonyPatch] internal class FontLoader { private class FontBundle { public TMP_FontAsset Normal; public TMP_FontAsset Transmit; } private static List<FontBundle> fontBundles = new List<FontBundle>(); public static void Load(string location) { try { string directoryName = Path.GetDirectoryName(location); string path = Path.Combine(directoryName, "Bundles"); DirectoryInfo directoryInfo = new DirectoryInfo(path); FileInfo[] files = directoryInfo.GetFiles("rtlc.font"); FileInfo[] array = files; foreach (FileInfo fileInfo in array) { AssetBundle val = AssetBundle.LoadFromFile(fileInfo.FullName); FontBundle fontBundle = new FontBundle { Normal = val.LoadAsset<TMP_FontAsset>("3270_font"), Transmit = val.LoadAsset<TMP_FontAsset>("eduline_font") }; if (Object.op_Implicit((Object)(object)fontBundle.Normal)) { ((Object)fontBundle.Normal).name = fileInfo.Name + "(3270_font)"; } if (Object.op_Implicit((Object)(object)fontBundle.Transmit)) { ((Object)fontBundle.Transmit).name = fileInfo.Name + "(eduline_font)"; } fontBundles.Add(fontBundle); } Plugin.Instance.LogInfo("Font loaded!"); } catch (Exception ex) { Plugin.Instance.LogError(ex.Message); } } [HarmonyPrefix] [HarmonyPatch(typeof(TMP_FontAsset), "Awake")] private static void PrefixAwake(TMP_FontAsset __instance) { switch (((Object)__instance).name.Split(new char[1] { ' ' })[0]) { case "3270-Regular": case "3270-HUDIngame": case "3270-HUDIngameB": case "DialogueText": case "b": if (!Plugin.Instance.configNormalIngameFont.Value) { DisableFont(__instance); } { foreach (FontBundle fontBundle in fontBundles) { if (Object.op_Implicit((Object)(object)fontBundle.Normal)) { __instance.fallbackFontAssetTable.Add(fontBundle.Normal); } } break; } case "edunline": if (!Plugin.Instance.configTransmitIngameFont.Value) { DisableFont(__instance); } { foreach (FontBundle fontBundle2 in fontBundles) { if (Object.op_Implicit((Object)(object)fontBundle2.Transmit)) { __instance.fallbackFontAssetTable.Add(fontBundle2.Transmit); } } break; } } } private static void DisableFont(TMP_FontAsset font) { font.characterLookupTable.Clear(); font.atlasPopulationMode = (AtlasPopulationMode)0; } } internal class PluginInfo { public const string GUID = "RTLC.Font"; public const string Name = "RTLC.Font"; public const string Version = "1.1.2"; } [BepInPlugin("RTLC.Font", "RTLC.Font", "1.1.2")] internal class Plugin : BaseUnityPlugin { public ConfigEntry<bool> configNormalIngameFont; public ConfigEntry<bool> configTransmitIngameFont; public static Plugin Instance; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } configNormalIngameFont = ((BaseUnityPlugin)this).Config.Bind<bool>("Шрифты", "Стандартный шрифт", false, "Вкл/Выкл стандартный игровой шрифт."); configTransmitIngameFont = ((BaseUnityPlugin)this).Config.Bind<bool>("Шрифты", "Шрифт транслятора", false, "Вкл/Выкл стандартный шрифт транслятора сигналов."); FontLoader.Load(((BaseUnityPlugin)this).Info.Location); Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null); } public void LogInfo(string msg) { ((BaseUnityPlugin)this).Logger.LogInfo((object)msg); } public void LogWarning(string msg) { ((BaseUnityPlugin)this).Logger.LogWarning((object)msg); } public void LogError(string msg) { ((BaseUnityPlugin)this).Logger.LogError((object)msg); } } }