Decompiled source of Chzzk Skul v1.7.2
ChzzItem.dll
Decompiled 11 hours 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.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Characters; using Characters.AI; using Characters.AI.TwinSister; using Characters.Abilities; using Characters.Abilities.Customs; using Characters.Abilities.Spirits; using Characters.Actions; using Characters.Cooldowns; using Characters.Gear; using Characters.Gear.Items; using Characters.Gear.Quintessences; using Characters.Gear.Synergy; using Characters.Gear.Synergy.Inscriptions; using Characters.Gear.Weapons; using Characters.Gear.Weapons.Gauges; using Characters.Operations; using Characters.Operations.Attack; using Characters.Operations.Fx; using Characters.Operations.Gauge; using Characters.Operations.Summon; using Characters.Player; using DCDefense; using Data; using FX; using GameResources; using HarmonyLib; using Level; using Level.Npc.FieldNpcs; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Platforms; using Platforms.Steam; using Scenes; using Services; using Singletons; using Steamworks; using UI; using UI.GearPopup; using UI.Inventory; using UnityEngine; using UnityEngine.AddressableAssets; using UnityEngine.ResourceManagement.AsyncOperations; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: IgnoresAccessChecksTo("Plugins.Common")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ChzzkSkul { public static class ChzzkCardSynergy { public static List<string> EnemiesAssetKeys = new List<string>(); public static bool EnemiesKeysCached = false; private static int _cachedCardCount = 0; private static bool _cachedIsSuper = false; private static float _cacheExpireTime = 0f; private const float CACHE_DURATION = 0.3f; public static Character GetPlayer() { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Expected O, but got Unknown try { if ((Object)(object)Object.FindObjectOfType<Service>() == (Object)null) { return null; } Service instance = Singleton<Service>.Instance; object obj; if ((Object)(object)instance == (Object)null) { obj = null; } else { LevelManager levelManager = instance.levelManager; obj = (((Object)(object)levelManager != (Object)null) ? levelManager.player : null); } return (Character)obj; } catch { return null; } } public static Inscription TryGetCardInscription(Character player) { if ((Object)(object)player == (Object)null || player.playerComponents == null || player.playerComponents.inventory == null || (Object)(object)player.playerComponents.inventory.synergy == (Object)null) { return null; } try { EnumArray<Key, Inscription> inscriptions = player.playerComponents.inventory.synergy.inscriptions; if (inscriptions == null) { return null; } PropertyInfo property = ((object)inscriptions).GetType().GetProperty("Array"); if (property != null && (!(property.GetValue(inscriptions) is Array array) || 37 >= array.Length)) { return null; } return inscriptions[(Key)37]; } catch { return null; } } private static void RefreshCache() { if (!(Time.time < _cacheExpireTime)) { _cacheExpireTime = Time.time + 0.3f; Character player = GetPlayer(); Inscription val = TryGetCardInscription(player); _cachedCardCount = val?.count ?? 0; _cachedIsSuper = val != null && val.isSuper; } } public static int GetCardCount(Item item = null) { if ((Object)(object)item != (Object)null && (Object)(object)((Component)item).gameObject != (Object)null) { string name = ((Object)((Component)item).gameObject).name; if (name.Contains("_E") || name.Contains("_RE")) { return 4; } } RefreshCache(); return _cachedCardCount; } public static bool IsCardSynergySuper(Item item = null) { if ((Object)(object)item != (Object)null && (Object)(object)((Component)item).gameObject != (Object)null) { string name = ((Object)((Component)item).gameObject).name; if (name.Contains("_R") || name.Contains("_RE")) { return true; } } RefreshCache(); return _cachedIsSuper; } public static void ShowFloatingText(string message) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Expected O, but got Unknown //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) if (message.Contains("$CHAOS$")) { message = "무언가가 일어났습니다!"; } try { Service instance = Singleton<Service>.Instance; object obj; if ((Object)(object)instance == (Object)null) { obj = null; } else { LevelManager levelManager = instance.levelManager; obj = (((Object)(object)levelManager != (Object)null) ? levelManager.player : null); } Character val = (Character)obj; if ((Object)val == (Object)null) { return; } Service instance2 = Singleton<Service>.Instance; if ((Object)(object)instance2 != (Object)null) { FloatingTextSpawner floatingTextSpawner = instance2.floatingTextSpawner; if ((Object)(object)floatingTextSpawner != (Object)null) { floatingTextSpawner.SpawnBuff(message, ((Component)val).transform.position + Vector3.up * 2f, "#FFD700"); } } } catch { } } public static void InvalidateCache() { _cacheExpireTime = 0f; } } public static class ChzzkStatManager { public class StatData { public double percent = 0.0; public double percentPoint = 0.0; public double constant = 0.0; } [Serializable] public class SavedStatValue { public int categoryIndex; public int kindIndex; public double value; } [Serializable] public class SavedAbilityValue { public GlitchedTrigger trigger; public GlitchedAction action; public float value1; public float value2; public string effectDescription; } [Serializable] public class SavedGlitchedItem { public string originalName; public int slotIndex; public Rarity rarity; public Key keyword1; public Key keyword2; public List<SavedStatValue> stats = new List<SavedStatValue>(); public List<SavedAbilityValue> abilities = new List<SavedAbilityValue>(); public string glitchedName; public string glitchedDesc; public string glitchedFlavor; public string copiedItemName; public string extraCopiedItemName; } public class SaveWrapper { public bool ForceNextOmen; public bool ForceNextDarkEnemy; public bool IsBossRushActive; public bool IsScreenEffectActive; public string ScreenEffectType; public float ScreenEffectTimer; public bool IsNukeActive; public int NukeScenesPassed; public float NukeElapsed; public float BossRushElapsed; public List<string> CurrentVoteOptions = new List<string>(); public Dictionary<int, StatData> SavedStats = new Dictionary<int, StatData>(); public int SpawnedBossCount; public bool IsVoteCompletedInThisStage; public string StageName; public string VotedResultTitle; public List<string> CustomSuperInscriptions = new List<string>(); public List<SavedGlitchedItem> SavedGlitchedItems = new List<SavedGlitchedItem>(); public List<string> ExtraInventoryItems = new List<string>(); public bool IsInventoryExpanded; } public static Dictionary<int, StatData> SavedStats = new Dictionary<int, StatData>(); public static SaveWrapper SaveData = new SaveWrapper(); private static string saveFilePath => Path.Combine(Application.persistentDataPath, "ChzzkSkul_SavedStats.json"); public static event Action OnSave; public static event Action OnLoad; public static event Action OnClear; public static string GetOriginalItemName(string name) { if (string.IsNullOrEmpty(name)) { return name; } if (name.StartsWith("Glitched-")) { int num = "Glitched-".Length - 1; int num2 = name.LastIndexOf('-'); if (num2 > num) { return name.Substring(num + 1, num2 - num - 1); } } return name; } public static void Load() { try { if (!File.Exists(saveFilePath)) { return; } string text = File.ReadAllText(saveFilePath); try { SaveWrapper saveWrapper = JsonConvert.DeserializeObject<SaveWrapper>(text); if (saveWrapper != null) { SaveData = saveWrapper; if (saveWrapper.SavedStats != null) { SavedStats = saveWrapper.SavedStats; } ChzzkStatManager.OnLoad?.Invoke(); } } catch (Exception ex) { Debug.LogError((object)("[ChzzkStatManager] JSON Deserialize Error: " + ex.Message)); } } catch (Exception ex2) { Debug.LogError((object)("[ChzzkStatManager] Load Error: " + ex2.Message)); } } public static void Save() { try { SaveData.SavedStats = SavedStats; ChzzkStatManager.OnSave?.Invoke(); string contents = JsonConvert.SerializeObject((object)SaveData, (Formatting)1); File.WriteAllText(saveFilePath, contents); } catch (Exception ex) { Debug.LogError((object)("[ChzzkStatManager] Save Error: " + ex.Message)); } } public static int KindToInt(Kind kind) { if (kind == Kind.AttackDamage) { return 0; } if (kind == Kind.PhysicalAttackDamage) { return 1; } if (kind == Kind.MagicAttackDamage) { return 2; } if (kind == Kind.AttackSpeed) { return 3; } if (kind == Kind.MovementSpeed) { return 4; } if (kind == Kind.CriticalChance) { return 5; } if (kind == Kind.CriticalDamage) { return 6; } if (kind == Kind.Health) { return 7; } if (kind == Kind.TakingDamage) { return 8; } return -1; } public static Kind IntToKind(int id) { return (Kind)(id switch { 0 => Kind.AttackDamage, 1 => Kind.PhysicalAttackDamage, 2 => Kind.MagicAttackDamage, 3 => Kind.AttackSpeed, 4 => Kind.MovementSpeed, 5 => Kind.CriticalChance, 6 => Kind.CriticalDamage, 7 => Kind.Health, 8 => Kind.TakingDamage, _ => Kind.AttackDamage, }); } public static void AddStat(Character player, Category category, Kind kind, double value) { //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Expected O, but got Unknown //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Expected O, but got Unknown int num = KindToInt(kind); if (num != -1) { if (!SavedStats.ContainsKey(num)) { SavedStats[num] = new StatData(); } if (category == Category.Percent) { SavedStats[num].percent += value; } else if (category == Category.PercentPoint) { SavedStats[num].percentPoint += value; } else if (category == Category.Constant) { SavedStats[num].constant += value; } Save(); if ((Object)(object)player != (Object)null && player.stat != null) { double num2 = ((category == Category.Percent) ? (1.0 + value) : value); player.stat.AttachValues(new Values((Value[])(object)new Value[1] { new Value(category, kind, num2) })); } } } public static void ApplyToPlayer(Character player) { //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Expected O, but got Unknown //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Expected O, but got Unknown //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Expected O, but got Unknown //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Expected O, but got Unknown //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Expected O, but got Unknown //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Expected O, but got Unknown if ((Object)(object)player == (Object)null || player.stat == null) { return; } foreach (KeyValuePair<int, StatData> savedStat in SavedStats) { Kind val = IntToKind(savedStat.Key); if (savedStat.Value.percent != 0.0) { player.stat.AttachValues(new Values((Value[])(object)new Value[1] { new Value(Category.Percent, val, 1.0 + savedStat.Value.percent) })); } if (savedStat.Value.percentPoint != 0.0) { player.stat.AttachValues(new Values((Value[])(object)new Value[1] { new Value(Category.PercentPoint, val, savedStat.Value.percentPoint) })); } if (savedStat.Value.constant != 0.0) { player.stat.AttachValues(new Values((Value[])(object)new Value[1] { new Value(Category.Constant, val, savedStat.Value.constant) })); } } } public static void Clear() { if (SavedStats.Count > 0) { SavedStats.Clear(); } SaveData.IsInventoryExpanded = false; if (SaveData.ExtraInventoryItems != null) { SaveData.ExtraInventoryItems.Clear(); } if (SaveData.SavedGlitchedItems != null) { SaveData.SavedGlitchedItems.Clear(); } ChzzkStatManager.OnClear?.Invoke(); Save(); Debug.Log((object)"[ChzzkStatManager] Cleared saved stats because a new run started."); } } public sealed class VaseOfTheFallenAbilityComponent : AbilityComponent<VaseOfTheFallenAbility>, IStackable { public int currentKillCount { get; set; } public float stack { get { return currentKillCount; } set { currentKillCount = (int)value; } } public override void Initialize() { base.Initialize(); base._ability.component = this; } } [Serializable] public class VaseOfTheFallenAbility : Ability, ICloneable { public class Instance : AbilityInstance<VaseOfTheFallenAbility> { private Values _stats; private float _currentRevengeCooldown; private float _revengeTimeRemaining = 1f; public bool _canRevenge = false; public bool _isCooldown = false; private int _lostStacks; public override float iconFillAmount => _isCooldown ? (1f - _currentRevengeCooldown / base.ability._revengeCooldown) : (1f - _revengeTimeRemaining / base.ability._revengeTimeout); public override int iconStacks => ((Object)(object)base.ability.component != (Object)null) ? base.ability.component.currentKillCount : 0; public override Sprite icon { get { if ((Object)(object)base.ability.component == (Object)null || base.ability.component.currentKillCount == 0) { return null; } return ((Ability)base.ability)._defaultIcon; } } public Instance(Character owner, VaseOfTheFallenAbility ability) : base(owner, ability) { } public override void OnAttach() { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected O, but got Unknown //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Expected O, but got Unknown _stats = base.ability._statPerStack.Clone(); ((AbilityInstance)this).owner.stat.AttachValues(_stats); RefreshStacks(); Character owner = ((AbilityInstance)this).owner; owner.onKilled = (OnKilledDelegate)Delegate.Combine((Delegate?)(object)owner.onKilled, (Delegate?)new OnKilledDelegate(OnKilledEnemy)); ((Health)((AbilityInstance)this).owner.health).onTakeDamage.Add(-1000, new TakeDamageDelegate(OnTakeDamage)); } public override void OnDetach() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected O, but got Unknown Character owner = ((AbilityInstance)this).owner; owner.onKilled = (OnKilledDelegate)Delegate.Remove((Delegate?)(object)owner.onKilled, (Delegate?)new OnKilledDelegate(OnKilledEnemy)); ((AbilityInstance)this).owner.stat.DetachValues(_stats); ((Health)((AbilityInstance)this).owner.health).onTakeDamage.Remove(new TakeDamageDelegate(OnTakeDamage)); } private void OnKilledEnemy(ITarget target, ref Damage damage) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 if ((int)target.character.type != 7 && (Object)(object)base.ability.component != (Object)null) { int currentKillCount = base.ability.component.currentKillCount; base.ability.component.currentKillCount = Math.Min(currentKillCount + 1, base.ability._maxStack); RefreshStacks(); } } private unsafe bool OnTakeDamage(ref Damage damage) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Expected O, but got Unknown if (((AbilityInstance)this).owner.invulnerable.value) { return false; } AttackType attackType = damage.attackType; if (((object)(*(AttackType*)(&attackType))/*cast due to .constrained prefix*/).Equals((object)(AttackType)0)) { return false; } if (damage.@null) { return false; } if (((Damage)(ref damage)).amount < 1.0) { return false; } if ((Object)(object)base.ability.component != (Object)null) { int currentKillCount = base.ability.component.currentKillCount; _lostStacks = currentKillCount / 2; base.ability.component.currentKillCount /= 2; RefreshStacks(); _canRevenge = true; _revengeTimeRemaining = base.ability._revengeTimeout; ((PriorityList<GiveDamageDelegate>)(object)((AbilityInstance)this).owner.onGiveDamage).Add(int.MaxValue, new GiveDamageDelegate(OnRevenge)); } return false; } private bool OnRevenge(ITarget target, ref Damage damage) { //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown if (damage.@null) { return false; } if (((Damage)(ref damage)).amount < 1.0) { return false; } _canRevenge = false; _revengeTimeRemaining = base.ability._revengeTimeout; ((PriorityList<GiveDamageDelegate>)(object)((AbilityInstance)this).owner.onGiveDamage).Remove(new GiveDamageDelegate(OnRevenge)); if (_isCooldown) { return false; } if ((Object)(object)base.ability.component != (Object)null) { base.ability.component.currentKillCount += _lostStacks / 2; } _isCooldown = true; _currentRevengeCooldown = 0f; return false; } public override void UpdateTime(float deltaTime) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown ((AbilityInstance)this).UpdateTime(deltaTime); if (_canRevenge) { _revengeTimeRemaining -= deltaTime; } if (_revengeTimeRemaining < 0f) { _revengeTimeRemaining = base.ability._revengeTimeout; _canRevenge = false; ((PriorityList<GiveDamageDelegate>)(object)((AbilityInstance)this).owner.onGiveDamage).Remove(new GiveDamageDelegate(OnRevenge)); } if (_isCooldown) { _currentRevengeCooldown += deltaTime; } if (_currentRevengeCooldown > base.ability._revengeCooldown) { _currentRevengeCooldown = 0f; _isCooldown = false; } } private void RefreshStacks() { if (!((Object)(object)base.ability.component == (Object)null)) { int currentKillCount = base.ability.component.currentKillCount; for (int i = 0; i < ((ReorderableArray<Value>)(object)_stats).values.Length; i++) { ((ReorderableArray<Value>)(object)_stats).values[i].value = ((ReorderableArray<Value>)(object)base.ability._statPerStack).values[i].GetStackedValue((double)currentKillCount); } ((AbilityInstance)this).owner.stat.SetNeedUpdate(); } } } [SerializeField] internal float _revengeTimeout = 1f; [SerializeField] internal float _revengeCooldown = 1f; [SerializeField] internal int _maxStack = 1; [SerializeField] internal Values _statPerStack; public VaseOfTheFallenAbilityComponent component { get; set; } public override IAbilityInstance CreateInstance(Character owner) { return (IAbilityInstance)(object)new Instance(owner, this); } public object Clone() { return new VaseOfTheFallenAbility { _revengeTimeout = _revengeTimeout, _revengeCooldown = _revengeCooldown, _maxStack = _maxStack, _statPerStack = _statPerStack.Clone(), _defaultIcon = base._defaultIcon }; } } public sealed class CorruptedSymbolAbilityComponent : AbilityComponent<CorruptedSymbolAbility> { public override void Initialize() { base.Initialize(); } } [Serializable] public class CorruptedSymbolAbility : Ability, ICloneable { public class Instance : AbilityInstance<CorruptedSymbolAbility> { private Values _stats; private EnumArray<Key, Inscription> _inscriptions; private Inventory _inventory; public override int iconStacks => SpoilsInscriptionCount(); public int SpoilsInscriptionCount() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Invalid comparison between Unknown and I4 foreach (Inscription inscription in _inscriptions) { if ((int)inscription.key == 21) { return inscription.count; } } return 0; } public Instance(Character owner, CorruptedSymbolAbility ability) : base(owner, ability) { _inventory = owner.playerComponents.inventory; _inscriptions = owner.playerComponents.inventory.synergy.inscriptions; } public override void OnAttach() { _stats = base.ability._statPerStack.Clone(); ((AbilityInstance)this).owner.stat.AttachValues(_stats); RefreshSpoilsInscriptionCount(); _inventory.onUpdatedKeywordCounts += RefreshSpoilsInscriptionCount; } public override void OnDetach() { ((AbilityInstance)this).owner.stat.DetachValues(_stats); _inventory.onUpdatedKeywordCounts -= RefreshSpoilsInscriptionCount; } private void RefreshSpoilsInscriptionCount() { for (int i = 0; i < ((ReorderableArray<Value>)(object)_stats).values.Length; i++) { ((ReorderableArray<Value>)(object)_stats).values[i].value = ((ReorderableArray<Value>)(object)base.ability._statPerStack).values[i].GetStackedValue((double)SpoilsInscriptionCount()); } ((AbilityInstance)this).owner.stat.SetNeedUpdate(); } } [SerializeField] internal Values _statPerStack; public override IAbilityInstance CreateInstance(Character owner) { return (IAbilityInstance)(object)new Instance(owner, this); } public object Clone() { return new CorruptedSymbolAbility { _statPerStack = _statPerStack.Clone(), _defaultIcon = base._defaultIcon }; } } public sealed class GodLittleBoneAbilityComponent : AbilityComponent<GodLittleBoneAbility> { public override void Initialize() { base.Initialize(); } } [Serializable] public class GodLittleBoneAbility : Ability, ICloneable { public class Instance : AbilityInstance<GodLittleBoneAbility> { public Instance(Character owner, GodLittleBoneAbility ability) : base(owner, ability) { } public override void OnAttach() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown ((PriorityList<GiveDamageDelegate>)(object)((AbilityInstance)this).owner.onGiveDamage).Add(100, new GiveDamageDelegate(OnGiveDamage)); } public override void OnDetach() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown ((PriorityList<GiveDamageDelegate>)(object)((AbilityInstance)this).owner.onGiveDamage).Remove(new GiveDamageDelegate(OnGiveDamage)); } private bool OnGiveDamage(ITarget target, ref Damage damage) { if (damage.@null || ((Damage)(ref damage)).amount < 1.0) { return false; } damage.multiplier *= 1.5; return false; } } public override IAbilityInstance CreateInstance(Character owner) { return (IAbilityInstance)(object)new Instance(owner, this); } public object Clone() { return new GodLittleBoneAbility { _defaultIcon = base._defaultIcon }; } } public sealed class StreamerHealAbilityComponent : AbilityComponent<StreamerHealAbility> { public override void Initialize() { base.Initialize(); } } [Serializable] public class StreamerHealAbility : Ability, ICloneable { public class Instance : AbilityInstance<StreamerHealAbility> { private float _elapsed = 0f; public Instance(Character owner, StreamerHealAbility ability) : base(owner, ability) { } public override void OnAttach() { } public override void OnDetach() { } public override void UpdateTime(float deltaTime) { ((AbilityInstance)this).UpdateTime(deltaTime); _elapsed += deltaTime; if (_elapsed >= 3f) { _elapsed -= 3f; ((Health)((AbilityInstance)this).owner.health).Heal(1.0, true); } } } public override IAbilityInstance CreateInstance(Character owner) { return (IAbilityInstance)(object)new Instance(owner, this); } public object Clone() { return new StreamerHealAbility { _defaultIcon = base._defaultIcon }; } } public enum GlitchedTrigger { OnAttack, OnSkill, OnHit, OnDash, OnSwap, OnPeriodic, OnKill, OnPassive } public enum GlitchedAction { AddDamage, Shield, Heal, StatBoost, SpawnGold, SpawnBone, Explosion, SelfExplosion, StatDebuff, LoseGold, CastRandomSkill, UseRandomQuintessence, SpawnEnemy, SpawnItem, Freeze, Teleport, SpawnTemporarySpirit, PassiveBonusDamage, PassiveSummonSpirit, PassiveStatBoost, PassiveCopyItem, None } public sealed class TMTrainerAbilityComponent : AbilityComponent<TMTrainerAbility> { public override void Initialize() { base.Initialize(); } } [Serializable] public class TMTrainerAbility : Ability, ICloneable { public class Instance : AbilityInstance<TMTrainerAbility> { private float _cooldownTimer = 0f; private float _periodicTimer = 0f; private Random _rnd = new Random(); private List<Spirit> _summonedSpirits = new List<Spirit>(); private Values _passiveStats; private static readonly string[] SpiritItemNames = new string[6] { "UndineWaterSpirit", "SalamanderFireSpirit", "GnomeEarthSpirit", "SylphidWindSpirit", "LughLightSpirit", "DeathShadowSpirit" }; private static readonly FieldInfo damageKeyField = typeof(Damage).GetField("key", BindingFlags.Instance | BindingFlags.Public); public Instance(Character owner, TMTrainerAbility ability) : base(owner, ability) { } public override void OnAttach() { //IL_01b4: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Expected O, but got Unknown //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Expected O, but got Unknown //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Expected O, but got Unknown //IL_0204: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Expected O, but got Unknown //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected O, but got Unknown //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Expected O, but got Unknown //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Expected O, but got Unknown if (base.ability.trigger == GlitchedTrigger.OnPassive) { if (base.ability.action == GlitchedAction.PassiveSummonSpirit) { string spiritItemName = SpiritItemNames[_rnd.Next(SpiritItemNames.Length)]; ((MonoBehaviour)((AbilityInstance)this).owner).StartCoroutine(C_SummonSpirit(spiritItemName)); } else if (base.ability.action == GlitchedAction.PassiveBonusDamage) { ((PriorityList<GiveDamageDelegate>)(object)((AbilityInstance)this).owner.onGiveDamage).Add(100, new GiveDamageDelegate(OnGiveDamageForPassiveBonus)); } else if (base.ability.action == GlitchedAction.PassiveStatBoost) { int num = (int)base.ability.value2; Kind val = Kind.AttackSpeed; switch (num) { case 1: val = Kind.PhysicalAttackDamage; break; case 2: val = Kind.MagicAttackDamage; break; case 3: val = Kind.MovementSpeed; break; } _passiveStats = new Values((Value[])(object)new Value[1] { new Value(Category.PercentPoint, val, (double)base.ability.value1 / 100.0) }); ((AbilityInstance)this).owner.stat.AttachValues(_passiveStats); ((AbilityInstance)this).owner.stat.SetNeedUpdate(); } } else { switch (base.ability.trigger) { case GlitchedTrigger.OnAttack: ((PriorityList<GiveDamageDelegate>)(object)((AbilityInstance)this).owner.onGiveDamage).Add(100, new GiveDamageDelegate(OnGiveDamageForAttack)); break; case GlitchedTrigger.OnHit: ((Health)((AbilityInstance)this).owner.health).onTakeDamage.Add(-100, new TakeDamageDelegate(OnTakeDamageForHit)); break; case GlitchedTrigger.OnKill: { Character owner = ((AbilityInstance)this).owner; owner.onKilled = (OnKilledDelegate)Delegate.Combine((Delegate?)(object)owner.onKilled, (Delegate?)new OnKilledDelegate(OnKilled)); break; } case GlitchedTrigger.OnSkill: case GlitchedTrigger.OnDash: case GlitchedTrigger.OnSwap: ((AbilityInstance)this).owner.onStartAction += OnStartAction; break; case GlitchedTrigger.OnPeriodic: break; } } } public override void OnDetach() { //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Expected O, but got Unknown //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Expected O, but got Unknown //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Expected O, but got Unknown //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Expected O, but got Unknown //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Expected O, but got Unknown foreach (Spirit summonedSpirit in _summonedSpirits) { if ((Object)(object)summonedSpirit != (Object)null && (Object)(object)((Component)summonedSpirit).gameObject != (Object)null) { Object.Destroy((Object)(object)((Component)summonedSpirit).gameObject); } } _summonedSpirits.Clear(); if (_passiveStats != null) { ((AbilityInstance)this).owner.stat.DetachValues(_passiveStats); ((AbilityInstance)this).owner.stat.SetNeedUpdate(); } if (base.ability.trigger == GlitchedTrigger.OnPassive) { if (base.ability.action == GlitchedAction.PassiveBonusDamage) { ((PriorityList<GiveDamageDelegate>)(object)((AbilityInstance)this).owner.onGiveDamage).Remove(new GiveDamageDelegate(OnGiveDamageForPassiveBonus)); } return; } switch (base.ability.trigger) { case GlitchedTrigger.OnAttack: ((PriorityList<GiveDamageDelegate>)(object)((AbilityInstance)this).owner.onGiveDamage).Remove(new GiveDamageDelegate(OnGiveDamageForAttack)); break; case GlitchedTrigger.OnHit: ((Health)((AbilityInstance)this).owner.health).onTakeDamage.Remove(new TakeDamageDelegate(OnTakeDamageForHit)); break; case GlitchedTrigger.OnKill: { Character owner = ((AbilityInstance)this).owner; owner.onKilled = (OnKilledDelegate)Delegate.Remove((Delegate?)(object)owner.onKilled, (Delegate?)new OnKilledDelegate(OnKilled)); break; } case GlitchedTrigger.OnSkill: case GlitchedTrigger.OnDash: case GlitchedTrigger.OnSwap: ((AbilityInstance)this).owner.onStartAction -= OnStartAction; break; case GlitchedTrigger.OnPeriodic: break; } } public override void UpdateTime(float deltaTime) { ((AbilityInstance)this).UpdateTime(deltaTime); if (base.ability.trigger == GlitchedTrigger.OnPeriodic) { _periodicTimer += deltaTime; if (_periodicTimer >= base.ability.value2) { _periodicTimer = 0f; TriggerAction(null); } } } private bool OnGiveDamageForAttack(ITarget target, ref Damage damage) { if (base.ability.trigger == GlitchedTrigger.OnAttack) { if (damage.key == "GlitchedPassiveBonus") { return false; } TriggerAction(target); } return false; } private bool OnTakeDamageForHit(ref Damage damage) { if (base.ability.trigger == GlitchedTrigger.OnHit) { TriggerAction(null); } return false; } private void OnKilled(ITarget target, ref Damage damage) { if (base.ability.trigger == GlitchedTrigger.OnKill) { TriggerAction(target); } } private void OnStartAction(Action action) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Invalid comparison between Unknown and I4 //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Invalid comparison between Unknown and I4 //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Invalid comparison between Unknown and I4 if (!((Object)(object)action == (Object)null)) { bool flag = false; if (base.ability.trigger == GlitchedTrigger.OnSkill && (int)action.type == 4) { flag = true; } else if (base.ability.trigger == GlitchedTrigger.OnDash && (int)action.type == 0) { flag = true; } else if (base.ability.trigger == GlitchedTrigger.OnSwap && (int)action.type == 5) { flag = true; } if (flag) { TriggerAction(null); } } } private void TriggerAction(ITarget target) { //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_05fd: Unknown result type (might be due to invalid IL or missing references) //IL_05fe: Unknown result type (might be due to invalid IL or missing references) //IL_0742: Unknown result type (might be due to invalid IL or missing references) //IL_0743: Unknown result type (might be due to invalid IL or missing references) //IL_0b17: Unknown result type (might be due to invalid IL or missing references) //IL_0b18: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_0543: Unknown result type (might be due to invalid IL or missing references) //IL_0548: Unknown result type (might be due to invalid IL or missing references) //IL_0552: Unknown result type (might be due to invalid IL or missing references) //IL_0557: Unknown result type (might be due to invalid IL or missing references) //IL_05c0: Unknown result type (might be due to invalid IL or missing references) //IL_05c5: Unknown result type (might be due to invalid IL or missing references) //IL_05cf: Unknown result type (might be due to invalid IL or missing references) //IL_05d4: Unknown result type (might be due to invalid IL or missing references) //IL_064c: Unknown result type (might be due to invalid IL or missing references) //IL_0652: Invalid comparison between Unknown and I4 //IL_0791: Unknown result type (might be due to invalid IL or missing references) //IL_0797: Invalid comparison between Unknown and I4 //IL_0b66: Unknown result type (might be due to invalid IL or missing references) //IL_0b6c: Invalid comparison between Unknown and I4 //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_0656: Unknown result type (might be due to invalid IL or missing references) //IL_065c: Invalid comparison between Unknown and I4 //IL_079b: Unknown result type (might be due to invalid IL or missing references) //IL_07a1: Invalid comparison between Unknown and I4 //IL_08aa: Unknown result type (might be due to invalid IL or missing references) //IL_08bc: Unknown result type (might be due to invalid IL or missing references) //IL_08c1: Unknown result type (might be due to invalid IL or missing references) //IL_0b70: Unknown result type (might be due to invalid IL or missing references) //IL_0b76: Invalid comparison between Unknown and I4 //IL_0691: Unknown result type (might be due to invalid IL or missing references) //IL_069f: Unknown result type (might be due to invalid IL or missing references) //IL_06a4: Unknown result type (might be due to invalid IL or missing references) //IL_07d6: Unknown result type (might be due to invalid IL or missing references) //IL_07e4: Unknown result type (might be due to invalid IL or missing references) //IL_07e9: Unknown result type (might be due to invalid IL or missing references) //IL_0274: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Invalid comparison between Unknown and I4 //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_0284: Invalid comparison between Unknown and I4 //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_02c7: Unknown result type (might be due to invalid IL or missing references) //IL_02cc: Unknown result type (might be due to invalid IL or missing references) //IL_0328: Unknown result type (might be due to invalid IL or missing references) //IL_0345: Unknown result type (might be due to invalid IL or missing references) //IL_034a: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)((AbilityInstance)this).owner == (Object)null || (Object)(object)((Component)((AbilityInstance)this).owner).gameObject == (Object)null || (Object)(object)((Component)((AbilityInstance)this).owner).transform == (Object)null || (Object)(object)((AbilityInstance)this).owner.health == (Object)null || ((Health)((AbilityInstance)this).owner.health).dead) { return; } Vector3 position = ((Component)((AbilityInstance)this).owner).transform.position; if (target != null && (Object)(object)target.transform != (Object)null) { position = target.transform.position; } switch (base.ability.action) { case GlitchedAction.AddDamage: { double num9 = base.ability.value1; bool flag2 = _rnd.Next(2) == 0; if (target != null && (Object)(object)target.character != (Object)null && (Object)(object)((Component)target.character).transform != (Object)null && (Object)(object)target.character.health != (Object)null && !((Health)target.character.health).dead) { Damage val9 = default(Damage); ((Damage)(ref val9))..ctor(Attacker.op_Implicit(((AbilityInstance)this).owner), num9, Vector2.op_Implicit(((Component)target.character).transform.position), (Attribute)(!flag2), (AttackType)4, (MotionType)0, 1.0, 0f, 0.0, 1.0, 1.0, true, false, 0.0, 0.0, (short)0, (PriorityList<bool>)null, 1.0); object obj5 = val9; damageKeyField.SetValue(obj5, "GlitchedPassiveBonus"); val9 = (Damage)obj5; ((AbilityInstance)this).owner.Attack(target, ref val9); break; } Collider2D[] array7 = Physics2D.OverlapCircleAll(Vector2.op_Implicit(position), 5f); Collider2D[] array8 = array7; Damage val11 = default(Damage); foreach (Collider2D val10 in array8) { if (!((Object)(object)val10 == (Object)null)) { Character componentInParent4 = ((Component)val10).GetComponentInParent<Character>(); if ((Object)(object)componentInParent4 != (Object)null && (int)componentInParent4.type != 6 && (int)componentInParent4.type != 7 && (Object)(object)componentInParent4.health != (Object)null && !((Health)componentInParent4.health).dead) { ((Damage)(ref val11))..ctor(Attacker.op_Implicit(((AbilityInstance)this).owner), num9, Vector2.op_Implicit(((Component)componentInParent4).transform.position), (Attribute)(!flag2), (AttackType)4, (MotionType)0, 1.0, 0f, 0.0, 1.0, 1.0, true, false, 0.0, 0.0, (short)0, (PriorityList<bool>)null, 1.0); object obj6 = val11; damageKeyField.SetValue(obj6, "GlitchedPassiveBonus"); val11 = (Damage)obj6; ((AbilityInstance)this).owner.Attack(componentInParent4, ref val11); } } } break; } case GlitchedAction.Shield: { double num7 = base.ability.value1; try { FieldInfo field = ((object)((AbilityInstance)this).owner.health).GetType().GetField("shield", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { object value = field.GetValue(((AbilityInstance)this).owner.health); if (value != null) { (value.GetType().GetMethod("Add", new Type[2] { typeof(Object), typeof(double) }) ?? value.GetType().GetMethod("Add", new Type[2] { typeof(object), typeof(double) }))?.Invoke(value, new object[2] { ((AbilityInstance)this).owner, num7 }); } } break; } catch { break; } } case GlitchedAction.Heal: { double num6 = base.ability.value1; ((Health)((AbilityInstance)this).owner.health).Heal(num6, true); break; } case GlitchedAction.StatBoost: { bool attackSpeed2 = _rnd.Next(2) == 0; double amount2 = (double)base.ability.value1 / 100.0; ((MonoBehaviour)((AbilityInstance)this).owner).StartCoroutine(C_TriggerStatBoost(attackSpeed2, amount2, base.ability.value2)); break; } case GlitchedAction.SpawnGold: { int num5 = (int)base.ability.value1; try { Service instance2 = Singleton<Service>.Instance; if ((Object)(object)instance2 != (Object)null && (Object)(object)instance2.levelManager != (Object)null) { instance2.levelManager.DropCurrency((Type)0, num5, 10, ((Component)((AbilityInstance)this).owner).transform.position + Vector3.up * 1.5f); } break; } catch { break; } } case GlitchedAction.SpawnBone: { int num4 = (int)base.ability.value1; try { Service instance = Singleton<Service>.Instance; if ((Object)(object)instance != (Object)null && (Object)(object)instance.levelManager != (Object)null) { instance.levelManager.DropCurrency((Type)2, num4, num4, ((Component)((AbilityInstance)this).owner).transform.position + Vector3.up * 1.5f); } break; } catch { break; } } case GlitchedAction.Explosion: { double num8 = base.ability.value1; Collider2D[] array5 = Physics2D.OverlapCircleAll(Vector2.op_Implicit(position), 7f); Collider2D[] array6 = array5; Damage val8 = default(Damage); foreach (Collider2D val7 in array6) { if (!((Object)(object)val7 == (Object)null)) { Character componentInParent3 = ((Component)val7).GetComponentInParent<Character>(); if ((Object)(object)componentInParent3 != (Object)null && (int)componentInParent3.type != 6 && (int)componentInParent3.type != 7 && (Object)(object)componentInParent3.health != (Object)null && !((Health)componentInParent3.health).dead) { ((Damage)(ref val8))..ctor(Attacker.op_Implicit(((AbilityInstance)this).owner), num8, Vector2.op_Implicit(((Component)componentInParent3).transform.position), (Attribute)2, (AttackType)4, (MotionType)0, 1.0, 0f, 0.0, 1.0, 1.0, true, false, 0.0, 0.0, (short)0, (PriorityList<bool>)null, 1.0); ((AbilityInstance)this).owner.Attack(componentInParent3, ref val8); } } } break; } case GlitchedAction.SelfExplosion: { double num2 = base.ability.value1; double num3 = _rnd.Next(3, 11); Collider2D[] array3 = Physics2D.OverlapCircleAll(Vector2.op_Implicit(position), 8f); Collider2D[] array4 = array3; Damage val5 = default(Damage); foreach (Collider2D val4 in array4) { if (!((Object)(object)val4 == (Object)null)) { Character componentInParent2 = ((Component)val4).GetComponentInParent<Character>(); if ((Object)(object)componentInParent2 != (Object)null && (int)componentInParent2.type != 6 && (int)componentInParent2.type != 7 && (Object)(object)componentInParent2.health != (Object)null && !((Health)componentInParent2.health).dead) { ((Damage)(ref val5))..ctor(Attacker.op_Implicit(((AbilityInstance)this).owner), num2, Vector2.op_Implicit(((Component)componentInParent2).transform.position), (Attribute)2, (AttackType)4, (MotionType)0, 1.0, 0f, 0.0, 1.0, 1.0, true, false, 0.0, 0.0, (short)0, (PriorityList<bool>)null, 1.0); ((AbilityInstance)this).owner.Attack(componentInParent2, ref val5); } } } if ((Object)(object)((AbilityInstance)this).owner != (Object)null && (Object)(object)((AbilityInstance)this).owner.health != (Object)null && !((Health)((AbilityInstance)this).owner.health).dead) { Damage val6 = default(Damage); ((Damage)(ref val6))..ctor(Attacker.op_Implicit(((AbilityInstance)this).owner), num3, Vector2.op_Implicit(((Component)((AbilityInstance)this).owner).transform.position), (Attribute)2, (AttackType)4, (MotionType)0, 1.0, 0f, 0.0, 1.0, 1.0, true, false, 0.0, 0.0, (short)0, (PriorityList<bool>)null, 1.0); ((Health)((AbilityInstance)this).owner.health).TakeDamage(ref val6); } break; } case GlitchedAction.StatDebuff: { bool attackSpeed = _rnd.Next(2) == 0; double amount = (double)(0f - base.ability.value1) / 100.0; ((MonoBehaviour)((AbilityInstance)this).owner).StartCoroutine(C_TriggerStatBoost(attackSpeed, amount, base.ability.value2)); break; } case GlitchedAction.LoseGold: { int val2 = (int)base.ability.value1; try { int num = Math.Min(val2, Currency.gold.balance); if (num > 0) { Currency.gold.Consume(num); } break; } catch { break; } } case GlitchedAction.CastRandomSkill: { if (((AbilityInstance)this).owner.playerComponents == null || ((AbilityInstance)this).owner.playerComponents.inventory == null || !((Object)(object)((AbilityInstance)this).owner.playerComponents.inventory.weapon != (Object)null)) { break; } Weapon current = ((AbilityInstance)this).owner.playerComponents.inventory.weapon.current; if ((Object)(object)current != (Object)null && current.currentSkills != null && current.currentSkills.Count > 0) { SkillInfo val3 = current.currentSkills[_rnd.Next(current.currentSkills.Count)]; if ((Object)(object)val3 != (Object)null && (Object)(object)val3.action != (Object)null) { val3.action.TryStart(); } } break; } case GlitchedAction.UseRandomQuintessence: ((MonoBehaviour)((AbilityInstance)this).owner).StartCoroutine(C_UseRandomQuintessence(((AbilityInstance)this).owner)); break; case GlitchedAction.SpawnEnemy: ((MonoBehaviour)((AbilityInstance)this).owner).StartCoroutine(C_SpawnRandomEnemy(((AbilityInstance)this).owner)); break; case GlitchedAction.SpawnItem: ((MonoBehaviour)((AbilityInstance)this).owner).StartCoroutine(C_SpawnRandomItem(((AbilityInstance)this).owner)); break; case GlitchedAction.Freeze: { Collider2D[] array = Physics2D.OverlapCircleAll(Vector2.op_Implicit(position), 8f); bool flag = false; Collider2D[] array2 = array; foreach (Collider2D val in array2) { if (!((Object)(object)val == (Object)null)) { Character componentInParent = ((Component)val).GetComponentInParent<Character>(); if ((Object)(object)componentInParent != (Object)null && (int)componentInParent.type != 6 && (int)componentInParent.type != 7 && (Object)(object)componentInParent.health != (Object)null && !((Health)componentInParent.health).dead && (Object)(object)componentInParent.status != (Object)null) { componentInParent.status.ApplyFreeze(((AbilityInstance)this).owner); flag = true; } } } if (!flag) { } break; } case GlitchedAction.Teleport: break; case GlitchedAction.SpawnTemporarySpirit: { string spiritItemName = SpiritItemNames[_rnd.Next(SpiritItemNames.Length)]; ((MonoBehaviour)((AbilityInstance)this).owner).StartCoroutine(C_SummonSpirit(spiritItemName, base.ability.value1)); break; } } } private IEnumerator C_SpawnRandomEnemy(Character owner) { if (ChzzkCardSynergy.EnemiesAssetKeys == null || ChzzkCardSynergy.EnemiesAssetKeys.Count == 0) { yield break; } string foundKey = ChzzkCardSynergy.EnemiesAssetKeys[_rnd.Next(ChzzkCardSynergy.EnemiesAssetKeys.Count)]; if (foundKey == null) { yield break; } AsyncOperationHandle<GameObject> handle = Addressables.InstantiateAsync((object)foundKey, (Transform)null, false, true); while (!handle.IsDone) { yield return null; } if ((Object)(object)owner == (Object)null || (Object)(object)((Component)owner).gameObject == (Object)null || (Object)(object)((Component)owner).transform == (Object)null || (int)handle.Status != 1) { yield break; } GameObject loadedObj = handle.Result; if (!((Object)(object)loadedObj != (Object)null)) { yield break; } Character enemyChar = loadedObj.GetComponent<Character>(); if (!((Object)(object)enemyChar != (Object)null)) { yield break; } loadedObj.transform.position = ((Component)owner).transform.position + new Vector3((float)_rnd.Next(-4, 5), 1f, 0f); loadedObj.SetActive(true); if ((Object)(object)enemyChar.attach != (Object)null) { enemyChar.attach.SetActive(true); } yield return null; if (!((Object)(object)enemyChar != (Object)null) || !((Object)(object)owner != (Object)null) || !((Object)(object)((Component)owner).gameObject != (Object)null)) { yield break; } MonoBehaviour[] componentsInChildren = ((Component)enemyChar).GetComponentsInChildren<MonoBehaviour>(true); foreach (MonoBehaviour mono in componentsInChildren) { if ((Object)(object)mono == (Object)null) { continue; } AIController controller = (AIController)(object)((mono is AIController) ? mono : null); if (controller != null) { controller.target = owner; try { controller.FoundEnemy(); } catch { } } } if ((Object)(object)Map.Instance != (Object)null && (Object)(object)Map.Instance.waveContainer != (Object)null) { try { Map.Instance.waveContainer.Attach(enemyChar); } catch { } } } private IEnumerator C_SpawnRandomItem(Character owner) { Service service = Singleton<Service>.Instance; if (!((Object)(object)service != (Object)null) || !((Object)(object)service.gearManager != (Object)null) || !((Object)(object)service.levelManager != (Object)null)) { yield break; } Rarity rarity = (Rarity)_rnd.Next(4); ItemReference itemRef = service.gearManager.GetItemToTake(rarity); if (itemRef != null) { ItemRequest request = itemRef.LoadAsync(); while (!((Request<Item>)(object)request).isDone) { yield return null; } if (!((Object)(object)owner == (Object)null) && !((Object)(object)((Component)owner).gameObject == (Object)null) && !((Object)(object)((Component)owner).transform == (Object)null) && (Object)(object)((Request<Item>)(object)request).asset != (Object)null) { service.levelManager.DropItem(request, ((Component)owner).transform.position + Vector3.up * 1f); } } } private IEnumerator C_UseRandomQuintessence(Character owner) { Service service = Singleton<Service>.Instance; if (!((Object)(object)service != (Object)null) || !((Object)(object)service.gearManager != (Object)null)) { yield break; } Rarity rarity = (Rarity)_rnd.Next(4); EssenceReference quinteRef = service.gearManager.GetQuintessenceToTake(rarity); if (quinteRef == null) { yield break; } EssenceRequest req = quinteRef.LoadAsync(); while (!((Request<Quintessence>)(object)req).isDone) { yield return null; } if ((Object)(object)owner == (Object)null || (Object)(object)((Component)owner).gameObject == (Object)null || (Object)(object)((Component)owner).transform == (Object)null || !((Object)(object)((Request<Quintessence>)(object)req).asset != (Object)null)) { yield break; } Quintessence prefab = ((Component)((Request<Quintessence>)(object)req).asset).GetComponent<Quintessence>(); if ((Object)(object)prefab != (Object)null) { Quintessence quinteInstance = Object.Instantiate<Quintessence>(prefab); ((Component)quinteInstance).transform.parent = ((Component)owner).transform; ((Component)quinteInstance).transform.localPosition = Vector3.zero; try { ((Gear)quinteInstance).Initialize(); quinteInstance.SetOwner(owner); quinteInstance.Use(); } catch (Exception ex) { Debug.LogError((object)("[UseRandomQuintessence] Failed to use quintessence: " + ex)); } Object.Destroy((Object)(object)((Component)quinteInstance).gameObject, 20f); } } private IEnumerator C_SummonSpirit(string spiritItemName, float duration = -1f) { Service service = Singleton<Service>.Instance; if ((Object)(object)service == (Object)null) { yield break; } GlobalSummonedSpirits.RemoveAll((Spirit s) => (Object)(object)s == (Object)null || (Object)(object)((Component)s).gameObject == (Object)null); if (GlobalSummonedSpirits.Count >= 128) { yield break; } ItemReference itemRef = null; if (!GearResource.instance.TryGetItemReferenceByName(spiritItemName, ref itemRef)) { yield break; } ItemRequest req = itemRef.LoadAsync(); while (!((Request<Item>)(object)req).isDone) { yield return null; } if ((Object)(object)((AbilityInstance)this).owner == (Object)null || (Object)(object)((Component)((AbilityInstance)this).owner).gameObject == (Object)null || !((Object)(object)((Request<Item>)(object)req).asset != (Object)null)) { yield break; } Item itemPrefab = ((Component)((Request<Item>)(object)req).asset).GetComponent<Item>(); if (!((Object)(object)itemPrefab != (Object)null)) { yield break; } Spirit spiritComponent = ((Component)itemPrefab).GetComponentInChildren<Spirit>(true); if (!((Object)(object)spiritComponent != (Object)null)) { yield break; } GameObject spiritGo = Object.Instantiate<GameObject>(((Component)spiritComponent).gameObject); spiritGo.transform.position = ((Component)((AbilityInstance)this).owner).transform.position; Spirit spiritInstance = spiritGo.GetComponent<Spirit>(); if ((Object)(object)spiritInstance != (Object)null) { ((AbilityAttacher)spiritInstance).Initialize(((AbilityInstance)this).owner); spiritInstance.targetPosition = ((Component)((AbilityInstance)this).owner).transform; spiritInstance.Attach(); ((AbilityAttacher)spiritInstance).StartAttach(); _summonedSpirits.Add(spiritInstance); GlobalSummonedSpirits.Add(spiritInstance); if (duration > 0f) { ((MonoBehaviour)((AbilityInstance)this).owner).StartCoroutine(C_TemporarySpirit(spiritInstance, duration)); } } } private IEnumerator C_TemporarySpirit(Spirit spirit, float duration) { yield return (object)new WaitForSeconds(duration); if ((Object)(object)spirit != (Object)null) { _summonedSpirits.Remove(spirit); try { spirit.Detach(); } catch { } try { ((AbilityAttacher)spirit).StopAttach(); } catch { } try { Object.Destroy((Object)(object)((Component)spirit).gameObject); } catch { } } } private bool OnGiveDamageForPassiveBonus(ITarget target, ref Damage damage) { //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) if (damage.@null || ((Damage)(ref damage)).amount < 1.0) { return false; } if (damage.key == "GlitchedPassiveBonus") { return false; } double num = base.ability.value1; bool flag = _rnd.Next(2) == 0; if (target != null && (Object)(object)target.character != (Object)null && (Object)(object)((Component)target.character).transform != (Object)null && (Object)(object)target.character.health != (Object)null && !((Health)target.character.health).dead) { Damage val = default(Damage); ((Damage)(ref val))..ctor(Attacker.op_Implicit(((AbilityInstance)this).owner), num, Vector2.op_Implicit(((Component)target.character).transform.position), (Attribute)(!flag), (AttackType)4, (MotionType)0, 1.0, 0f, 0.0, 1.0, 1.0, true, false, 0.0, 0.0, (short)0, (PriorityList<bool>)null, 1.0); object obj = val; damageKeyField.SetValue(obj, "GlitchedPassiveBonus"); val = (Damage)obj; ((AbilityInstance)this).owner.Attack(target, ref val); } return false; } private IEnumerator C_TriggerStatBoost(bool attackSpeed, double amount, float duration) { if (!((Object)(object)((AbilityInstance)this).owner == (Object)null) && !((Object)(object)((Component)((AbilityInstance)this).owner).gameObject == (Object)null) && ((AbilityInstance)this).owner.stat != null) { Category category = Category.PercentPoint; Kind kind = (attackSpeed ? Kind.BasicAttackSpeed : Kind.SkillCooldownSpeed); Value val = new Value(category, kind, amount); Values statValues = new Values((Value[])(object)new Value[1] { val }); ((AbilityInstance)this).owner.stat.AttachValues(statValues); if (amount < 0.0) { string msg = ((!PluginItems.IsKorean()) ? (attackSpeed ? $"[Data Degrade] Attack speed reduced by {Math.Abs(amount) * 100.0:F0}%!" : $"[Data Degrade] Cooldown speed reduced by {Math.Abs(amount) * 100.0:F0}%!") : (attackSpeed ? $"[?곗씠???\u0080?? 怨듦꺽 ?띾룄 {amount * 100.0:F0}% 媛먯냼!" : $"[?곗씠???\u0080?? 荑⑤떎???띾룄 {amount * 100.0:F0}% 媛먯냼!")); ChzzkCardSynergy.ShowFloatingText(msg); } else { string msg2 = ((!PluginItems.IsKorean()) ? (attackSpeed ? $"[Data Alter] Attack speed +{amount * 100.0:F0}%!" : $"[Data Alter] Cooldown speed +{amount * 100.0:F0}%!") : (attackSpeed ? $"[?곗씠??蹂\u0080議? 怨듦꺽 ?띾룄 +{amount * 100.0:F0}% 媛\u0080??" : $"[?곗씠??蹂\u0080議? 荑⑤떎???띾룄 +{amount * 100.0:F0}% 媛\u0080??")); ChzzkCardSynergy.ShowFloatingText(msg2); } yield return (object)new WaitForSeconds(duration); if ((Object)(object)((AbilityInstance)this).owner != (Object)null && (Object)(object)((Component)((AbilityInstance)this).owner).gameObject != (Object)null && ((AbilityInstance)this).owner.stat != null) { ((AbilityInstance)this).owner.stat.DetachValues(statValues); } } } } public GlitchedTrigger trigger; public GlitchedAction action; public float value1; public float value2; public string effectDescription; public static readonly List<Spirit> GlobalSummonedSpirits = new List<Spirit>(); public override IAbilityInstance CreateInstance(Character owner) { return (IAbilityInstance)(object)new Instance(owner, this); } public object Clone() { return MemberwiseClone(); } } public sealed class GlitchedStatAbilityComponent : AbilityComponent<GlitchedStatAbility> { public override void Initialize() { base.Initialize(); } } [Serializable] public class GlitchedStatAbility : Ability, ICloneable { public class Instance : AbilityInstance<GlitchedStatAbility> { private Values _stats; public Instance(Character owner, GlitchedStatAbility ability) : base(owner, ability) { } public override void OnAttach() { if (base.ability.stats != null) { _stats = base.ability.stats.Clone(); ((AbilityInstance)this).owner.stat.AttachValues(_stats); ((AbilityInstance)this).owner.stat.SetNeedUpdate(); } } public override void OnDetach() { if (_stats != null) { ((AbilityInstance)this).owner.stat.DetachValues(_stats); ((AbilityInstance)this).owner.stat.SetNeedUpdate(); } } } public Values stats; public override IAbilityInstance CreateInstance(Character owner) { return (IAbilityInstance)(object)new Instance(owner, this); } public object Clone() { return new GlitchedStatAbility { stats = ((stats != null) ? stats.Clone() : null), _defaultIcon = base._defaultIcon }; } } [HarmonyPatch] public class UseSkillBypassPatch { [HarmonyPrefix] [HarmonyPatch(typeof(CooldownSerializer), "get_canUse")] private static bool get_canUse_Prefix(CooldownSerializer __instance, ref bool __result) { try { Character player = ChzzkCardSynergy.GetPlayer(); if ((Object)(object)player != (Object)null && player.playerComponents != null && player.playerComponents.inventory != null) { WeaponInventory weapon = player.playerComponents.inventory.weapon; if ((Object)(object)weapon != (Object)null) { Weapon current = weapon.current; if ((Object)(object)current != (Object)null && current.currentSkills != null) { foreach (SkillInfo currentSkill in current.currentSkills) { if ((Object)(object)currentSkill != (Object)null && (Object)(object)currentSkill.action != (Object)null && currentSkill.action.cooldown == __instance) { __result = true; return false; } } } Weapon next = weapon.next; if ((Object)(object)next != (Object)null && next.currentSkills != null) { foreach (SkillInfo currentSkill2 in next.currentSkills) { if ((Object)(object)currentSkill2 != (Object)null && (Object)(object)currentSkill2.action != (Object)null && currentSkill2.action.cooldown == __instance) { __result = true; return false; } } } } } } catch (Exception ex) { Debug.LogWarning((object)("[UseSkillBypassPatch] Failed to bypass cooldown: " + ex.Message)); } return true; } } public sealed class GuanYuCrescentBladeAbilityComponent : AbilityComponent<GuanYuCrescentBladeAbility> { public override void Initialize() { base.Initialize(); } } [Serializable] public class GuanYuCrescentBladeAbility : Ability, ICloneable { public class Instance : AbilityInstance<GuanYuCrescentBladeAbility> { private float _cooldownTimer = 0f; private const float Cooldown = 0f; public Instance(Character owner, GuanYuCrescentBladeAbility ability) : base(owner, ability) { } public override void OnAttach() { ((AbilityInstance)this).owner.onStartAction += OnStartAction; } public override void OnDetach() { ((AbilityInstance)this).owner.onStartAction -= OnStartAction; } public override void UpdateTime(float deltaTime) { ((AbilityInstance)this).UpdateTime(deltaTime); if (_cooldownTimer > 0f) { _cooldownTimer -= deltaTime; } } private void OnStartAction(Action action) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Invalid comparison between Unknown and I4 //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Invalid comparison between Unknown and I4 //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Invalid comparison between Unknown and I4 if (!((Object)(object)action == (Object)null)) { Debug.Log((object)$"[ChzzkSkul] GuanYu Crescent Blade OnStartAction: name='{((Object)action).name}', type={action.type}"); if ((int)action.type == 1 || (((Object)action).name != null && ((Object)action).name.IndexOf("attack", StringComparison.OrdinalIgnoreCase) >= 0 && (int)action.type != 4 && (int)action.type != 0 && (int)action.type != 5)) { TriggerSlash(); } } } private void TriggerSlash() { //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_04d7: Unknown result type (might be due to invalid IL or missing references) //IL_04df: Unknown result type (might be due to invalid IL or missing references) //IL_035b: Unknown result type (might be due to invalid IL or missing references) //IL_046e: Unknown result type (might be due to invalid IL or missing references) //IL_047a: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Invalid comparison between Unknown and I4 //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Invalid comparison between Unknown and I4 //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Invalid comparison between Unknown and I4 //IL_03f5: Unknown result type (might be due to invalid IL or missing references) //IL_024a: Unknown result type (might be due to invalid IL or missing references) //IL_02e4: Unknown result type (might be due to invalid IL or missing references) bool flag = false; _cooldownTimer = 0f; if ((Object)(object)((AbilityInstance)this).owner == (Object)null || (Object)(object)((Component)((AbilityInstance)this).owner).gameObject == (Object)null || (Object)(object)((AbilityInstance)this).owner.health == (Object)null || ((Health)((AbilityInstance)this).owner.health).dead) { return; } int num = 0; try { Collider2D[] array = Physics2D.OverlapCircleAll(Vector2.op_Implicit(((Component)((AbilityInstance)this).owner).transform.position), 10f); Collider2D[] array2 = array; foreach (Collider2D val in array2) { if (!((Object)(object)val == (Object)null)) { Character componentInParent = ((Component)val).GetComponentInParent<Character>(); if ((Object)(object)componentInParent != (Object)null && (int)componentInParent.type != 6 && (int)componentInParent.type != 7 && (Object)(object)componentInParent.health != (Object)null && !((Health)componentInParent.health).dead) { num++; } } } } catch { } double baseMultiplier = 1.0; if (num == 1) { baseMultiplier = 1.5; } Debug.Log((object)("[ChzzkSkul] GuanYu TriggerSlash executing! GreenSlashEffect: " + ((GreenSlashEffect != null) ? "Ready" : "NULL") + ", BlackCircleEffect: " + ((BlackCircleEffect != null) ? "Ready" : "NULL") + ", SlashSound: " + ((SlashSound != null) ? "Ready" : "NULL"))); Vector3 val2 = ((Component)((AbilityInstance)this).owner).transform.position; if ((Object)(object)((AbilityInstance)this).owner.collider != (Object)null) { Bounds bounds = ((Collider2D)((AbilityInstance)this).owner.collider).bounds; val2 = ((Bounds)(ref bounds)).center; } float num2 = (((int)((AbilityInstance)this).owner.lookingDirection == 1) ? (-1f) : 1f); val2.x += num2 * 1.5f; float num3 = ((num >= 4) ? 1.1f : 0.7f); MonoBehaviour val3 = null; MonoBehaviour val4 = null; EffectInfo val5 = GreenSlashEffect ?? SlashEffect; if (val5 != null) { try { EffectPoolInstance val6 = val5.Spawn(val2, 0f, num3); val3 = (MonoBehaviour)(object)val6; if ((Object)(object)val3 != (Object)null) { if (!((Component)val3).gameObject.activeSelf) { Debug.Log((object)"[ChzzkSkul] GuanYu GreenSlashEffect spawned inactive! Forcing SetActive(true)."); ((Component)val3).gameObject.SetActive(true); } SpriteRenderer component = ((Component)val3).GetComponent<SpriteRenderer>(); if ((Object)(object)component != (Object)null) { ((Renderer)component).enabled = true; } Animator component2 = ((Component)val3).GetComponent<Animator>(); if ((Object)(object)component2 != (Object)null) { ((Behaviour)component2).enabled = true; } Debug.Log((object)$"[ChzzkSkul] GuanYu GreenSlashEffect spawned successfully at {val2} (scale {num3})"); } else { Debug.LogWarning((object)"[ChzzkSkul] GuanYu GreenSlashEffect Spawn returned null!"); } } catch (Exception ex) { Debug.LogError((object)("[ChzzkSkul] Failed to spawn GuanYu GreenSlashEffect: " + ex)); } } else { Debug.LogWarning((object)"[ChzzkSkul] GuanYu GreenSlashEffect is null, cannot spawn green visual!"); } if (BlackCircleEffect != null) { try { EffectPoolInstance val7 = BlackCircleEffect.Spawn(val2, 0f, num3); val4 = (MonoBehaviour)(object)val7; if ((Object)(object)val4 != (Object)null) { if (!((Component)val4).gameObject.activeSelf) { Debug.Log((object)"[ChzzkSkul] GuanYu BlackCircleEffect spawned inactive! Forcing SetActive(true)."); ((Component)val4).gameObject.SetActive(true); } SpriteRenderer component3 = ((Component)val4).GetComponent<SpriteRenderer>(); if ((Object)(object)component3 != (Object)null) { ((Renderer)component3).enabled = true; } Animator component4 = ((Component)val4).GetComponent<Animator>(); if ((Object)(object)component4 != (Object)null) { ((Behaviour)component4).enabled = true; } Debug.Log((object)$"[ChzzkSkul] GuanYu BlackCircleEffect spawned successfully at {val2} (scale {num3})"); } else { Debug.LogWarning((object)"[ChzzkSkul] GuanYu BlackCircleEffect Spawn returned null!"); } } catch (Exception ex2) { Debug.LogError((object)("[ChzzkSkul] Failed to spawn GuanYu BlackCircleEffect: " + ex2)); } } else { Debug.LogWarning((object)"[ChzzkSkul] GuanYu BlackCircleEffect is null, cannot spawn black visual!"); } if (SlashSound != null) { try { PersistentSingleton<SoundManager>.Instance.PlaySound(SlashSound, val2); Debug.Log((object)$"[ChzzkSkul] GuanYu SlashSound played successfully at {val2}"); } catch (Exception ex3) { Debug.LogError((object)("[ChzzkSkul] Failed to play GuanYu SlashSound: " + ex3)); } } else { Debug.LogWarning((object)"[ChzzkSkul] GuanYu SlashSound is null, cannot play audio!"); } ((MonoBehaviour)((AbilityInstance)this).owner).StartCoroutine(PerformContinuousSlash(val3 ?? val4, ((AbilityInstance)this).owner.lookingDirection, baseMultiplier, num3, val2)); } private IEnumerator PerformContinuousSlash(MonoBehaviour spawnedEffect, LookingDirection direction, double baseMultiplier, float visualScale, Vector3 spawnPos) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) float duration = 0.25f; float elapsed = 0f; HashSet<Character> alreadyHit = new HashSet<Character>(); while (elapsed < duration && !((Object)(object)((AbilityInstance)this).owner == (Object)null) && !((Object)(object)((Component)((AbilityInstance)this).owner).gameObject == (Object)null) && !((Object)(object)((AbilityInstance)this).owner.health == (Object)null) && !((Health)((AbilityInstance)this).owner.health).dead) { Vector3 slashCenter = (((Object)(object)spawnedEffect != (Object)null && (Object)(object)((Component)spawnedEffect).gameObject != (Object)null) ? ((Component)spawnedEffect).transform.position : spawnPos); try { Collider2D[] colliders = Physics2D.OverlapCircleAll(Vector2.op_Implicit(slashCenter), 12f * visualScale); Collider2D[] array = colliders; foreach (Collider2D c in array) { if ((Object)(object)c == (Object)null) { continue; } Character enemy = ((Component)c).GetComponentInParent<Character>(); if (!((Object)(object)enemy != (Object)null) || (int)enemy.type == 6 || (int)enemy.type == 7 || !((Object)(object)enemy.health != (Object)null) || ((Health)enemy.health).dead || alreadyHit.Contains(enemy)) { continue; } float dx = ((Component)enemy).transform.position.x - slashCenter.x; float dy = Mathf.Abs(((Component)enemy).transform.position.y - slashCenter.y); float minDx = -7.5f * visualScale; float maxDx = 7.5f * visualScale; float maxDy = 5f * visualScale; if (dx >= minDx && dx <= maxDx && dy <= maxDy) { alreadyHit.Add(enemy); double currentMultiplier = baseMultiplier; if (((Health)enemy.health).percent <= 0.5) { currentMultiplier *= 1.5; } double physPower = ((AbilityInstance)this).owner.stat.GetFinal(Kind.PhysicalAttackDamage); Damage slashDmg = new Damage(Attacker.op_Implicit(((AbilityInstance)this).owner), 35.0 * currentMultiplier * physPower, Vector2.op_Implicit(((Component)enemy).transform.position), (Attribute)0, (AttackType)4, (MotionType)0, "GuanYuSlash", 1.0, 0f, 0.0, 1.0, 1.0, true, false, 0.0, 0.0, (short)0, (PriorityList<bool>)null, 1.0); try { ((AbilityInstance)this).owner.Attack(enemy, ref slashDmg); Debug.Log((object)$"[ChzzkSkul] GuanYu attacked enemy {((Object)enemy).name} for {35.0 * currentMultiplier} damage (continuous slash, elapsed {elapsed}s)."); } catch (Exception ex) { Debug.LogError((object)("[ChzzkSkul] Failed to execute Attack on enemy: " + ex)); } } } } catch (Exception ex2) { Debug.LogError((object)("[ChzzkSkul] GuanYu continuous overlap search exception: " + ex2)); } elapsed += Time.deltaTime; yield return null; } } } public static EffectInfo SlashEffect; public static EffectInfo GreenSlashEffect; public static EffectInfo BlackCircleEffect; public static SoundInfo SlashSound; public override IAbilityInstance CreateInstance(Character owner) { return (IAbilityInstance)(object)new Instance(owner, this); } public object Clone() { return new GuanYuCrescentBladeAbility { _defaultIcon = base._defaultIcon }; } } public sealed class ZeusHammerAbilityComponent : AbilityComponent<ZeusHammerAbility> { public override void Initialize() { base.Initialize(); } } [Serializable] public class ZeusHammerAbility : Ability, ICloneable { public class Instance : AbilityInstance<ZeusHammerAbility> { private float _timer = 0f; private const float Interval = 0.4f; public Instance(Character owner, ZeusHammerAbility ability) : base(owner, ability) { } public override void OnAttach() { } public override void OnDetach() { } public override void UpdateTime(float deltaTime) { ((AbilityInstance)this).UpdateTime(deltaTime); _timer += deltaTime; if (_timer >= 0.4f) { _timer = 0f; TriggerLightning(); } } private void TriggerLightning() { //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)((AbilityInstance)this).owner == (Object)null || (Object)(object)((Component)((AbilityInstance)this).owner).gameObject == (Object)null || (Object)(object)((AbilityInstance)this).owner.health == (Object)null || ((Health)((AbilityInstance)this).owner.health).dead) { return; } Collider2D[] source = Physics2D.OverlapCircleAll(Vector2.op_Implicit(((Component)((AbilityInstance)this).owner).transform.position), 7f); List<Character> list = (from c in source select ((Object)(object)c != (Object)null) ? ((Component)c).GetComponentInParent<Character>() : null into c where (Object)(object)c != (Object)null && (int)c.type != 6 && (int)c.type != 7 && (Object)(object)c.health != (Object)null && !((Health)c.health).dead select c).Distinct().ToList(); if (list.Count > 0) { int index = Random.Range(0, list.Count); Character val = list[index]; double final = ((AbilityInstance)this).owner.stat.GetFinal(Kind.MagicAttackDamage); Damage val2 = default(Damage); ((Damage)(ref val2))..ctor(Attacker.op_Implicit(((AbilityInstance)this).owner), 35.0 * final, Vector2.op_Implicit(((Component)val).transform.position), (Attribute)1, (AttackType)4, (MotionType)0, "ZeusLightning", 1.0, 0f, 0.0, 1.0, 1.0, true, false, 0.0, 0.0, (short)0, (PriorityList<bool>)null, 1.0); ((AbilityInstance)this).owner.Attack(val, ref val2); if (LightningEffect != null) { LightningEffect.Spawn(((Component)val).transform.position, 0f, 1f); } if (LightningSound != null) { PersistentSingleton<SoundManager>.Instance.PlaySound(LightningSound, ((Component)val).transform.position); } } } } public static EffectInfo LightningEffect; public static SoundInfo LightningSound; public override IAbilityInstance CreateInstance(Character owner) { return (IAbilityInstance)(object)new Instance(owner, this); } public object Clone() { return new ZeusHammerAbility { _defaultIcon = base._defaultIcon }; } } public sealed class MedjedCloakAbilityComponent : AbilityComponent<MedjedCloakAbility> { public override void Initialize() { base.Initialize(); } } [Serializable] public class MedjedCloakAbility : Ability, ICloneable { public class Instance : AbilityInstance<MedjedCloakAbility> { public Instance(Character owner, MedjedCloakAbility ability) : base(owner, ability) { } public override void OnAttach() { IsActive = true; } public override void OnDetach() { IsActive = false; } } public static bool IsActive; public override IAbilityInstance CreateInstance(Character owner) { return (IAbilityInstance)(object)new Instance(owner, this); } public object Clone() { return new MedjedCloakAbility { _defaultIcon = base._defaultIcon }; } } public sealed class VirusAbilityComponent : AbilityComponent<VirusAbility> { public override void Initialize() { base.Initialize(); } } [Serializable] public class VirusAbility : Ability, ICloneable { public class Instance : AbilityInstance<VirusAbility> { private float _timer = 0f; private const float Interval = 10f; public Instance(Character owner, VirusAbility ability) : base(owner, ability) { } public override void OnAttach() { } public override void OnDetach() { } public override void UpdateTime(float deltaTime) { ((AbilityInstance)this).UpdateTime(deltaTime); _timer += deltaTime; if (_timer >= 10f) { _timer = 0f; TriggerVirusDamage(); } } private void TriggerVirusDamage() { if (!((Object)(object)((AbilityInstance)this).owner == (Object)null) && !((Object)(object)((AbilityInstance)this).owner.health == (Object)null) && !((Health)((AbilityInstance)this).owner.health).dead) { ((Health)((AbilityInstance)this).owner.health).TakeHealth(0.5); ChzzkCardSynergy.ShowFloatingText("諛붿씠?ъ뒪 ?④낵濡?泥대젰??0.5 媛먯냼?덉뒿?덈떎."); } } } public override IAbilityInstance CreateInstance(Character owner) { return (IAbilityInstance)(object)new Instance(owner, this); } public object Clone() { return new VirusAbility { _defaultIcon = base._defaultIcon }; } } public sealed class ChallengersBeltAbilityComponent : AbilityComponent<ChallengersBeltAbility> { public override void Initialize() { base.Initialize(); } } [Serializable] public class ChallengersBeltAbility : Ability, ICloneable { public class Instance : AbilityInstance<ChallengersBeltAbility> { public Instance(Character owner, ChallengersBeltAbility ability) : base(owner, ability) { } public override void OnAttach() { IsActive = true; } public override void OnDetach() { IsActive = false; } } public static bool IsActive; public override IAbilityInstance CreateInstance(Character owner) { return (IAbilityInstance)(object)new Instance(owner, this); } public object Clone() { return new ChallengersBeltAbility { _defaultIcon = base._defaultIcon }; } } [Serializable] public sealed class BrokenHeartEvolveBehavior : MonoBehaviour { [SerializeField] private Item _item = null; private void Update() { Character player = Singleton<Service>.Instance.levelManager.player; if (!((Object)(object)player == (Object)null) && player.playerComponents != null && player.playerComponents.inventory != null) { List<Quintessence> items = player.playerComponents.inventory.quintessence.items; if (items.Any((Quintessence q) => (Object)(object)q != (Object)null && ((Object)q).name.Equals("Succubus", StringComparison.OrdinalIgnoreCase))) { ChangeItem(); } } } private void ChangeItem() { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Invalid comparison between Unknown and I4 //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) ItemReference val = default(ItemReference); if (GearResource.instance.TryGetItemReferenceByName(((Object)_item).name + "_2", ref val)) { ItemRequest val2 = val.LoadAsync(); ((Request<Item>)(object)val2).WaitForCompletion(); if ((int)((Gear)_item).state == 1) { Character player = Singleton<Service>.Instance.levelManager.player; Vector3 val3 = (((Object)(object)player != (Object)null) ? ((Component)player).transform.position : ((Component)_item).transform.position); Item val4 = Singleton<Service>.Instance.levelManager.DropItem(val2, val3); _item.ChangeOnInventory(val4); } } } } [Serializable] public sealed class SmallTwigEvolveBehavior : MonoBehaviour { [SerializeField] private Item _item = null; private bool _hasEquipped = false; private Character player; private void Awake() { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Expected O, but got Unknown player = Singleton<Service>.Instance.levelManager.player; _hasEquipped = false; player.playerComponents.inventory.weapon.onSwap += CheckEvolveCondition; player.playerComponents.inventory.weapon.onChanged += new OnChangeDelegate(OnSkullChanged); } private void OnDestroy() { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown if ((Object)(object)player != (Object)null && player.playerComponents != null && player.playerComponents.inventory != null) { player.playerComponents.inventory.weapon.onSwap -= CheckEvolveCondition; player.playerComponents.inventory.weapon.onChanged -= new OnChangeDelegate(OnSkullChanged); } } private void Update() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 if ((int)((Gear)_item).state == 1 && !_hasEquipped) { CheckEvolveCondition(); _hasEquipped = true; } } private void OnSkullChanged(Weapon old, Weapon @new) { CheckEvolveCondition(); } private void CheckEvolveCondition() { Weapon current = player.playerComponents.inventory.weapon.current; if ((Object)(object)current != (Object)null && (((Object)current).name.Equals("Skul", StringComparison.OrdinalIgnoreCase) || ((Object)current).name.Equals("HeroSkul", StringComparison.OrdinalIgnoreCase))) { ChangeItem(); } } private void ChangeItem() { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Invalid comparison between Unknown and I4 //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) ItemReference val = default(ItemReference); if (GearResource.instance.TryGetItemReferenceByName(((Object)_item).name + "_2", ref val)) { ItemRequest val2 = val.LoadAsync(); ((Request<Item>)(object)val2).WaitForCompletion(); if ((int)((Gear)_item).state == 1) { Vector3 val3 = (((Object)(object)player != (Object)null) ? ((Component)player).transform.position : ((Component)_item).transform.position); Item val4 = Singleton<Service>.Instance.levelManager.DropItem(val2, val3); _item.ChangeOnInventory(val4); } } } } [Serializable] public sealed class SmallTwigRevertBehavior : MonoBehaviour { [SerializeField] private Item _item = null; private bool _hasEquipped = false; private Character player; private void Awake() { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Expected O, but got Unknown player = Singleton<Service>.Instance.levelManager.player; _hasEquipped = false; player.playerComponents.inventory.weapon.onSwap += CheckRevertCondition; player.playerComponents.inventory.weapon.onChanged += new OnChangeDelegate(OnSkullChanged); } private void OnDestroy() { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown if ((Object)(object)player != (Object)null && player.playerComponents != null && player.playerComponents.inventory != null) { player.playerComponents.inventory.weapon.onSwap -= CheckRevertCondition; player.playerComponents.inventory.weapon.onChanged -= new OnChangeDelegate(OnSkullChanged); } } private void Update() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 if ((int)((Gear)_item).state == 1 && !_hasEquipped) { CheckRevertCondition(); _hasEquipped = true; } } private void OnSkullChanged(Weapon old, Weapon @new) { CheckRevertCondition(); } private void CheckRevertCondition() { Weapon current = player.playerComponents.inventory.weapon.current; if ((Object)(object)current != (Object)null && !((Object)current).name.Equals("Skul", StringComparison.OrdinalIgnoreCase) && !((Object)current).name.Equals("HeroSkul", StringComparison.OrdinalIgnoreCase)) { ChangeItem(); } } private void ChangeItem() { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Invalid comparison between Unknown and I4 //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) string text = ((Object)_item).name; if (text.EndsWith("_2")) { text = text.Substring(0, text.Length - 2); } ItemReference val = default(ItemReference); if (GearResource.instance.TryGetItemReferenceByName(text, ref val)) { ItemRequest val2 = val.LoadAsync(); ((Request<Item>)(object)val2).WaitForCompletion(); if ((int)((Gear)_item).state == 1) { Vector3 val3 = (((Object)(object)player != (Object)null) ? ((Component)player).transform.position : ((Component)_item).transform.position); Item val4 = Singleton<Service>.Instance.levelManager.DropItem(val2, val3); _item.ChangeOnInventory(val4); } } } } [Serializable] public sealed class ScaleOfTheOtherworldBehavior : MonoBehaviour { [SerializeField] private Item _item = null; private void Awake() { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown //IL_004a: 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_00cb: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_item == (Object)null) { _item = ((Component)this).GetComponentInParent<Item>() ?? ((Component)this).GetComponent<Item>(); } if (!((Object)(object)_item == (Object)null)) { BonusKeyword val = new BonusKeyword(); val.type = (Type)0; val.count = 1; _item.bonusKeyword = (BonusKeyword[])(object)new BonusKeyword[1] { val }; Key[] array = new Key[36]; RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); Key[] array2 = (Key[])(object)array; Random random = new Random(); int num = random.Next(array2.Length); int num2; for (num2 = random.Next(array2.Length); num2 == num; num2 = random.Next(array2.Length)) { } _item.keyword1 = array2[num]; _item.keyword2 = array2[num2]; } } } [Serializable] public sealed class CardFoolBehavior : MonoBehaviour { [SerializeField] private Item _item = null; private bool _isHooked = false; private Character _lastOwner = null; private Values _extraStats = null; private Values _dashStats = null; private bool _hasDashCharge = false; private bool _lastIsSuper = false; private bool _lastIsEnhanced = false; private Random _rnd = new Random(); private void Awake() { if ((Object)(object)_item == (Object)null) { _item = ((Component)this).GetComponentInParent<Item>() ?? ((Component)this).GetComponent<Item>(); } } private void Update() { //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Expected O, but got Unknown //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Expected O, but got Unknown //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Expected O, but got Unknown if ((Object)(object)_item == (Object)null || (Object)(object)((Gear)_item).owner == (Object)null) { ClearStats(); Unsubscribe(); return; } if ((Object)(object)((Gear)_item).owner != (Object)(object)_lastOwner) { Unsubscribe(); _lastOwner = ((Gear)_item).owner; Subscribe(); } bool flag = ChzzkCardSynergy.IsCardSynergySuper(_item); bool flag2 = ChzzkCardSynergy.GetCardCount(_item) >= 6; if (_extraStats == null || flag != _lastIsSuper || flag2 != _lastIsEnhanced) { ClearStats(); _lastIsSuper = flag; _lastIsEnhanced = flag2; List<Value> list = new List<Value>(); if (!flag) { double num = (flag2 ? 0.3 : 0.2); list.Add(new Value(Category.PercentPoint, Kind.MovementSpeed, num)); } else { list.Add(new Value(Category.PercentPoint, Kind.MovementSpeed, -0.1)); } if (list.Count > 0) { _extraStats = new Values(list.ToArray()); ((Gear)_item).owner.stat.AttachValues(_extraStats); ((Gear)_item).owner.stat.SetNeedUpdate(); } } } private void Subscribe() { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Expected O, but got Unknown if ((Object)(object)_lastOwner == (Object)null) { return; } try { _lastOwner.onStartAction += OnStartAction; ((PriorityList<GiveDamageDelegate>)(object)_lastOwner.onGiveDamage).Add(100, new GiveDamageDelegate(OnGiveDamage)); _isHooked = true; } catch { } } private void Unsubscribe() { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown if ((Object)(object)_lastOwner == (Object)null || !_isHooked) { return; } try { _lastOwner.onStartAction -= OnStartAction; ((PriorityList<GiveDamageDelegate>)(object)_lastOwner.onGiveDamage).Remove(new GiveDamageDelegate(OnGiveDamage)); _isHooked = false; } catch { } } private void OnStartAction(Action action) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)action == (Object)null) && (int)action.type == 0 && !((Object)(object)_lastOwner == (Object)null) && _lastIsSuper) { ((MonoBehaviour)this).StartCoroutine(C_FoolDashBuff()); } } private IEnumerator C_FoolDashBuff() { if (!((Object)(object)_lastOwner == (Object)null) && _dashStats == null) { double speed = (_lastIsEnhanced ? 0.7 : 0.5); float duration = (_lastIsEnhanced ? 1.5f : 1f); _dashStats = new Values((Value[])(object)new Value[1] { new Value(Category.PercentPoint, Kind.MovementSpeed, speed) }); _lastOwner.stat.AttachValues(_dashStats); _lastOwner.stat.SetNeedUpdate(); _hasDashCharge = true; yield return (object)new WaitForSeconds(duration); if ((Object)(object)_lastOwner != (Object)null && _dashStats != null) { _lastOwner.stat.DetachValues(_dashStats); _lastOwner.stat.SetNeedUpdate(); _dashStats = null; } _hasDashCharge = false; } } private bool OnGiveDamage(ITarget target, ref Damage damage) { if (_hasDashCharge && (Object)(object)_lastOwner != (Object)null) { _hasDashCharge = false; double num = (_lastIsEnhanced ? 2.5 : 2.0); damage.multiplier *= num; ChzzkCardSynergy.ShowFloatingText(PluginItems.IsKorean() ? "[??쐞移?愿묐?] ?\u0080誘몄? 利앺룺!" : "[Reversed Fool] Damage Amplified!"); if (_dashStats != null && (Object)(object)_lastOwner != (Object)null) { try { _lastOwner.stat.DetachValues(_dashStats); _lastOwner.stat.SetNeedUpdate(); } catch { } _dashStats = null; } } return false; } private void ClearStats() { if ((Object)(object)_lastOwner != (Object)null) { if (_extraStats != null) { try { _lastOwner.stat.DetachValues(_extraStats); } catch { } } if (_dashStats != null) { try { _lastOwner.stat.DetachValues(_dashStats); } catch { } } try { _lastOwner.stat.SetNeedUpdate(); } catch { } } _extraStats = null; _dashStats = null; _hasDashCharge = false; } private void OnDestroy() { ClearStats(); Unsubscribe(); } } [Serializable] public sealed class CardMagicianBehavior : MonoBehaviour { [SerializeField] private Item _item = null; private bool _isHooked = false; private Character _lastOwner = null; private Values _extraStats = null; private bool _lastIsSuper = false; private bool _lastIsEnhanced = false; private Random _rnd = new Random(); private void Awake() { if ((Object)(object)_item == (Object)null) { _item = ((Component)this).GetComponentInParent<Item>() ?? ((Component)this).GetComponent<Item>(); } } private void Update() { //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Expected O, but got Unknown //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Expected O, but got Unknown //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Expected O, but got Unknown //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Expected O, but got Unknown if ((Object)(object)_item == (Object)null || (Object)(object)((Gear)_item).owner == (Object)null) { ClearStats(); Unsubscribe(); return; } if ((Object)(object)((Gear)_item).owner != (Object)(object)_lastOwner) { Unsubscribe(); _lastOwner = ((Gear)_item).owner; Subscribe(); } bool flag
ChzzkController.dll
Decompiled 11 hours agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: IgnoresAccessChecksTo("Plugins.Common")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ChzzkSkul { [BepInPlugin("com.slibul.chzzkskulcontroller", "ChzzkSkulController", "1.1.8")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class PluginController : BaseUnityPlugin { public static ManualLogSource Log; public static ConfigEntry<bool> EnableItemsMode; public static ConfigEntry<bool> EnableStreamerMode; public static ConfigEntry<KeyCode> ToggleKey; private bool _showWindow = false; private Rect _windowRect = new Rect(150f, 150f, 380f, 260f); private GUIStyle _windowStyle; private GUIStyle _labelStyle; private GUIStyle _buttonStyle; private GUIStyle _toggleStyle; private GUIStyle _titleStyle; private bool _styleInitialized = false; private void Awake() { Log = ((BaseUnityPlugin)this).Logger; EnableItemsMode = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "아이템 모드 활성화", true, "커스텀 아이템/스컬/각인 등의 콘텐츠 기능을 켜거나 끕니다."); EnableStreamerMode = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "스트리머 모드 활성화", true, "치지직/유튜브 실시간 채팅 및 후원 연동 기능을 켜거나 끕니다."); ToggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("General", "메뉴 단축키", (KeyCode)108, "컨트롤러 메뉴 창을 열고 닫는 단축키입니다."); Log.LogInfo((object)"ChzzkSkulController initialized. Appling initial states..."); try { PluginItems.SetEnabled(EnableItemsMode.Value); } catch (Exception ex) { Log.LogError((object)("Failed to apply initial ItemsMode: " + ex)); } try { Plugin.SetEnabled(EnableStreamerMode.Value); } catch (Exception ex2) { Log.LogError((object)("Failed to apply initial StreamerMode: " + ex2)); } Log.LogInfo((object)"ChzzkSkulController loaded successfully!"); } private void Update() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (!Input.GetKeyDown(ToggleKey.Value)) { return; } _showWindow = !_showWindow; if (!_showWindow) { ((BaseUnityPlugin)this).Config.Save(); try { Plugin.ReloadAndReconnect(); } catch (Exception ex) { Log.LogError((object)("Failed to reload and reconnect: " + ex)); } } } private void OnGUI() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) if (_showWindow) { InitStyles(); _windowRect = GUI.Window(9998, _windowRect, new WindowFunction(DrawWindow), "ChzzkSkul 통합 컨트롤러", _windowStyle); } } private Texture2D MakeRoundedTex(int width, int height, Color col, int radius) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) Texture2D val = new Texture2D(width, height, (TextureFormat)4, false); Color[] array = (Color[])(object)new Color[width * height]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { bool flag = false; float num = 0f; if (j < radius && i < radius) { flag = true; num = Vector2.Distance(new Vector2((float)j, (float)i), new Vector2((float)radius, (float)radius)); } else if (j >= width - radius && i < radius) { flag = true; num = Vector2.Distance(new Vector2((float)j, (float)i), new Vector2((float)(width - radius - 1), (float)radius)); } else if (j < radius && i >= height - radius) { flag = true; num = Vector2.Distance(new Vector2((float)j, (float)i), new Vector2((float)radius, (float)(height - radius - 1))); } else if (j >= width - radius && i >= height - radius) { flag = true; num = Vector2.Distance(new Vector2((float)j, (float)i), new Vector2((float)(width - radius - 1), (float)(height - radius - 1))); } if (flag && num > (float)radius) { array[i * width + j] = Color.clear; } else { array[i * width + j] = col; } } } val.SetPixels(array); val.Apply(); ((Object)val).hideFlags = (HideFlags)61; return val; } private void InitStyles() { //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Expected O, but got Unknown //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Expected O, but got Unknown //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: Expected O, but got Unknown //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Expected O, but got Unknown //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Expected O, but got Unknown //IL_024f: Unknown result type (might be due to invalid IL or missing references) //IL_026d: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Expected O, but got Unknown //IL_02bd: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Unknown result type (might be due to invalid IL or missing references) //IL_0301: Unknown result type (might be due to invalid IL or missing references) //IL_030b: Expected O, but got Unknown //IL_0316: Unknown result type (might be due to invalid IL or missing references) if (!_styleInitialized) { _styleInitialized = true; Color col = default(Color); ((Color)(ref col))..ctor(0.1f, 0.08f, 0.14f, 0.96f); Color col2 = default(Color); ((Color)(ref col2))..ctor(0.22f, 0.13f, 0.32f, 1f); Color col3 = default(Color); ((Color)(ref col3))..ctor(0.35f, 0.2f, 0.5f, 1f); Color col4 = default(Color); ((Color)(ref col4))..ctor(0.28f, 0.18f, 0.38f, 1f); Color textColor = default(Color); ((Color)(ref textColor))..ctor(1f, 0.85f, 0.4f, 1f); Color textColor2 = default(Color); ((Color)(ref textColor2))..ctor(0.9f, 0.9f, 0.95f, 1f); int num = 32; int num2 = 12; _windowStyle = new GUIStyle(GUI.skin.window); _windowStyle.normal.background = MakeRoundedTex(num, num, col, num2); _windowStyle.onNormal.background = MakeRoundedTex(num, num, col, num2); _windowStyle.border = new RectOffset(num2, num2, num2, num2); _windowStyle.normal.textColor = textColor; _windowStyle.onNormal.textColor = textColor; _windowStyle.fontSize = 17; _windowStyle.fontStyle = (FontStyle)1; _windowStyle.padding = new RectOffset(15, 15, 35, 15); _windowStyle.alignment = (TextAnchor)1; _titleStyle = new GUIStyle(GUI.skin.label); _titleStyle.fontSize = 15; _titleStyle.fontStyle = (FontStyle)1; _titleStyle.normal.textColor = textColor; _titleStyle.alignment = (TextAnchor)4; _labelStyle = new GUIStyle(GUI.skin.label); _labelStyle.fontSize = 14; _labelStyle.normal.textColor = textColor2; _labelStyle.alignment = (TextAnchor)3; int num3 = 6; _buttonStyle = new GUIStyle(GUI.skin.button); _buttonStyle.normal.background = MakeRoundedTex(num, num, col2, num3); _buttonStyle.hover.background = MakeRoundedTex(num, num, col3, num3); _buttonStyle.active.background = MakeRoundedTex(num, num, col4, num3); _buttonStyle.border = new RectOffset(num3, num3, num3, num3); _buttonStyle.normal.textColor = textColor2; _buttonStyle.hover.textColor = Color.white; _buttonStyle.fontSize = 14; _buttonStyle.fontStyle = (FontStyle)1; _toggleStyle = new GUIStyle(GUI.skin.toggle); _toggleStyle.normal.textColor = textColor2; _toggleStyle.fontSize = 14; } } private void DrawWindow(int windowID) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) GUILayout.Space(10f); GUILayout.Label($"{ToggleKey.Value} 키로 이 창을 열고 닫을 수 있습니다.", _titleStyle, Array.Empty<GUILayoutOption>()); GUILayout.Space(15f); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("아이템 모드 (Items, Skulls, Inscriptions)", _labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(240f) }); bool flag = GUILayout.Toggle(EnableItemsMode.Value, EnableItemsMode.Value ? " ON" : " OFF", _toggleStyle, Array.Empty<GUILayoutOption>()); if (flag != EnableItemsMode.Value) { EnableItemsMode.Value = flag; try { PluginItems.SetEnabled(flag); } catch (Exception ex) { Log.LogError((object)("Failed to toggle ItemsMode: " + ex)); } } GUILayout.EndHorizontal(); GUILayout.Space(10f); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("스트리머 모드 (Chzzk/YT Live, Chat & Don)", _labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(240f) }); bool flag2 = GUILayout.Toggle(EnableStreamerMode.Value, EnableStreamerMode.Value ? " ON" : " OFF", _toggleStyle, Array.Empty<GUILayoutOption>()); if (flag2 != EnableStreamerMode.Value) { EnableStreamerMode.Value = flag2; try { Plugin.SetEnabled(flag2); } catch (Exception ex2) { Log.LogError((object)("Failed to toggle StreamerMode: " + ex2)); } } GUILayout.EndHorizontal(); GUILayout.Space(25f); if (GUILayout.Button("설정 저장 및 닫기", _buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(38f) })) { ((BaseUnityPlugin)this).Config.Save(); _showWindow = false; try { Plugin.ReloadAndReconnect(); } catch (Exception ex3) { Log.LogError((object)("Failed to reload and reconnect: " + ex3)); } } GUI.DragWindow(); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "ChzzkController"; public const string PLUGIN_NAME = "ChzzkController"; public const string PLUGIN_VERSION = "1.1.8"; } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } }
ChzzkStream.dll
Decompiled 11 hours 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.Diagnostics; using System.IO; using System.Linq; using System.Net.Security; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Characters; using Characters.AI; using Characters.AI.Behaviours; using Characters.AI.TwinSister; using Characters.Abilities; using Characters.Abilities.Darks; using Characters.Abilities.Debuffs; using Characters.Actions; using Characters.Gear; using Characters.Gear.Fragments; using Characters.Gear.Items; using Characters.Gear.Quintessences; using Characters.Gear.Synergy; using Characters.Gear.Synergy.Inscriptions; using Characters.Gear.Upgrades; using Characters.Gear.Weapons; using Characters.Player; using Cysharp.Threading.Tasks; using Cysharp.Threading.Tasks.CompilerServices; using Data; using GameResources; using Hardmode; using HarmonyLib; using Level; using Level.Altars; using Level.Npc.FieldNpcs; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Services; using Singletons; using UnityEngine; using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets.ResourceLocators; using UnityEngine.Events; using UnityEngine.Networking; using UnityEngine.Rendering; using UnityEngine.Rendering.Universal; using UnityEngine.ResourceManagement.AsyncOperations; using UnityEngine.SceneManagement; using UnityEngine.UI; using WebSocketSharp; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: IgnoresAccessChecksTo("Plugins.Common")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } public class BypassCertificate : CertificateHandler { public override bool ValidateCertificate(byte[] certificateData) { return true; } } public class ChzzkUnity : MonoBehaviour { private enum SslProtocolsHack { Tls = 192, Tls11 = 768, Tls12 = 3072 } [Serializable] public class LiveStatus { [Serializable] public class Content { public string liveTitle; public string status; public int concurrentUserCount; public int accumulateCount; public bool paidPromotion; public bool adult; public string chatChannelId; public string categoryType; public string liveCategory; public string liveCategoryValue; public string livePollingStatusJson; public string faultStatus; public string userAdultStatus; public bool chatActive; public string chatAvailableGroup; public string chatAvailableCondition; public int minFollowerMinute; } public int code; public string message; public Content content; } [Serializable] public class AccessTokenResult { [Serializable] public class Content { [Serializable] public class TemporaryRestrict { public bool temporaryRestrict; public int times; public int duration; public int createdTime; } public string accessToken; public bool realNameAuth; public string extraToken; } public int code; public string message; public Content content; } [Serializable] public class Profile { [Serializable] public class StreamingProperty { } public string userIdHash; public string nickname; public string profileImageUrl; public string userRoleCode; public string badge; public string title; public string verifiedMark; public List<string> activityBadges; public StreamingProperty streamingProperty; } [Serializable] public class SubscriptionExtras { public int month; public string tierName; public string nickname; public int tierNo; } [Serializable] public class DonationExtras { [Serializable] public class WeeklyRank { public string userIdHash; public string nickName; public bool verifiedMark; public int donationAmount; public int ranking; } private object emojis; public bool isAnonymous; public string payType; public int payAmount; public string streamingChannelId; public string nickname; public string osType; public string donationType; public List<WeeklyRank> weeklyRankList; public WeeklyRank donationUserWeeklyRank; } [Serializable] public class ChannelInfo { [Serializable] public class Content { public string channelId; public string channelName; public string channelImageUrl; public bool verifiedMark; public string channelType; public string channelDescription; public int followerCount; public bool openLive; } public int code; public string message; public Content content; } [CompilerGenerated] private sealed class <Connect>d__31 : IAsyncStateMachine { public int <>1__state; public AsyncUniTaskMethodBuilder <>t__builder; public ChzzkUnity <>4__this; private LiveStatus <liveStatus>5__1; private AccessTokenResult <accessTokenResult>5__2; private SslProtocols <sslProtocolHack>5__3; private LiveStatus <>s__4; private AccessTokenResult <>s__5; private Exception <ex>5__6; private Awaiter<LiveStatus> <>u__1; private Awaiter<AccessTokenResult> <>u__2; private Awaiter <>u__3; private void MoveNext() { //IL_04c1: Unknown result type (might be due to invalid IL or missing references) //IL_04c6: Unknown result type (might be due to invalid IL or missing references) //IL_04db: Unknown result type (might be due to invalid IL or missing references) //IL_04dd: Unknown result type (might be due to invalid IL or missing references) //IL_04f8: Unknown result type (might be due to invalid IL or missing references) //IL_04fd: Unknown result type (might be due to invalid IL or missing references) //IL_0505: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01e2: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_030a: Unknown result type (might be due to invalid IL or missing references) //IL_0314: Expected O, but got Unknown //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; try { Awaiter val3; if ((uint)num <= 1u || num != 2) { try { Awaiter<AccessTokenResult> val; Awaiter<LiveStatus> val2; if (num != 0) { if (num == 1) { val = <>u__2; <>u__2 = default(Awaiter<AccessTokenResult>); num = (<>1__state = -1); goto IL_0233; } if (<>4__this.socket != null && <>4__this.socket.IsAlive) { <>4__this.socket.Close(); <>4__this.socket = null; } Debug.Log((object)("[ChzzkUnity] Connecting to channel: " + <>4__this.channel)); val2 = <>4__this.GetLiveStatus(<>4__this.channel).GetAwaiter(); if (!val2.IsCompleted) { num = (<>1__state = 0); <>u__1 = val2; <Connect>d__31 <Connect>d__ = this; ((AsyncUniTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<Awaiter<LiveStatus>, <Connect>d__31>(ref val2, ref <Connect>d__); return; } } else { val2 = <>u__1; <>u__1 = default(Awaiter<LiveStatus>); num = (<>1__state = -1); } <>s__4 = val2.GetResult(); <liveStatus>5__1 = <>s__4; <>s__4 = null; if (<liveStatus>5__1 == null) { Debug.LogError((object)"[ChzzkUnity] 라이브 상태 데이터를 가져오지 못했습니다. 연결을 중단합니다."); } else if (<liveStatus>5__1.content == null) { Debug.LogError((object)$"[ChzzkUnity] 라이브 상태 content가 null입니다. (코드: {<liveStatus>5__1.code}, 메시지: {<liveStatus>5__1.message}). 연결을 중단합니다."); } else { <>4__this.cid = <liveStatus>5__1.content.chatChannelId; if (!string.IsNullOrEmpty(<>4__this.cid)) { val = <>4__this.GetAccessToken(<>4__this.cid).GetAwaiter(); if (!val.IsCompleted) { num = (<>1__state = 1); <>u__2 = val; <Connect>d__31 <Connect>d__ = this; ((AsyncUniTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<Awaiter<AccessTokenResult>, <Connect>d__31>(ref val, ref <Connect>d__); return; } goto IL_0233; } Debug.LogError((object)"[ChzzkUnity] chatChannelId가 비어있습니다. 방송이 켜져있지 않거나 채널 ID가 틀렸습니다. 연결을 중단합니다."); } goto end_IL_0007; IL_0233: <>s__5 = val.GetResult(); <accessTokenResult>5__2 = <>s__5; <>s__5 = null; if (<accessTokenResult>5__2 == null) { Debug.LogError((object)"[ChzzkUnity] 액세스 토큰 데이터를 가져오지 못했습니다. 연결을 중단합니다."); } else if (<accessTokenResult>5__2.content == null) { Debug.LogError((object)$"[ChzzkUnity] 액세스 토큰 content가 null입니다. (코드: {<accessTokenResult>5__2.code}, 메시지: {<accessTokenResult>5__2.message}). 연결을 중단합니다."); } else { <>4__this.token = <accessTokenResult>5__2.content.accessToken; if (!string.IsNullOrEmpty(<>4__this.token)) { <>4__this.socket = new WebSocket("wss://kr-ss3.chat.naver.com/chat", Array.Empty<string>()); if (<>4__this.socket.Log != null) { <>4__this.socket.Log.Output = delegate { }; } <sslProtocolHack>5__3 = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12; <>4__this.socket.SslConfiguration.EnabledSslProtocols = <sslProtocolHack>5__3; <>4__this.socket.SslConfiguration.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true; <>4__this.socket.OnMessage += <>4__this.ParseMessage; <>4__this.socket.OnClose += <>4__this.CloseConnect; <>4__this.socket.OnOpen += <>4__this.StartChat; <>4__this.socket.OnError += delegate(object sender, ErrorEventArgs e) { Debug.LogError((object)("[ChzzkUnity] WebSocket 오류: " + e.Message)); }; <>4__this.socket.ConnectAsync(); Debug.Log((object)("[ChzzkUnity] WebSocket 연결 요청 완료 (채널 ID: " + <>4__this.cid + ")")); <liveStatus>5__1 = null; <accessTokenResult>5__2 = null; goto end_IL_001c; } Debug.LogError((object)"[ChzzkUnity] 액세스 토큰 값이 비어있습니다. 연결을 중단합니다."); } goto end_IL_0007; end_IL_001c:; } catch (Exception ex) { <ex>5__6 = ex; Debug.LogError((object)$"[ChzzkUnity] Connect 중 치명적 예외 발생: {<ex>5__6}"); } val3 = ((UniTask)(ref UniTask.CompletedTask)).GetAwaiter(); if (!((Awaiter)(ref val3)).IsCompleted) { num = (<>1__state = 2); <>u__3 = val3; <Connect>d__31 <Connect>d__ = this; ((AsyncUniTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<Awaiter, <Connect>d__31>(ref val3, ref <Connect>d__); return; } } else { val3 = <>u__3; <>u__3 = default(Awaiter); num = (<>1__state = -1); } ((Awaiter)(ref val3)).GetResult(); end_IL_0007:; } catch (Exception ex) { <>1__state = -2; ((AsyncUniTaskMethodBuilder)(ref <>t__builder)).SetException(ex); return; } <>1__state = -2; ((AsyncUniTaskMethodBuilder)(ref <>t__builder)).SetResult(); } void IAsyncStateMachine.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext this.MoveNext(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine this.SetStateMachine(stateMachine); } } [CompilerGenerated] private sealed class <GetAccessToken>d__30 : IAsyncStateMachine { public int <>1__state; public AsyncUniTaskMethodBuilder<AccessTokenResult> <>t__builder; public string cid; public ChzzkUnity <>4__this; private string <url>5__1; private UnityWebRequest <request>5__2; private AccessTokenResult <accessTokenResult>5__3; private Exception <ex>5__4; private Awaiter <>u__1; private void MoveNext() { //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: 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) //IL_00ef: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; AccessTokenResult result; try { if (num != 0) { <url>5__1 = "https://comm-api.game.naver.com/nng_main/v1/chats/access-token?channelId=" + cid + "&chatType=STREAMING"; <request>5__2 = UnityWebRequest.Get(<url>5__1); } try { if (num != 0) { <request>5__2.certificateHandler = (CertificateHandler)(object)new BypassCertificate(); <request>5__2.SendWebRequest(); <accessTokenResult>5__3 = null; goto IL_00cf; } Awaiter val = <>u__1; <>u__1 = default(Awaiter); num = (<>1__state = -1); goto IL_00c6; IL_00c6: ((Awaiter)(ref val)).GetResult(); goto IL_00cf; IL_00cf: if (!<request>5__2.isDone) { YieldAwaitable val2 = UniTask.Yield(); val = ((YieldAwaitable)(ref val2)).GetAwaiter(); if (!((Awaiter)(ref val)).IsCompleted) { num = (<>1__state = 0); <>u__1 = val; <GetAccessToken>d__30 <GetAccessToken>d__ = this; <>t__builder.AwaitUnsafeOnCompleted<Awaiter, <GetAccessToken>d__30>(ref val, ref <GetAccessToken>d__); return; } goto IL_00c6; } if ((int)<request>5__2.result == 1) { try { <accessTokenResult>5__3 = JsonConvert.DeserializeObject<AccessTokenResult>(<request>5__2.downloadHandler.text); } catch (Exception ex) { <ex>5__4 = ex; Debug.LogError((object)("[ChzzkUnity] GetAccessToken JSON 파싱 실패: " + <ex>5__4.Message)); } } else { Debug.LogError((object)("[ChzzkUnity] GetAccessToken HTTP 요청 실패: " + <request>5__2.error + " (URL: " + <url>5__1 + ")")); } result = <accessTokenResult>5__3; } finally { if (num < 0 && <request>5__2 != null) { ((IDisposable)<request>5__2).Dispose(); } } } catch (Exception ex) { <>1__state = -2; <url>5__1 = null; <>t__builder.SetException(ex); return; } <>1__state = -2; <url>5__1 = null; <>t__builder.SetResult(result); } void IAsyncStateMachine.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext this.MoveNext(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine this.SetStateMachine(stateMachine); } } [CompilerGenerated] private sealed class <GetChannelInfo>d__28 : IAsyncStateMachine { public int <>1__state; public AsyncUniTaskMethodBuilder<ChannelInfo> <>t__builder; public string channelId; public ChzzkUnity <>4__this; private string <url>5__1; private UnityWebRequest <request>5__2; private ChannelInfo <channelInfo>5__3; private Awaiter <>u__1; private void MoveNext() { //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: 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_0073: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Invalid comparison between Unknown and I4 //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; ChannelInfo result; try { if (num != 0) { <url>5__1 = "https://api.chzzk.naver.com/service/v1/channels/" + channelId; <request>5__2 = UnityWebRequest.Get(<url>5__1); } try { if (num != 0) { <request>5__2.certificateHandler = (CertificateHandler)(object)new BypassCertificate(); <request>5__2.SendWebRequest(); <channelInfo>5__3 = null; goto IL_00ca; } Awaiter val = <>u__1; <>u__1 = default(Awaiter); num = (<>1__state = -1); goto IL_00c1; IL_00c1: ((Awaiter)(ref val)).GetResult(); goto IL_00ca; IL_00ca: if (!<request>5__2.isDone) { YieldAwaitable val2 = UniTask.Yield(); val = ((YieldAwaitable)(ref val2)).GetAwaiter(); if (!((Awaiter)(ref val)).IsCompleted) { num = (<>1__state = 0); <>u__1 = val; <GetChannelInfo>d__28 <GetChannelInfo>d__ = this; <>t__builder.AwaitUnsafeOnCompleted<Awaiter, <GetChannelInfo>d__28>(ref val, ref <GetChannelInfo>d__); return; } goto IL_00c1; } if ((int)<request>5__2.result == 1) { <channelInfo>5__3 = JsonConvert.DeserializeObject<ChannelInfo>(<request>5__2.downloadHandler.text); } result = <channelInfo>5__3; } finally { if (num < 0 && <request>5__2 != null) { ((IDisposable)<request>5__2).Dispose(); } } } catch (Exception exception) { <>1__state = -2; <url>5__1 = null; <>t__builder.SetException(exception); return; } <>1__state = -2; <url>5__1 = null; <>t__builder.SetResult(result); } void IAsyncStateMachine.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext this.MoveNext(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine this.SetStateMachine(stateMachine); } } [CompilerGenerated] private sealed class <GetLiveStatus>d__29 : IAsyncStateMachine { public int <>1__state; public AsyncUniTaskMethodBuilder<LiveStatus> <>t__builder; public string channelId; public ChzzkUnity <>4__this; private string <url>5__1; private UnityWebRequest <request>5__2; private LiveStatus <liveStatus>5__3; private Exception <ex>5__4; private Awaiter <>u__1; private void MoveNext() { //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: 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) //IL_00ef: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; LiveStatus result; try { if (num != 0) { <url>5__1 = "https://api.chzzk.naver.com/polling/v2/channels/" + channelId + "/live-status"; <request>5__2 = UnityWebRequest.Get(<url>5__1); } try { if (num != 0) { <request>5__2.certificateHandler = (CertificateHandler)(object)new BypassCertificate(); <request>5__2.SendWebRequest(); <liveStatus>5__3 = null; goto IL_00cf; } Awaiter val = <>u__1; <>u__1 = default(Awaiter); num = (<>1__state = -1); goto IL_00c6; IL_00c6: ((Awaiter)(ref val)).GetResult(); goto IL_00cf; IL_00cf: if (!<request>5__2.isDone) { YieldAwaitable val2 = UniTask.Yield(); val = ((YieldAwaitable)(ref val2)).GetAwaiter(); if (!((Awaiter)(ref val)).IsCompleted) { num = (<>1__state = 0); <>u__1 = val; <GetLiveStatus>d__29 <GetLiveStatus>d__ = this; <>t__builder.AwaitUnsafeOnCompleted<Awaiter, <GetLiveStatus>d__29>(ref val, ref <GetLiveStatus>d__); return; } goto IL_00c6; } if ((int)<request>5__2.result == 1) { try { <liveStatus>5__3 = JsonConvert.DeserializeObject<LiveStatus>(<request>5__2.downloadHandler.text); } catch (Exception ex) { <ex>5__4 = ex; Debug.LogError((object)("[ChzzkUnity] GetLiveStatus JSON 파싱 실패: " + <ex>5__4.Message)); } } else { Debug.LogError((object)("[ChzzkUnity] GetLiveStatus HTTP 요청 실패: " + <request>5__2.error + " (URL: " + <url>5__1 + ")")); } result = <liveStatus>5__3; } finally { if (num < 0 && <request>5__2 != null) { ((IDisposable)<request>5__2).Dispose(); } } } catch (Exception ex) { <>1__state = -2; <url>5__1 = null; <>t__builder.SetException(ex); return; } <>1__state = -2; <url>5__1 = null; <>t__builder.SetResult(result); } void IAsyncStateMachine.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext this.MoveNext(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine this.SetStateMachine(stateMachine); } } private const string WS_URL = "wss://kr-ss3.chat.naver.com/chat"; private const string HEARTBEAT_REQUEST = "{\"ver\":\"2\",\"cmd\":0}"; private const string HEARTBEAT_RESPONSE = "{\"ver\":\"2\",\"cmd\":10000}"; private string cid; private string token; public string channel; private WebSocket socket = null; private float timer = 0f; private bool running = false; public UnityEvent<Profile, string> onMessage = new UnityEvent<Profile, string>(); public UnityEvent<Profile, string, DonationExtras> onDonation = new UnityEvent<Profile, string, DonationExtras>(); public UnityEvent<Profile, SubscriptionExtras> onSubscription = new UnityEvent<Profile, SubscriptionExtras>(); public UnityEvent onClose = new UnityEvent(); public UnityEvent onOpen = new UnityEvent(); private int closedCount = 0; private bool reOpenTrying = false; private void Start() { onMessage.AddListener((UnityAction<Profile, string>)DebugMessage); onDonation.AddListener((UnityAction<Profile, string, DonationExtras>)DebugDonation); onSubscription.AddListener((UnityAction<Profile, SubscriptionExtras>)DebugSubscription); } private void Update() { if (closedCount > 0) { UnityEvent obj = onClose; if (obj != null) { obj.Invoke(); } if (!reOpenTrying) { ((MonoBehaviour)this).StartCoroutine(TryReOpen()); } closedCount--; } } public IEnumerator TryReOpen() { reOpenTrying = true; yield return (object)new WaitForSeconds(3f); UniTaskExtensions.Forget(Connect()); reOpenTrying = false; } private void FixedUpdate() { if (running) { timer += Time.unscaledDeltaTime; if (timer > 15f) { socket.Send("{\"ver\":\"2\",\"cmd\":0}"); timer = 0f; } } } private void OnDestroy() { StopListening(); } private void DebugMessage(Profile profile, string str) { } private void DebugDonation(Profile profile, string str, DonationExtras donation) { } private void DebugSubscription(Profile profile, SubscriptionExtras subscription) { } public void RemoveAllOnMessageListener() { ((UnityEventBase)onMessage).RemoveAllListeners(); } public void RemoveAllOnDonationListener() { ((UnityEventBase)onDonation).RemoveAllListeners(); } public void RemoveAllOnSubscriptionListener() { ((UnityEventBase)onSubscription).RemoveAllListeners(); } [AsyncStateMachine(typeof(<GetChannelInfo>d__28))] [DebuggerStepThrough] public UniTask<ChannelInfo> GetChannelInfo(string channelId) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) <GetChannelInfo>d__28 <GetChannelInfo>d__ = new <GetChannelInfo>d__28(); <GetChannelInfo>d__.<>t__builder = AsyncUniTaskMethodBuilder<ChannelInfo>.Create(); <GetChannelInfo>d__.<>4__this = this; <GetChannelInfo>d__.channelId = channelId; <GetChannelInfo>d__.<>1__state = -1; <GetChannelInfo>d__.<>t__builder.Start<<GetChannelInfo>d__28>(ref <GetChannelInfo>d__); return <GetChannelInfo>d__.<>t__builder.Task; } [AsyncStateMachine(typeof(<GetLiveStatus>d__29))] [DebuggerStepThrough] public UniTask<LiveStatus> GetLiveStatus(string channelId) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) <GetLiveStatus>d__29 <GetLiveStatus>d__ = new <GetLiveStatus>d__29(); <GetLiveStatus>d__.<>t__builder = AsyncUniTaskMethodBuilder<LiveStatus>.Create(); <GetLiveStatus>d__.<>4__this = this; <GetLiveStatus>d__.channelId = channelId; <GetLiveStatus>d__.<>1__state = -1; <GetLiveStatus>d__.<>t__builder.Start<<GetLiveStatus>d__29>(ref <GetLiveStatus>d__); return <GetLiveStatus>d__.<>t__builder.Task; } [AsyncStateMachine(typeof(<GetAccessToken>d__30))] [DebuggerStepThrough] public UniTask<AccessTokenResult> GetAccessToken(string cid) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) <GetAccessToken>d__30 <GetAccessToken>d__ = new <GetAccessToken>d__30(); <GetAccessToken>d__.<>t__builder = AsyncUniTaskMethodBuilder<AccessTokenResult>.Create(); <GetAccessToken>d__.<>4__this = this; <GetAccessToken>d__.cid = cid; <GetAccessToken>d__.<>1__state = -1; <GetAccessToken>d__.<>t__builder.Start<<GetAccessToken>d__30>(ref <GetAccessToken>d__); return <GetAccessToken>d__.<>t__builder.Task; } [AsyncStateMachine(typeof(<Connect>d__31))] [DebuggerStepThrough] public UniTask Connect() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) <Connect>d__31 <Connect>d__ = new <Connect>d__31(); <Connect>d__.<>t__builder = AsyncUniTaskMethodBuilder.Create(); <Connect>d__.<>4__this = this; <Connect>d__.<>1__state = -1; ((AsyncUniTaskMethodBuilder)(ref <Connect>d__.<>t__builder)).Start<<Connect>d__31>(ref <Connect>d__); return ((AsyncUniTaskMethodBuilder)(ref <Connect>d__.<>t__builder)).Task; } public void Connect(string channelId) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) channel = channelId; UniTaskExtensions.Forget(Connect()); } public void StopListening() { if (socket != null) { socket.Close(); socket = null; } } private void ParseMessage(object sender, MessageEventArgs e) { //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Expected O, but got Unknown //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Expected O, but got Unknown //IL_0293: Unknown result type (might be due to invalid IL or missing references) //IL_0299: Expected O, but got Unknown //IL_0272: Unknown result type (might be due to invalid IL or missing references) //IL_0278: Expected O, but got Unknown try { IDictionary<string, object> dictionary = JsonConvert.DeserializeObject<IDictionary<string, object>>(e.Data); switch ((long)dictionary["cmd"]) { case 0L: socket.Send("{\"ver\":\"2\",\"cmd\":10000}"); timer = 0f; break; case 93101L: { JArray val = (JArray)dictionary["bdy"]; { foreach (JToken item in val) { try { JObject val2 = (JObject)item; string text = ((object)val2["profile"])?.ToString(); Profile profile = new Profile(); profile.nickname = "익명"; if (!string.IsNullOrEmpty(text) && text != "null") { try { JObject val6 = JObject.Parse(text); if (val6["nickname"] != null) { profile.nickname = ((object)val6["nickname"]).ToString(); } if (val6["userIdHash"] != null) { profile.userIdHash = ((object)val6["userIdHash"]).ToString(); } } catch (Exception ex5) { Debug.LogWarning((object)("[ChzzkUnity] 프로필 JObject 파싱 오류: " + ex5.Message + ". 원본: " + text)); } } string text3 = ((object)val2["msg"])?.ToString()?.Trim() ?? ""; onMessage?.Invoke(profile, text3); } catch (Exception ex6) { Debug.LogError((object)("[ChzzkUnity] 개별 채팅 메시지 처리 중 오류: " + ex6.Message)); } } break; } } case 93102L: { JArray val = (JArray)dictionary["bdy"]; { JToken val4 = default(JToken); JToken val5 = default(JToken); foreach (JToken item2 in val) { try { JObject val2 = (JObject)item2; string text = ((object)val2["profile"])?.ToString(); Profile profile = new Profile(); profile.nickname = "익명"; if (!string.IsNullOrEmpty(text) && text != "null") { try { JObject val3 = JObject.Parse(text); if (val3["nickname"] != null) { profile.nickname = ((object)val3["nickname"]).ToString(); } if (val3["userIdHash"] != null) { profile.userIdHash = ((object)val3["userIdHash"]).ToString(); } } catch (Exception ex) { Debug.LogWarning((object)("[ChzzkUnity] 후원자 프로필 JObject 파싱 오류: " + ex.Message + ". 원본: " + text)); } } int num = int.Parse(((object)val2["msgTypeCode"]).ToString()); string text2 = null; if (val2.TryGetValue("extra", ref val4)) { text2 = ((object)val4).ToString(); } else if (val2.TryGetValue("extras", ref val5)) { text2 = ((object)val5).ToString(); } switch (num) { case 10: { DonationExtras donationExtras = null; if (!string.IsNullOrEmpty(text2)) { try { donationExtras = JsonConvert.DeserializeObject<DonationExtras>(text2); } catch (Exception ex3) { Debug.LogError((object)("[ChzzkUnity] DonationExtras 파싱 오류: " + ex3.Message + ". 원본: " + text2)); } } onDonation?.Invoke(profile, ((object)val2["msg"])?.ToString() ?? "", donationExtras); break; } case 11: { SubscriptionExtras subscriptionExtras = null; if (!string.IsNullOrEmpty(text2)) { try { subscriptionExtras = JsonConvert.DeserializeObject<SubscriptionExtras>(text2); } catch (Exception ex2) { Debug.LogError((object)("[ChzzkUnity] SubscriptionExtras 파싱 오류: " + ex2.Message + ". 원본: " + text2)); } } onSubscription?.Invoke(profile, subscriptionExtras); break; } default: Debug.LogError((object)$"MessageTypeCode-{num} is not supported"); Debug.LogError((object)((object)val2).ToString()); break; } } catch (Exception ex4) { Debug.LogError((object)("[ChzzkUnity] 후원/구독 메시지 처리 중 오류: " + ex4.Message)); } } break; } } case 10100L: { UnityEvent obj = onOpen; if (obj != null) { obj.Invoke(); } break; } } } catch (Exception ex7) { Debug.LogError((object)ex7.ToString()); } } private void CloseConnect(object sender, CloseEventArgs e) { Debug.LogError((object)"[ChzzkUnity] 치지직 채팅 서버와 연결이 해제되었습니다."); closedCount++; } private void StartChat(object sender, EventArgs e) { Debug.Log((object)"[ChzzkUnity] 치지직 채팅 서버에 성공적으로 연결되었습니다!"); string text = "{\"ver\":\"2\",\"cmd\":100,\"svcid\":\"game\",\"cid\":\"" + cid + "\",\"bdy\":{\"uid\":null,\"devType\":2001,\"accTkn\":\"" + token + "\",\"auth\":\"READ\"},\"tid\":1}"; timer = 0f; running = true; socket.Send(text); } } public class ChzzkVideoDonationUnity : MonoBehaviour { private enum SslProtocolsHack { Tls = 192, Tls11 = 768, Tls12 = 3072 } [Serializable] public class SessionUrl { [Serializable] public class Content { public string sessionUrl; } public string code; public object message; public Content content; } public class DonationControl { private int startSecond; private int endSecond; private bool stopVideo; private bool titleExpose; private string donationId; private int payAmount; private bool isAnonymous; private bool useSpeech; } [Serializable] public class VideoDonationList { public List<string> videoDonation; } [Serializable] public class VideoDonation { public int startSecond; public int endSecond; public string videoType; public string videoId; public string playMode; public bool stopVideo; public bool titleExpose; public string donationId; public string profile; public int payAmount; public string donationText; public bool isAnonymous; public int tierNo; public bool useSpeech; public override string ToString() { return JsonConvert.SerializeObject((object)this); } } [Serializable] public class Profile { [Serializable] public class ActivityBadge { public int badgeNo; public string badgeId; public string imageUrl; public bool activated; } [Serializable] public class StreamingProperty { [Serializable] public class Subscription { public class Badge { public string imageUrl; } public int accumulativeMonth; public int tier; public Badge badge; } [Serializable] public class NicknameColor { public string colorCode; } public Subscription subscription; public NicknameColor nicknameColor; } public string userIdHash; public string nickname; public string profileImageUrl; public string userRoleCode; public string badge; public string title; public bool verifiedMark; public List<ActivityBadge> activityBadges; public StreamingProperty streamingProperty; } [CompilerGenerated] private sealed class <Connect>d__21 : IAsyncStateMachine { public int <>1__state; public AsyncUniTaskMethodBuilder <>t__builder; public ChzzkVideoDonationUnity <>4__this; private SslProtocols <sslProtocolHack>5__1; private Awaiter <>u__1; private void MoveNext() { //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_011d: 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) //IL_0132: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; try { Awaiter val; if (num != 0) { if (<>4__this.socket != null && <>4__this.socket.IsAlive) { <>4__this.socket.Close(); <>4__this.socket = null; } <>4__this.socket = new WebSocket(<>4__this.wssUrl, Array.Empty<string>()); <sslProtocolHack>5__1 = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12; <>4__this.socket.SslConfiguration.EnabledSslProtocols = <sslProtocolHack>5__1; <>4__this.socket.OnMessage += <>4__this.ParseMessage; <>4__this.socket.OnClose += <>4__this.CloseConnect; <>4__this.socket.OnOpen += <>4__this.onSocketOpen; <>4__this.socket.Connect(); val = ((UniTask)(ref UniTask.CompletedTask)).GetAwaiter(); if (!((Awaiter)(ref val)).IsCompleted) { num = (<>1__state = 0); <>u__1 = val; <Connect>d__21 <Connect>d__ = this; ((AsyncUniTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<Awaiter, <Connect>d__21>(ref val, ref <Connect>d__); return; } } else { val = <>u__1; <>u__1 = default(Awaiter); num = (<>1__state = -1); } ((Awaiter)(ref val)).GetResult(); } catch (Exception exception) { <>1__state = -2; ((AsyncUniTaskMethodBuilder)(ref <>t__builder)).SetException(exception); return; } <>1__state = -2; ((AsyncUniTaskMethodBuilder)(ref <>t__builder)).SetResult(); } void IAsyncStateMachine.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext this.MoveNext(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine this.SetStateMachine(stateMachine); } } [CompilerGenerated] private sealed class <GetSessionURL>d__16 : IAsyncStateMachine { public int <>1__state; public AsyncUniTaskMethodBuilder<string> <>t__builder; public string missionWSSId; public ChzzkVideoDonationUnity <>4__this; private string <url>5__1; private UnityWebRequest <request>5__2; private SessionUrl <sessionUrl>5__3; private void MoveNext() { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Invalid comparison between Unknown and I4 int num = <>1__state; string sessionUrl; try { <url>5__1 = "https://api.chzzk.naver.com/manage/v1/alerts/video@" + missionWSSId + "/session-url"; <request>5__2 = UnityWebRequest.Get(<url>5__1); <request>5__2.SendWebRequest(); <sessionUrl>5__3 = null; if ((int)<request>5__2.result == 1) { <sessionUrl>5__3 = JsonUtility.FromJson<SessionUrl>(<request>5__2.downloadHandler.text); } sessionUrl = <sessionUrl>5__3.content.sessionUrl; } catch (Exception exception) { <>1__state = -2; <url>5__1 = null; <request>5__2 = null; <sessionUrl>5__3 = null; <>t__builder.SetException(exception); return; } <>1__state = -2; <url>5__1 = null; <request>5__2 = null; <sessionUrl>5__3 = null; <>t__builder.SetResult(sessionUrl); } void IAsyncStateMachine.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext this.MoveNext(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine this.SetStateMachine(stateMachine); } } [CompilerGenerated] private sealed class <GetWssUrlFromMissionUrl>d__19 : IAsyncStateMachine { public int <>1__state; public AsyncUniTaskMethodBuilder<string> <>t__builder; public string missionUrl; public ChzzkVideoDonationUnity <>4__this; private string <wssId>5__1; private string <sessionUrl>5__2; private string <>s__3; private Awaiter<string> <>u__1; private void MoveNext() { //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; string result; try { Awaiter<string> val; if (num != 0) { <wssId>5__1 = <>4__this.GetMissionWSSId(missionUrl); val = <>4__this.GetSessionURL(<wssId>5__1).GetAwaiter(); if (!val.IsCompleted) { num = (<>1__state = 0); <>u__1 = val; <GetWssUrlFromMissionUrl>d__19 <GetWssUrlFromMissionUrl>d__ = this; <>t__builder.AwaitUnsafeOnCompleted<Awaiter<string>, <GetWssUrlFromMissionUrl>d__19>(ref val, ref <GetWssUrlFromMissionUrl>d__); return; } } else { val = <>u__1; <>u__1 = default(Awaiter<string>); num = (<>1__state = -1); } <>s__3 = val.GetResult(); <sessionUrl>5__2 = <>s__3; <>s__3 = null; result = <>4__this.MakeWssURL(<sessionUrl>5__2); } catch (Exception exception) { <>1__state = -2; <wssId>5__1 = null; <sessionUrl>5__2 = null; <>t__builder.SetException(exception); return; } <>1__state = -2; <wssId>5__1 = null; <sessionUrl>5__2 = null; <>t__builder.SetResult(result); } void IAsyncStateMachine.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext this.MoveNext(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine this.SetStateMachine(stateMachine); } } private WebSocket socket = null; private float timer = 0f; private bool running = false; private const string HEARTBEAT_REQUEST = "2"; private const string HEARTBEAT_RESPONSE = "3"; public UnityEvent<Profile, VideoDonation> onVideoDonationArrive = new UnityEvent<Profile, VideoDonation>(); public UnityEvent<DonationControl> onVideoDonationControl = new UnityEvent<DonationControl>(); public UnityEvent onClose = new UnityEvent(); public UnityEvent onOpen = new UnityEvent(); private int closedCount = 0; private bool reOpenTrying = false; private string wssUrl; private Dictionary<string, KeyValuePair<Profile, VideoDonation>> activeVideo; private void Start() { } private void Update() { if (closedCount > 0) { UnityEvent obj = onClose; if (obj != null) { obj.Invoke(); } if (!reOpenTrying) { ((MonoBehaviour)this).StartCoroutine(TryReOpen()); } closedCount--; } if (running) { timer += Time.unscaledDeltaTime; if (timer > 15f) { socket.Send("2"); timer = 0f; } } } private void OnDestroy() { StopListening(); } public string GetMissionWSSId(string url) { return url.Split(new char[1] { '@' })[1]; } [AsyncStateMachine(typeof(<GetSessionURL>d__16))] [DebuggerStepThrough] public UniTask<string> GetSessionURL(string missionWSSId) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) <GetSessionURL>d__16 <GetSessionURL>d__ = new <GetSessionURL>d__16(); <GetSessionURL>d__.<>t__builder = AsyncUniTaskMethodBuilder<string>.Create(); <GetSessionURL>d__.<>4__this = this; <GetSessionURL>d__.missionWSSId = missionWSSId; <GetSessionURL>d__.<>1__state = -1; <GetSessionURL>d__.<>t__builder.Start<<GetSessionURL>d__16>(ref <GetSessionURL>d__); return <GetSessionURL>d__.<>t__builder.Task; } public string MakeWssURL(string sessionUrl) { string text = sessionUrl.Split(new string[1] { "auth=" }, StringSplitOptions.None)[1]; string text2 = sessionUrl.Split(new string[1] { ".nchat" }, StringSplitOptions.None)[0].Substring(12); return "wss://ssio" + text2 + ".nchat.naver.com/socket.io/?auth=" + text + "&EIO=3&transport=websocket"; } [AsyncStateMachine(typeof(<GetWssUrlFromMissionUrl>d__19))] [DebuggerStepThrough] public UniTask<string> GetWssUrlFromMissionUrl(string missionUrl) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) <GetWssUrlFromMissionUrl>d__19 <GetWssUrlFromMissionUrl>d__ = new <GetWssUrlFromMissionUrl>d__19(); <GetWssUrlFromMissionUrl>d__.<>t__builder = AsyncUniTaskMethodBuilder<string>.Create(); <GetWssUrlFromMissionUrl>d__.<>4__this = this; <GetWssUrlFromMissionUrl>d__.missionUrl = missionUrl; <GetWssUrlFromMissionUrl>d__.<>1__state = -1; <GetWssUrlFromMissionUrl>d__.<>t__builder.Start<<GetWssUrlFromMissionUrl>d__19>(ref <GetWssUrlFromMissionUrl>d__); return <GetWssUrlFromMissionUrl>d__.<>t__builder.Task; } public async void Connect(string url) { wssUrl = await GetWssUrlFromMissionUrl(url); UniTaskExtensions.Forget(Connect()); } [AsyncStateMachine(typeof(<Connect>d__21))] [DebuggerStepThrough] public UniTask Connect() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) <Connect>d__21 <Connect>d__ = new <Connect>d__21(); <Connect>d__.<>t__builder = AsyncUniTaskMethodBuilder.Create(); <Connect>d__.<>4__this = this; <Connect>d__.<>1__state = -1; ((AsyncUniTaskMethodBuilder)(ref <Connect>d__.<>t__builder)).Start<<Connect>d__21>(ref <Connect>d__); return ((AsyncUniTaskMethodBuilder)(ref <Connect>d__.<>t__builder)).Task; } private void onSocketOpen(object sender, EventArgs e) { timer = 0f; running = true; socket.Send("2"); } public void StopListening() { if (socket != null) { socket.Close(); socket = null; } } private void ParseMessage(object sender, MessageEventArgs e) { Debug.Log((object)e.Data); if (e.Data == "2") { timer = 0f; socket.Send("3"); } else { if (e.Data == "3" || e.Data == "40") { return; } VideoDonationList videoDonationList = JsonUtility.FromJson<VideoDonationList>(e.Data); string text = videoDonationList.videoDonation[0]; string text2 = text; if (!(text2 == "donation")) { if (text2 == "donationControl") { List<DonationControl> list = new List<DonationControl>(); for (int i = 1; i < videoDonationList.videoDonation.Count; i++) { DonationControl donationControl = JsonUtility.FromJson<DonationControl>(videoDonationList.videoDonation[i]); Debug.Log((object)donationControl); list.Add(donationControl); onVideoDonationControl.Invoke(donationControl); } } } else { for (int j = 1; j < videoDonationList.videoDonation.Count; j++) { VideoDonation videoDonation = JsonUtility.FromJson<VideoDonation>(videoDonationList.videoDonation[j]); Debug.Log((object)videoDonation); Profile profile = JsonUtility.FromJson<Profile>(videoDonation.profile); onVideoDonationArrive.Invoke(profile, videoDonation); } } } } private void CloseConnect(object sender, CloseEventArgs e) { Debug.LogError((object)"연결이 해제되었습니다"); Debug.Log((object)e.Reason); Debug.Log((object)e.Code); Debug.Log((object)e); closedCount++; } private IEnumerator TryReOpen() { reOpenTrying = true; yield return (object)new WaitForSeconds(1f); if (!socket.IsAlive) { socket.Connect(); } reOpenTrying = false; } } namespace ChzzkSkul { public class ChzzkGameMode : MonoBehaviour { private struct CommandInfo { public string nickname; public string command; public bool isStreamer; } private struct DonationInfo { public string nickname; public int amount; public string message; } private struct ChatMessageInfo { public string msg; public float expireTime; } public enum VoteState { Inactive, Voting, Processing } public class VoteOption { public string Title; public int Votes; public Action<string> Action; public int Weight; } private struct DonationAction { public int cost; public Action action; } public static List<string> EnemiesAssetKeys = new List<string>(); public static bool EnemiesKeysCached = false; private const float BUFF_DURATION = 30f; private const float HEAL_PERCENT = 0.1f; private readonly ConcurrentQueue<CommandInfo> _commandQueue = new ConcurrentQueue<CommandInfo>(); private readonly ConcurrentQueue<DonationInfo> _donationQueue = new ConcurrentQueue<DonationInfo>(); private readonly ConcurrentQueue<string> _pendingChats = new ConcurrentQueue<string>(); private readonly Queue<ChatMessageInfo> _chatMessages = new Queue<ChatMessageInfo>(); private readonly Queue<string> _ttsQueue = new Queue<string>(); private AudioSource _ttsAudioSource; private object _sapiVoice = null; private Type _sapiType = null; private float _cooldownTimer = 0f; private bool _onCooldown = false; private float _lastCooldownMessageTime = 0f; private Random _random = new Random(); private bool _showItemDestroyer = false; private Vector2 _itemDestroyerScroll = Vector2.zero; public static bool _forceNextDarkEnemy = false; private HashSet<Character> _appliedDarkEnemies = new HashSet<Character>(); public static Map _darkEnemyTargetMap = null; private Map _lastMap; public static ChzzkGameMode _instance; public static HashSet<Key> CustomSuperInscriptions = new HashSet<Key>(); private Map _currentMap; private string _lastSpawnedBossMap = null; private bool _streamerUsedCommandInThisMap = false; private VoteState _voteState = VoteState.Inactive; private float _voteTimer; private float _voteAutoTimer; private float _chaosTimer; private float _bossRushEmptyStageTimer = 0f; private HashSet<string> _votedUsers = new HashSet<string>(); private List<VoteOption> _currentVoteOptions = new List<VoteOption>(); private GameObject _voteUI; private string _lastSpawnedBossRushStage = null; private Character _lastPlayerForStats; private int _lastCardSynergyStep = 0; private Values _cardSynergyStats = null; private float _cardBuffCooldown = 0f; private float _cardSynergyUpdateTimer = 0f; private bool _isApplyingCardSynergyDamage = false; private Values _cardActiveBuffStats = null; public static bool IsScreenEffectActive = false; public static int _screenEffectType = 0; public static float _screenEffectTimer = 0f; private ReverseHorizontalInput _reverseAbility = null; private Volume _screenEffectVolume = null; private GameObject _splitScreenCanvas = null; private RenderTexture _splitScreenRT = null; public static bool _isNukeActive = false; public static int _nukeScenesPassed = 0; public static float _nukeElapsed = 0f; public static float _bossRushElapsed = 0f; public static Map _irradiatedMap = null; private float _irradiatedTimer = 0f; private AudioSource _voidAudioSource = null; private bool _isVoidAudioPlaying = false; private Coroutine _voidAudioCoroutine = null; public static bool _isBossRushActive = false; private Coroutine _bossRushCoroutine = null; private AudioSource _bossRushAudioSource = null; private bool _isSpawningBossRush = false; public static bool ForceNextDarkEnemy { get { return _forceNextDarkEnemy; } set { _forceNextDarkEnemy = value; ChzzkStatManager.Save(); } } private float GLOBAL_COOLDOWN => Plugin.CommandCooldown.Value; private HashSet<string> HealCommands => GetCommands(Plugin.CmdHealString.Value); private HashSet<string> BuffCommands => GetCommands(Plugin.CmdBuffCurseString.Value); private HashSet<string> ItemCommands => GetCommands(Plugin.CmdItemString.Value); private HashSet<string> SkullCommands => GetCommands(Plugin.CmdSkullString.Value); private HashSet<string> SynergyCommands => GetCommands(Plugin.CmdSynergyString.Value); private HashSet<string> OmenCommands => GetCommands(Plugin.CmdOmenString.Value); private HashSet<string> BossCommands => GetCommands(Plugin.CmdBossString.Value); private HashSet<string> DarkEnemyCommands => GetCommands(Plugin.CmdDarkEnemyString.Value); private HashSet<string> DarkCommands => GetCommands(Plugin.CmdDarkAbilityString.Value); private HashSet<string> RandomCommands => GetCommands(Plugin.CmdRandomString.Value); private HashSet<string> NpcCommands => GetCommands(Plugin.CmdNpcString.Value); private HashSet<string> FoodCommands => GetCommands(Plugin.CmdFoodString.Value); private HashSet<string> BoneCommands => GetCommands(Plugin.CmdBoneString.Value); private HashSet<string> GoldCommands => GetCommands(Plugin.CmdGoldString.Value); private HashSet<string> DarkQuartzCommands => GetCommands(Plugin.CmdDarkQuartzString.Value); private HashSet<string> QuintessenceCommands => GetCommands(Plugin.CmdQuintessenceString.Value); private HashSet<string> FragmentCommands => GetCommands(Plugin.CmdFragmentString.Value); private HashSet<string> DefenseCommands => GetCommands(Plugin.CmdDefenseString.Value); private HashSet<string> TotemCommands => GetCommands(Plugin.CmdTotemString.Value); private HashSet<string> RandomStatCommands => GetCommands(Plugin.CmdRandomStatString.Value); private HashSet<string> ChestCommands => GetCommands(Plugin.CmdChestString.Value); public static bool IsBossRushActive { get { return _isBossRushActive; } set { _isBossRushActive = value; ChzzkStatManager.Save(); } } private IEnumerator ProcessTTSQueue() { try { _sapiType = Type.GetTypeFromProgID("SAPI.SpVoice"); if (_sapiType != null) { _sapiVoice = Activator.CreateInstance(_sapiType); } } catch (Exception ex) { Exception e = ex; Debug.LogWarning((object)("[ChzzkGameMode] Windows TTS 초기화 실패: " + e.Message)); } while (true) { if (_ttsQueue.Count > 0 && Plugin.EnableDonationTTS.Value) { string text = _ttsQueue.Dequeue(); if (!string.IsNullOrWhiteSpace(text)) { if (Plugin.TTSProvider != null && Plugin.TTSProvider.Value == "None") { continue; } if (Plugin.TTSProvider != null && Plugin.TTSProvider.Value == "Windows" && _sapiVoice != null && _sapiType != null) { bool isSpeaking = true; ThreadPool.QueueUserWorkItem(delegate { try { _sapiType.InvokeMember("Speak", BindingFlags.InvokeMethod, null, _sapiVoice, new object[2] { text, 0 }); } catch (Exception ex2) { Debug.LogWarning((object)("[ChzzkGameMode] Windows TTS 재생 오류: " + ex2.Message)); } isSpeaking = false; }); while (isSpeaking) { yield return null; } yield return (object)new WaitForSeconds(0.5f); } else { string url = "https://translate.google.com/translate_tts?ie=UTF-8&total=1&idx=0&client=tw-ob&q=" + UnityWebRequest.EscapeURL(text) + "&tl=ko"; UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url, (AudioType)13); try { yield return www.SendWebRequest(); if ((int)www.result == 1) { AudioClip clip = DownloadHandlerAudioClip.GetContent(www); _ttsAudioSource.clip = clip; _ttsAudioSource.Play(); yield return (object)new WaitForSeconds(clip.length + 0.5f); } } finally { ((IDisposable)www)?.Dispose(); } } } } yield return null; } } private string GetFirstCommand(string config, string defaultValue) { if (string.IsNullOrWhiteSpace(config)) { return defaultValue; } string[] array = config.Split(new char[1] { ',' }); if (array.Length != 0) { string text = array[0].Trim(); if (!string.IsNullOrEmpty(text)) { return text; } } return defaultValue; } private HashSet<string> GetCommands(string config) { HashSet<string> hashSet = new HashSet<string>(); if (config == null) { return hashSet; } string[] array = config.Split(new char[1] { ',' }); string[] array2 = array; foreach (string text in array2) { string text2 = text.Trim().ToLower(); if (!string.IsNullOrEmpty(text2)) { hashSet.Add(text2); } } return hashSet; } private void Awake() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown //IL_0028: Expected O, but got Unknown //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Expected O, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown if ((Object)_instance != (Object)null && (Object)_instance != (Object)this) { Object.Destroy((Object)((Component)this).gameObject); return; } _instance = this; Object.DontDestroyOnLoad((Object)((Component)this).gameObject); ChzzkStatManager.Load(); _ttsAudioSource = ((Component)this).gameObject.AddComponent<AudioSource>(); _ttsAudioSource.playOnAwake = false; ((MonoBehaviour)this).StartCoroutine(ProcessTTSQueue()); ((MonoBehaviour)this).StartCoroutine(RecoverStatesAfterLoad()); ((MonoBehaviour)this).StartCoroutine(C_CacheEnemyAssetKeys()); } private IEnumerator C_CacheEnemyAssetKeys() { if (EnemiesKeysCached) { yield break; } string[] targetMobs = new string[5] { "Hound", "CarleonRecruit", "Servant", "GoldmaneRecruit", "FanaticRecruit" }; HashSet<string> targetSet = new HashSet<string>(targetMobs, StringComparer.OrdinalIgnoreCase); foreach (IResourceLocator locator in Addressables.ResourceLocators) { if (locator == null || locator.Keys == null) { continue; } foreach (object keyObj in locator.Keys) { if (keyObj == null) { continue; } string k = keyObj.ToString(); if (k.EndsWith(".prefab") && k.Contains("Enemies") && !k.Contains("effect") && !k.Contains("ui")) { string fileName = Path.GetFileNameWithoutExtension(k); if (targetSet.Contains(fileName) && !EnemiesAssetKeys.Contains(k)) { EnemiesAssetKeys.Add(k); } } } yield return null; } EnemiesKeysCached = true; Debug.Log((object)$"[ChzzkGameMode] Successfully cached {EnemiesAssetKeys.Count} enemy asset keys."); } private IEnumerator RecoverStatesAfterLoad() { yield return (object)new WaitForSeconds(4f); if (_isNukeActive) { DoNuke("SYSTEM", isResume: true); } if (IsBossRushActive) { DoBossRush("SYSTEM", isResume: true); } yield return C_RestoreExtraInventoryItems(); } private IEnumerator C_RestoreExtraInventoryItems() { CustomGearsPatch.ExpandInventoryIfNeeded((Item)null); Character player = GetPlayer(); if ((Object)(object)player == (Object)null || player.playerComponents == null || player.playerComponents.inventory == null) { yield break; } ItemInventory itemInventory = player.playerComponents.inventory.item; if ((Object)(object)itemInventory == (Object)null || ChzzkStatManager.SaveData.ExtraInventoryItems == null || ChzzkStatManager.SaveData.ExtraInventoryItems.Count == 0) { yield break; } Service service = GetService(); if ((Object)(object)service == (Object)null || (Object)(object)service.gearManager == (Object)null || (Object)(object)service.levelManager == (Object)null) { yield break; } for (int i = 0; i < ChzzkStatManager.SaveData.ExtraInventoryItems.Count; i++) { string itemName = ChzzkStatManager.SaveData.ExtraInventoryItems[i]; int targetSlotIndex = 9 + i; if (string.IsNullOrEmpty(itemName)) { continue; } itemName = ChzzkStatManager.GetOriginalItemName(itemName); if (targetSlotIndex < itemInventory.items.Count && (Object)(object)itemInventory.items[targetSlotIndex] != (Object)null) { continue; } ItemReference itemRef = null; if (!GearResource.instance.TryGetItemReferenceByName(itemName, ref itemRef)) { continue; } ItemRequest req = itemRef.LoadAsync(); while (!((Request<Item>)(object)req).isDone) { yield return null; } if (!((Object)(object)((Request<Item>)(object)req).asset != (Object)null)) { continue; } Item drop = service.levelManager.DropItem(req, ((Component)player).transform.position); if (!((Object)(object)drop != (Object)null)) { continue; } try { MethodInfo equipAtMethod = typeof(ItemInventory).GetMethod("EquipAt", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? typeof(ItemInventory).GetMethod("EquipAt"); if (equipAtMethod != null) { equipAtMethod.Invoke(itemInventory, new object[2] { drop, targetSlotIndex }); } else if (targetSlotIndex < itemInventory.items.Count) { itemInventory.items[targetSlotIndex] = drop; ((Gear)drop).state = (State)1; ((Gear)drop).OnEquipped(); } } catch (Exception ex) { Debug.LogError((object)("[RestoreExtraInventoryItems] Failed to equip: " + ex)); } } } private void LateUpdate() { //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Expected O, but got Unknown //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02be: Expected O, but got Unknown //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0545: Unknown result type (might be due to invalid IL or missing references) //IL_054f: Unknown result type (might be due to invalid IL or missing references) //IL_0559: Expected O, but got Unknown //IL_0559: Expected O, but got Unknown //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Expected O, but got Unknown //IL_031a: Unknown result type (might be due to invalid IL or missing references) //IL_0262: Unknown result type (might be due to invalid IL or missing references) //IL_026d: Expected O, but got Unknown //IL_0231: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Expected O, but got Unknown //IL_0275: Unknown result type (might be due to invalid IL or missing references) //IL_027f: Expected O, but got Unknown //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Expected O, but got Unknown //IL_035a: Unknown result type (might be due to invalid IL or missing references) //IL_0364: Invalid comparison between Unknown and I4 //IL_036b: Unknown result type (might be due to invalid IL or missing references) //IL_0375: Invalid comparison between Unknown and I4 //IL_0379: Unknown result type (might be due to invalid IL or missing references) //IL_0383: Invalid comparison between Unknown and I4 //IL_0387: Unknown result type (might be due to invalid IL or missing references) //IL_0391: Invalid comparison between Unknown and I4 //IL_0395: Unknown result type (might be due to invalid IL or missing references) //IL_039f: Invalid comparison between Unknown and I4 //IL_03a3: Unknown result type (might be due to invalid IL or missing references) //IL_03ad: Invalid comparison between Unknown and I4 //IL_03b1: Unknown result type (might be due to invalid IL or missing references) //IL_03bb: Invalid comparison between Unknown and I4 //IL_03bf: Unknown result type (might be due to invalid IL or missing references) //IL_03c9: Invalid comparison between Unknown and I4 //IL_03cd: Unknown result type (might be due to invalid IL or missing references) //IL_03d7: Invalid comparison between Unknown and I4 //IL_03db: Unknown result type (might be due to invalid IL or missing references) //IL_03e5: Invalid comparison between Unknown and I4 //IL_03e9: Unknown result type (might be due to invalid IL or missing references) //IL_03ef: Invalid comparison between Unknown and I4 if (IsScreenEffectActive) { _screenEffectTimer -= Time.unscaledDeltaTime; if (_screenEffectTimer <= 0f) { IsScreenEffectActive = false; if ((Object)Camera.main != (Object)null) { ((Component)Camera.main).transform.localEulerAngles = Vector3.zero; } if (_reverseAbility != null) { Character player = GetPlayer(); if ((Object)player != (Object)null) { player.ability.Remove((IAbility)(object)_reverseAbility); } _reverseAbility = null; } if ((Object)_screenEffectVolume != (Object)null) { ((Component)_screenEffectVolume).gameObject.SetActive(false); } if ((Object)_splitScreenCanvas != (Object)null) { Object.Destroy((Object)(object)_splitScreenCanvas); _splitScreenCanvas = null; } if ((Object)_splitScreenRT != (Object)null) { if ((Object)Camera.main != (Object)null && (Object)(object)Camera.main.targetTexture == (Object)(object)_splitScreenRT) { Camera.main.targetTexture = null; } _splitScreenRT.Release(); Object.Destroy((Object)(object)_splitScreenRT); _splitScreenRT = null; } ChzzkStatManager.Save(); } else { if ((Object)Camera.main != (Object)null) { if (_screenEffectType == 0) { ((Component)Camera.main).transform.localEulerAngles = new Vector3(0f, 0f, 180f); } else if (_screenEffectType == 1) { ((Component)Camera.main).transform.localEulerAngles = new Vector3(0f, 0f, 15f); } else if (_screenEffectType == 2) { ((Component)Camera.main).transform.localEulerAngles = new Vector3(0f, 0f, -15f); } } if (_screenEffectType == 3 && _reverseAbility == null) { Character player2 = GetPlayer(); if ((Object)player2 != (Object)null) { _reverseAbility = new ReverseHorizontalInput(); player2.ability.Add((IAbility)(object)_reverseAbility); } } } } if (ForceNextDarkEnemy && (Object)(object)_darkEnemyTargetMap == (Object)(object)Map.Instance && (Object)Map.Instance != (Object)null) { if (!((Object)(object)Map.Instance.waveContainer != (Object)null)) { return; } { foreach (Character allSpawnedEnemy in Map.Instance.waveContainer.GetAllSpawnedEnemies()) { if (!((Object)(object)allSpawnedEnemy != (Object)null) || (int)allSpawnedEnemy.type != 0 || ((Health)allSpawnedEnemy.health).dead || !((Component)allSpawnedEnemy).gameObject.activeInHierarchy || _appliedDarkEnemies.Contains(allSpawnedEnemy) || (int)allSpawnedEnemy.key == 15005 || (int)allSpawnedEnemy.key == 30302 || (int)allSpawnedEnemy.key == 30303 || (int)allSpawnedEnemy.key == 30301 || (int)allSpawnedEnemy.key == 30304 || (int)allSpawnedEnemy.key == 10101 || (int)allSpawnedEnemy.key == 15002 || (int)allSpawnedEnemy.key == 15001 || (int)allSpawnedEnemy.key == 15010 || (int)allSpawnedEnemy.key == 10001 || (int)allSpawnedEnemy.key <= 0) { continue; } _appliedDarkEnemies.Add(allSpawnedEnemy); try { object obj = null; PropertyInfo property = typeof(DarkEnemySelector).GetProperty("instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); if (property != null) { obj = property.GetValue(null, null); } if (obj == null) { FieldInfo field = typeof(DarkEnemySelector).GetField("instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); if (field != null) { obj = field.GetValue(null); } } if (obj == null) { obj = Object.FindObjectOfType<DarkEnemySelector>(); } if (obj == null) { continue; } FieldInfo field2 = typeof(DarkEnemySelector).GetField("_constructors", BindingFlags.Instance | BindingFlags.NonPublic); if (field2 != null && field2.GetValue(obj) is DarkAbilityConstructor[] array) { int currentLevel = Singleton<HardmodeManager>.Instance.currentLevel; if (currentLevel >= 0 && currentLevel < array.Length) { array[currentLevel].Provide(allSpawnedEnemy); } } } catch { } } return; } } if ((Object)_darkEnemyTargetMap != (Object)Map.Instance) { _appliedDarkEnemies.Clear(); } } private void Update() { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown //IL_0474: Unknown result type (might be due to invalid IL or missing references) //IL_047f: Expected O, but got Unknown //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown //IL_004a: Expected O, but got Unknown //IL_045c: Unknown result type (might be due to invalid IL or missing references) //IL_0466: Expected O, but got Unknown //IL_04d1: Unknown result type (might be due to invalid IL or missing references) //IL_04d6: Unknown result type (might be due to invalid IL or missing references) //IL_117f: Unknown result type (might be due to invalid IL or missing references) //IL_118a: Expected O, but got Unknown //IL_035d: Unknown result type (might be due to invalid IL or missing references) //IL_0368: Expected O, but got Unknown //IL_036b: Unknown result type (might be due to invalid IL or missing references) //IL_0376: Unknown result type (might be due to invalid IL or missing references) //IL_0380: Expected O, but got Unknown //IL_0380: Expected O, but got Unknown //IL_0393: Unknown result type (might be due to invalid IL or missing references) //IL_039e: Expected O, but got Unknown //IL_03bb: Unknown result type (might be due to invalid IL or missing references) //IL_03c5: Expected O, but got Unknown //IL_064e: Unknown result type (might be due to invalid IL or missing references) //IL_0659: Expected O, but got Unknown //IL_0661: Unknown result type (might be due to invalid IL or missing references) //IL_066b: Unknown result type (might be due to invalid IL or missing references) //IL_0675: Expected O, but got Unknown //IL_0675: Expected O, but got Unknown //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Expected O, but got Unknown //IL_0773: Unknown result type (might be due to invalid IL or missing references) //IL_077d: Unknown result type (might be due to invalid IL or missing references) //IL_0787: Expected O, but got Unknown //IL_0787: Expected O, but got Unknown //IL_0736: Unknown result type (might be due to invalid IL or missing references) //IL_0740: Unknown result type (might be due to invalid IL or missing references) //IL_074a: Expected O, but got Unknown //IL_074a: Expected O, but got Unknown //IL_026c: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Expected O, but got Unknown //IL_0297: Unknown result type (might be due to invalid IL or missing references) //IL_029e: Expected O, but got Unknown //IL_0851: Unknown result type (might be due to invalid IL or missing references) //IL_085c: Expected O, but got Unknown //IL_0879: Unknown result type (might be due to invalid IL or missing references) //IL_087f: Invalid comparison between Unknown and I4 //IL_0883: Unknown result type (might be due to invalid IL or missing references) //IL_0889: Invalid comparison between Unknown and I4 //IL_088d: Unknown result type (might be due to invalid IL or missing references) //IL_0893: Invalid comparison between Unknown and I4 CheckMoonSunFusion(); if (Input.GetKeyDown((KeyCode)290)) { AssetDumper.DumpAllAssets(); } Map instance = Map.Instance; if ((Object)instance != (Object)null && (Object)instance != (Object)_currentMap) { bool flag = (Object)(object)_currentMap != (Object)null; string text = (((Object)(object)_currentMap != (Object)null) ? ((Object)_currentMap).name : null); _currentMap = instance; _streamerUsedCommandInThisMap = false; string name = ((Object)instance).name; if (flag && !string.IsNullOrEmpty(text) && _lastSpawnedBossMap == text) { if (ChzzkStatManager.SaveData.SpawnedBossCount > 0) { ChzzkStatManager.SaveData.SpawnedBossCount = 0; ChzzkStatManager.Save(); } _lastSpawnedBossMap = null; } if (name != ChzzkStatManager.SaveData.StageName) { ChzzkStatManager.SaveData.StageName = name; ChzzkStatManager.SaveData.IsVoteCompletedInThisStage = false; ChzzkStatManager.SaveData.VotedResultTitle = null; ChzzkStatManager.Save(); } if (ChzzkStatManager.SaveData.SpawnedBossCount > 0 && _lastSpawnedBossMap != name) { Debug.Log((object)$"[ChzzkGameMode] Map 변경 감지 및 보스 복구 트리거: stageName={name}, SpawnedBossCount={ChzzkStatManager.SaveData.SpawnedBossCount}"); _lastSpawnedBossMap = name; ((MonoBehaviour)this).StartCoroutine(C_RecoverBossesForMap(name)); } if (IsBossRushActive) { Debug.Log((object)("[ChzzkGameMode] Map 변경 감지 및 보스 러쉬 복구 트리거: stageName=" + name)); ((MonoBehaviour)this).StartCoroutine(SpawnBossRushBosses()); } if ((Object)(object)_irradiatedMap != (Object)null && (Object)_irradiatedMap != (Object)(object)instance) { _irradiatedMap = null; } if ((Object)(object)_irradiatedMap == (Object)null && _isVoidAudioPlaying) { _isVoidAudioPlaying = false; if (_voidAudioCoroutine != null) { ((MonoBehaviour)this).StopCoroutine(_voidAudioCoroutine); _voidAudioCoroutine = null; } if ((Object)(object)_voidAudioSource != (Object)null) { _voidAudioSource.Stop(); } FieldInfo field = typeof(SoundManager).GetField("_backgroundMusic", BindingFlags.Instance | BindingFlags.NonPublic); if ((Object)Singleton<SoundManager>.Instance != (Object)null && field != null) { AudioSource val = (AudioSource)field.GetValue(Singleton<SoundManager>.Instance); if ((Object)(object)val != (Object)null && !_isNukeActive && !IsBossRushActive) { val.mute = false; } } } if (_voteState == VoteState.Voting) { EndVote(); StartVote(); } } string result; while (_pendingChats.TryDequeue(out result)) { _chatMessages.Enqueue(new ChatMessageInfo { msg = result, expireTime = Time.unscaledTime + 5f }); if (_chatMessages.Count > 6) { _chatMessages.Dequeue(); } } Character player = GetPlayer(); if ((Object)player != (Object)null && (Object)player != (Object)_lastPlayerForStats) { if ((Object)_lastPlayerForStats != (Object)null) { try { ((PriorityList<GiveDamageDelegate>)(object)_lastPlayerForStats.onGiveDamage).Remove(new GiveDamageDelegate(OnGiveDamageForCardSynergy)); if (_cardSynergyStats != null) { _lastPlayerForStats.stat.DetachValues(_cardSynergyStats); } if (_cardActiveBuffStats != null) { _lastPlayerForStats.stat.DetachValues(_cardActiveBuffStats); } _lastPlayerForStats.stat.SetNeedUpdate(); } catch { } } _cardSynergyStats = null; _cardActiveBuffStats = null; _lastCardSynergyStep = 0; _lastPlayerForStats = player; try { ((PriorityList<GiveDamageDelegate>)(object)player.onGiveDamage).Add(100, new GiveDamageDelegate(OnGiveDamageForCardSynergy)); } catch { } if ((Object)Map.Instance != (Object)null && (((Object)Map.Instance).name.Contains("Castle") || ((Object)Map.Instance).name.Contains("Tutorial") || ((Object)Map.Instance).name.Contains("Test"))) { Scene activeScene = SceneManager.GetActiveScene(); string name2 = ((Scene)(ref activeScene)).name; Debug.Log((object)("[ChzzkGameMode] Castle/Tutorial/Test 감지됨. Scene: " + name2 + ", Map: " + ((Object)Map.Instance).name)); if (name2.IndexOf("Title", StringComparison.OrdinalIgnoreCase) >= 0 || name2.IndexOf("Menu", StringComparison.OrdinalIgnoreCase) >= 0) { Debug.Log((object)("[ChzzkGameMode] 타이틀/메뉴 화면 감지 (" + name2 + "). 초기화를 건너뜁니다.")); } else { ChzzkStatManager.Clear(); ChzzkStatManager.SaveData.SpawnedBossCount = 0; ChzzkStatManager.SaveData.IsVoteCompletedInThisStage = false; ChzzkStatManager.SaveData.VotedResultTitle = null; ChzzkStatManager.SaveData.StageName = null; ChzzkStatManager.Save(); _lastSpawnedBossMap = null; } } else { ChzzkStatManager.ApplyToPlayer(player); if (ChzzkStatManager.SaveData.IsVoteCompletedInThisStage && !string.IsNullOrEmpty(ChzzkStatManager.SaveData.VotedResultTitle)) { string votedResultTitle = ChzzkStatManager.SaveData.VotedResultTitle; if (votedResultTitle != "보스 소환" && votedResultTitle != "핵폭발 발동" && !votedResultTitle.EndsWith(" 모드")) { ApplyVotedAction(votedResultTitle); } } } } while (_chatMessages.Count > 0 && Time.unscaledTime > _chatMessages.Peek().expireTime) { _chatMessages.Dequeue(); } if ((Object)Map.Instance != (Object)null && (Object)_lastMap != (Object)Map.Instance) { _lastMap = Map.Instance; if (Plugin.EnableVote.Value && Plugin.VoteTriggerMode.Value.IndexOf("Scene", StringComparison.OrdinalIgnoreCase) >= 0 && _voteState == VoteState.Inactive && !_isNukeActive && !IsBossRushActive && !ChzzkStatManager.SaveData.IsVoteCompletedInThisStage) { StartVote(); } if (ForceNextDarkEnemy) { if ((Object)(object)_darkEnemyTargetMap == (Object)null) { _darkEnemyTargetMap = Map.Instance; Debug.Log((object)"[ChzzkGameMode] 다음 맵 커스텀 몬스터 강화 적용 완료 (타겟 맵 지정)"); ShowFloatingText("어둠의 기운이 다음 맵을 뒤덮습니다... (검은 적 등장!)"); } else if ((Object)_darkEnemyTargetMap != (Object)Map.Instance) { ForceNextDarkEnemy = false; _darkEnemyTargetMap = null; } } } if ((Object)(object)_irradiatedMap != (Object)null && (Object)Map.Instance == (Object)_irradiatedMap) { if (!_isVoidAudioPlaying && !_isNukeActive) { _isVoidAudioPlaying = true; _voidAudioCoroutine = ((MonoBehaviour)this).StartCoroutine(PlayVoidBgmRoutine()); } _irradiatedTimer += Time.unscaledDeltaTime; if (_irradiatedTimer >= 0.2f) { _irradiatedTimer = 0f; if ((Object)(object)Map.Instance.waveContainer != (Object)null) { List<Character> allSpawnedEnemies = Map.Instance.waveContainer.GetAllSpawnedEnemies(); if (allSpawnedEnemies != null) { foreach (Character item in allSpawnedEnemies) { if ((Object)item != (Object)null && !((Health)item.health).dead && (int)item.type != 3 && (int)item.type != 2 && (int)item.type != 1) { ApplyNukeDamage(item, isBoss: false); } } } } } } if ((Object)(object)_voidAudioSource != (Object)null) { _voidAudioSource.mute = IsBossRushActive || _isNukeActive; } if (Plugin.EnableVote.Value && !_isNukeActive && !IsBossRushActive) { if (_voteState == VoteState.Inactive && Plugin.VoteTriggerMode.Value.IndexOf("Timer", StringComparison.OrdinalIgnoreCase) >= 0) { _voteAutoTimer += Time.unscaledDeltaTime; if (_voteAutoTimer >= Plugin.VoteIntervalSeconds.Value) { StartVote(); _voteAutoTimer = 0f; } } else if (_voteState == VoteState.Voting) { _voteTimer -= Time.unscaledDeltaTime; if (_voteTimer <= 0f) { EndVote(); } } } if (Plugin.EnableChaosMode != null && Plugin.EnableChaosMode.Value && !_isNukeActive && !IsBossRushActive && Plugin.ChaosIntervalSeconds != null) { _chaosTimer += Time.unscaledDeltaTime; if (_chaosTimer >= Plugin.ChaosIntervalSeconds.Value) { _chaosTimer = 0f; try { TriggerRandomChaosCommand(); } catch (Exception arg) { Debug.LogError((object)$"[ChaosMode] 오류: {arg}"); } } } if (_onCooldown) { _cooldownTimer -= Time.unscaledDeltaTime; if (_cooldownTimer <= 0f) { _onCooldown = false; _cooldownTimer = 0f; } } DonationInfo result2; while (_donationQueue.TryDequeue(out result2)) { try { if (Plugin.EnableDonationTTS.Value && !string.IsNullOrWhiteSpace(result2.message)) { _ttsQueue.Enqueue(result2.message); } HandleDonation(result2.nickname, result2.amount); } catch (Exception arg2) { Debug.LogError((object)$"[ChzzkGameMode] 후원 실행 오류: {arg2}"); } } CommandInfo result3; while (_commandQueue.TryDequeue(out result3)) { string nickname = result3.nickname; string command = result3.command; if (!result3.isStreamer && _onCooldown) { if (Time.unscaledTime - _lastCooldownMessageTime > 1f) { _lastCooldownMessageTime = Time.unscaledTime; ShowFloatingText($"명령어 쿨타임.. ({_cooldownTimer:F1}초 남음)"); } continue; } if (!result3.isStreamer) { _onCooldown = true; _cooldownTimer = GLOBAL_COOLDOWN; } try { string text2 = command; string arg3 = ""; int num = command.IndexOf(' '); if (num != -1) { text2 = command.Substring(0, num).Trim(); arg3 = command.Substring(num + 1).Trim(); } text2 = text2.ToLower(); if (RandomCommands.Contains(text2)) { DoRandom(nickname); } else if (HealCommands.Contains(text2) && Plugin.AllowHeal.Value) { DoHeal(nickname); } else if (NpcCommands.Contains(text2) && Plugin.AllowNpc.Value) { DoNPC(nickname); } else if (FoodCommands.Contains(text2) && Plugin.AllowFood.Value) { DoFood(nickname); } else if (BoneCommands.Contains(text2) && Plugin.AllowBone.Value) { DoBone(nickname); } else if (GoldCommands.Contains(text2) && Plugin.AllowGold.Value) { DoGold(nickname); } else if (DarkQuartzCommands.Contains(text2) && Plugin.AllowDarkQuartz.Value) { DoDarkQuartz(nickname); } else if (QuintessenceCommands.Contains(text2) && Plugin.AllowQuintessence.Value) { ((MonoBehaviour)this).StartCoroutine(DoQuintessenceCoroutine(nickname)); } else if (FragmentCommands.Contains(text2) && Plugin.AllowFragment.Value) { ((MonoBehaviour)this).StartCoroutine(DoFragmentCoroutine(nickname)); } else if (DefenseCommands.Contains(text2) && Plugin.AllowDefense.Value) { DoDefense(nickname); } else if (TotemCommands.Contains(text2) && Plugin.AllowTotem.Value) { DoTotemBuff(nickname); } else if (ChestCommands.Contains(text2) && Plugin.AllowChest.Value) { DoChestSpawn(nickname); } else if (BuffCommands.Contains(text2) && Plugin.AllowBuffCurse.Value) { DoBuffOrCurse(nickname); } else if (ItemCommands.Contains(text2) && Plugin.AllowItem.Value) { ((MonoBehaviour)this).StartCoroutine(DoItemCoroutine(nickname, arg3)); } else if (SkullCommands.Contains(text2) && Plugin.AllowSkull.Value) { ((MonoBehaviour)this).StartCoroutine(DoSkullCoroutine(nickname, arg3)); } else if (SynergyCommands.Contains(text2) && Plugin.AllowSynergy.Value) { DoSynergy(nickname); } else if (OmenCommands.Contains(text2) && Plugin.AllowOmen.Value) { DoOmen(nickname); } else if ((BossCommands.Contains(text2) || text2 == "!보스소환") && Plugin.AllowBoss.Value) { if (text2 == "!보스소환") { if (result3.isStreamer) { DoBoss(nickname); } else { ShowFloatingText("보스소환 명령어는 스트리머 전용입니다."); } } else { DoBoss(nickname); } } else if (DarkEnemyCommands.Contains(text2)) { if (result3.isStreamer) { DoDarkEnemyForce(nickname); } else { ShowFloatingText("해당 명령어는 스트리머 전용입니다."); } } else if (DarkCommands.Contains(text2) && Plugin.AllowDarkAbility.Value) { DoDarkAbility(nickname); } else if (RandomStatCommands.Contains(text2) && Plugin.AllowRandomStat.Value) { DoRandomStat(nickname); } else if (text2 == "!핵" || text2 == "!nuke") { if (result3.isStreamer) { DoNuke(nickname); } } else if (text2 == "!entity" || text2 == "!엔티티") { if (result3.isStreamer) { DoPrintEntities(nickname); } else { ShowFloatingText("엔티티 명령어는 스트리머 전용입니다."); } } } catch (Exception arg4) { Debug.LogError((object)$"[Command Queue] Error processing {command}: {arg4}"); } } if (IsBossRushActive) { string text3 = (((Object)Map.Instance != (Object)null) ? ((Object)Map.Instance).name : null); if (text3 != null && !text3.Contains("Castle") && !text3.Contains("Tutorial") && !text3.Contains("Test")) { if (GetAliveEnemyCount() == 0) { _bossRushEmptyStageTimer += Time.unscaledDeltaTime; if (_bossRushEmptyStageTimer >= 30f) { _bossRushEmptyStageTimer = 0f; _lastSpawnedBossRushStage = null; ShowFloatingText("30초 동안 생존한 적이 없어 보스들이 재소환됩니다!"); ((MonoBehaviour)this).StartCoroutine(SpawnBossRushBosses()); } } else { _bossRushEmptyStageTimer = 0f; } } else { _bossRushEmptyStageTimer = 0f; } } else { _bossRushEmptyStageTimer = 0f; } if (_cardBuffCooldown > 0f) { _cardBuffCooldown -= Time.deltaTime; } if ((Object)(object)player != (Object)null) { _cardSynergyUpdateTimer -= Time.deltaTime; if (_cardSynergyUpdateTimer <= 0f) { _cardSynergyUpdateTimer = 0.5f; UpdateCardSynergy(player); } } if (Input.GetKeyDown((KeyCode)111) || Input.GetKeyDown((KeyCode)105)) { _showItemDestroyer = !_showItemDestroyer; } } private void TriggerRandomChaosCommand() { List<Action<string>> list = new List<Action<string>> { delegate(string n) { DoHeal(n); }, delegate(string n) { DoBuffOrCurse(n); }, delegate(string n) { ((MonoBehaviour)this).StartCoroutine(DoItemCoroutine(n)); }, delegate(string n) { ((MonoBehaviour)this).StartCoroutine(DoSkullCoroutine(n)); }, delegate(string n) { DoSynergy(n); }, delegate(string n) { DoOmen(n); }, delegate(string n) { DoBoss(n); }, delegate(string n) { DoDarkAbility(n); }, delegate(string n) { DoRandomStat(n); } }; list.Add(delegate(string n) { DoDropOmen(n); }); list.Add(delegate(string n) { DoBossRush(n); }); list.Add(delegate(string n) { DoRandomScreenEffect(n); }); if (Plugin.AllowNuke != null && Plugin.AllowNuke.Value) { list.Add(delegate(string n) { DoNuke(n); }); } list[_random.Next(list.Count)]("$CHAOS$"); } private void DrawItemDestroyerWindow(int windowId) { //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) GUILayout.Label("파괴할 아이템을 선택하세요. 파괴된 아이템은 즉시 인벤토리에서 삭제됩니다.", Array.Empty<GUILayoutOption>()); Character player = GetPlayer(); if ((Object)(object)player == (Object)null || player.playerComponents == null || player.playerComponents.inventory == null || (Object)(object)player.playerComponents.inventory.item == (Object)null) { GUILayout.Label("플레이어 인벤토리를 찾을 수 없습니다.", Array.Empty<GUILayoutOption>()); if (GUILayout.Button("닫기", Array.Empty<GUILayoutOption>())) { _showItemDestroyer = false; } GUI.DragWindow(); return; } List<Item> items = player.playerComponents.inventory.item.items; _itemDestroyerScroll = GUILayout.BeginScrollView(_itemDestroyerScroll, Array.Empty<GUILayoutOption>()); int num = 0; for (int i = 0; i < items.Count; i++) { Item val = items[i]; if ((Object)(object)val == (Object)null) { continue; } num++; GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); string text = ((Object)val).name; try { string localizedString = Localization.GetLocalizedString(((Gear)val).displayNameKey); if (!string.IsNullOrEmpty(localizedString)) { text = localizedString; } } catch { } GUILayout.Label($"[{i + 1}] {text}", Array.Empty<GUILayoutOption>()); if (GUILayout.Button("파괴 (Destroy)", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { try { player.playerComponents.inventory.item.Drop(i); Object.Destroy((Object)(object)((Component)val).gameObject); ChzzkStatManager.Save(); ShowFloatingText("[" + text + "] 아이템을 파괴했습니다!"); } catch (Exception ex) { Debug.LogError((object)("[ItemDestroyer] Failed to destroy item: " + ex)); } } GUILayout.EndHorizontal(); } if (num == 0) { GUILayout.Label("인벤토리에 보유 중인 아이템이 없습니다.", Array.Empty<GUILayoutOption>()); } GUILayout.EndScrollView(); if (GUILayout.Button("닫기", Array.Empty<GUILayoutOption>())) { _showItemDestroyer = false; } GUI.DragWindow(); } private void OnGUI() { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Expected O, but got Unknown //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Expected O, but got Unknown //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected O, but got Unknown //IL_005b: 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_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Expected O, but got Unknown //IL_00d9: 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) //IL_00a1: Expected O, but got Unknown //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01e0: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Expected O, but got Unknown //IL_02c7: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: Expected O, but got Unknown //IL_0320: Unknown result type (might be due to invalid IL or missing references) //IL_0355: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_03ca: Unknown result type (might be due to invalid IL or missing references) if (_showItemDestroyer) { Rect val = default(Rect); ((Rect)(ref val))..ctor((float)Screen.width / 2f - 250f, (float)Screen.height / 2f - 300f, 500f, 600f); GUI.Window(9999, val, new WindowFunction(DrawItemDestroyerWindow), "아이템 파괴기 (Item Destroyer)"); } GUIStyle val2 = new GUIStyle(); if ((Object)GUI.skin != (Object)null && GUI.skin.label != null) { val2 = new GUIStyle(GUI.skin.label); } val2.fontSize = 24; val2.wordWrap = true; val2.richText = true; val2.normal.textColor = Color.white; GUIStyle val3 = new GUIStyle(val2); val3.normal.textColor = Color.black; DrawTip(val2, val3); if (_chatMessages.Count == 0 && (!_onCooldown || !(_cooldownTimer > 0f)) && _voteState != VoteState.Voting) { return; } float num = (float)Screen.height - 350f; Rect val4 = default(Rect); Rect val5 = default(Rect); foreach (ChatMessageInfo chatMessage in _chatMessages) { val4 = new Rect(20f, num, 800f, 50f); ((Rect)(ref val5))..ctor(((Rect)(ref val4)).x + 1f, ((Rect)(ref val4)).y + 1f, ((Rect)(ref val4)).width, ((Rect)(ref val4)).height); GUI.Label(val5, chatMessage.msg, val3); ((Rect)(ref val5))..ctor(((Rect)(ref val4)).x - 1f, ((Rect)(ref val4)).y - 1f, ((Rect)(ref val4)).width, ((Rect)(ref val4)).height); GUI.Label(val5, chatMessage.msg, val3); GUI.Label(val4, chatMessage.msg, val2); num += 40f; } if (Plugin.EnableChatCommands != null && Plugin.EnableChatCommands.Value) { GUIStyle val6 = new GUIStyle(val2); val6.alignment = (TextAnchor)2; Rect val7 = default(Rect); ((Rect)(ref val7))..ctor((float)(Screen.width - 320), 20f, 300f, 50f); string text = ((_onCooldown && _cooldownTimer > 0f) ? $"<color=#FF5555>커맨드 쿨타임: {_cooldownTimer:F1}초</color>" : "<color=#55FF55>커맨드 사용 가능 \ud83d\udfe2</color>"); GUI.Label(val7, text, val6); } if (_voteState == VoteState.Voting) { GUIStyle val8 = new GUIStyle(val2); val8.fontSize = 28; val8.alignment = (TextAnchor)0; float num2 = 50f; float num3 = 100f; float num4 = 78f + (float)_currentVoteOptions.Count * 40f + 10f; GUI.Box(new Rect(30f, 90f, 640f, num4), ""); string text2 = $"<color=#FFFF00>[시청자 투표 진행중!] 남은 시간: {_voteTimer:F1}초</color>\n<size=20>채팅창에 번호(1, 2, 3)를 입력해 투표하세요!</size>"; GUI.Label(new Rect(num2, num3, 600f, 70f), text2, val8); num3 += 78f; val8.fontSize = 24; for (int i = 0; i < _currentVoteOptions.Count; i++) { string text3 = $"{i + 1}. {_currentVoteOptions[i].Title} <color=#AAAAFF>[{_currentVoteOptions[i].Votes}표]</color>"; GUI.Label(new Rect(num2, num3, 600f, 35f), text3, val8); num3 += 40f; } } } private void DrawTip(GUIStyle baseStyle, GUIStyle baseOutlineStyle) { //IL_05c5: Unknown result type (might be due to invalid IL or missing references) //IL_05cc: Expected O, but got Unknown //IL_05e0: Unknown result type (might be due to invalid IL or missing references) //IL_05e7: Expected O, but got Unknown //IL_0664: Unknown result type (might be due to invalid IL or missing references) //IL_069b: Unknown result type (might be due to invalid IL or missing references) //IL_06aa: Unknown result type (might be due to invalid IL or
Newtonsoft.Json.dll
Decompiled 11 hours 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.3.27908")] [assembly: AssemblyInformationalVersion("13.0.3+0a2e291c0d9c0c7675d445703e51750363a549ef")] [assembly: AssemblyProduct("Json.NET")] [assembly: AssemblyTitle("Json.NET .NET 4.5")] [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 = Volatile.Read(ref _mask); int num4 = num & num3; for (Entry entry = _entries[num4]; 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; Volatile.Write(ref _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) || StringUtils.IndexOf(text, '.') != -1 || StringUtils.IndexOf(text, 'E') != -1 || StringUtils.IndexOf(text, 'e') != -1) { return text; } return text + ".0"; } private static string EnsureDecimalPlace(string text) { if (StringUtils.IndexOf(text, '.') != -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; } internal 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.GetValueOrDef
UniTask.dll
Decompiled 11 hours 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.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using Cysharp.Threading.Tasks.CompilerServices; using Cysharp.Threading.Tasks.Internal; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Cysharp")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Cysharp, Inc.")] [assembly: AssemblyDescription("Provides an efficient async/await integration to Unity and .NET Core.")] [assembly: AssemblyFileVersion("2.5.10.0")] [assembly: AssemblyInformationalVersion("2.5.10+7c0f199fe0d3fc528024488ccd671e6c7b27745b")] [assembly: AssemblyProduct("UniTask")] [assembly: AssemblyTitle("UniTask")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Cysharp/UniTask")] [assembly: AssemblyVersion("2.5.10.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 { } internal sealed class AsyncMethodBuilderAttribute : Attribute { public Type BuilderType { get; } public AsyncMethodBuilderAttribute(Type builderType) { BuilderType = builderType; } } } namespace Cysharp.Threading.Tasks { [StructLayout(LayoutKind.Auto)] [AsyncMethodBuilder(typeof(AsyncUniTaskMethodBuilder))] public readonly struct UniTask { [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly struct YieldAwaitable { [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly struct Awaiter : ICriticalNotifyCompletion, INotifyCompletion { private static readonly SendOrPostCallback SendOrPostCallbackDelegate = Continuation; private static readonly WaitCallback WaitCallbackDelegate = Continuation; public bool IsCompleted => false; public void GetResult() { } public void OnCompleted(Action continuation) { UnsafeOnCompleted(continuation); } public void UnsafeOnCompleted(Action continuation) { SynchronizationContext current = SynchronizationContext.Current; if (current != null) { current.Post(SendOrPostCallbackDelegate, continuation); } else { ThreadPool.UnsafeQueueUserWorkItem(WaitCallbackDelegate, continuation); } } private static void Continuation(object state) { ((Action)state)(); } } public Awaiter GetAwaiter() { return default(Awaiter); } } private sealed class AsyncUnitSource : IUniTaskSource<AsyncUnit>, IUniTaskSource { private readonly IUniTaskSource source; public AsyncUnitSource(IUniTaskSource source) { this.source = source; } public AsyncUnit GetResult(short token) { source.GetResult(token); return AsyncUnit.Default; } public UniTaskStatus GetStatus(short token) { return source.GetStatus(token); } public void OnCompleted(Action<object> continuation, object state, short token) { source.OnCompleted(continuation, state, token); } public UniTaskStatus UnsafeGetStatus() { return source.UnsafeGetStatus(); } void IUniTaskSource.GetResult(short token) { GetResult(token); } } private sealed class IsCanceledSource : IUniTaskSource<bool>, IUniTaskSource { private readonly IUniTaskSource source; public IsCanceledSource(IUniTaskSource source) { this.source = source; } public bool GetResult(short token) { if (source.GetStatus(token) == UniTaskStatus.Canceled) { return true; } source.GetResult(token); return false; } void IUniTaskSource.GetResult(short token) { GetResult(token); } public UniTaskStatus GetStatus(short token) { return source.GetStatus(token); } public UniTaskStatus UnsafeGetStatus() { return source.UnsafeGetStatus(); } public void OnCompleted(Action<object> continuation, object state, short token) { source.OnCompleted(continuation, state, token); } } private sealed class MemoizeSource : IUniTaskSource { private IUniTaskSource source; private ExceptionDispatchInfo exception; private UniTaskStatus status; public MemoizeSource(IUniTaskSource source) { this.source = source; } public void GetResult(short token) { if (source == null) { if (exception != null) { exception.Throw(); } return; } try { source.GetResult(token); status = UniTaskStatus.Succeeded; } catch (Exception ex) { exception = ExceptionDispatchInfo.Capture(ex); if (ex is OperationCanceledException) { status = UniTaskStatus.Canceled; } else { status = UniTaskStatus.Faulted; } throw; } finally { source = null; } } public UniTaskStatus GetStatus(short token) { if (source == null) { return status; } return source.GetStatus(token); } public void OnCompleted(Action<object> continuation, object state, short token) { if (source == null) { continuation(state); } else { source.OnCompleted(continuation, state, token); } } public UniTaskStatus UnsafeGetStatus() { if (source == null) { return status; } return source.UnsafeGetStatus(); } } public readonly struct Awaiter : ICriticalNotifyCompletion, INotifyCompletion { private readonly UniTask task; public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] [DebuggerHidden] get { return task.Status.IsCompleted(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [DebuggerHidden] public Awaiter(in UniTask task) { this.task = task; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [DebuggerHidden] public void GetResult() { if (task.source != null) { task.source.GetResult(task.token); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [DebuggerHidden] public void OnCompleted(Action continuation) { if (task.source == null) { continuation(); } else { task.source.OnCompleted(AwaiterActions.InvokeContinuationDelegate, continuation, task.token); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [DebuggerHidden] public void UnsafeOnCompleted(Action continuation) { if (task.source == null) { continuation(); } else { task.source.OnCompleted(AwaiterActions.InvokeContinuationDelegate, continuation, task.token); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [DebuggerHidden] public void SourceOnCompleted(Action<object> continuation, object state) { if (task.source == null) { continuation(state); } else { task.source.OnCompleted(continuation, state, task.token); } } } private static class CanceledUniTaskCache<T> { public static readonly UniTask<T> Task; static CanceledUniTaskCache() { Task = new UniTask<T>(new CanceledResultSource<T>(CancellationToken.None), 0); } } private sealed class ExceptionResultSource : IUniTaskSource { private readonly ExceptionDispatchInfo exception; private bool calledGet; public ExceptionResultSource(Exception exception) { this.exception = ExceptionDispatchInfo.Capture(exception); } public void GetResult(short token) { if (!calledGet) { calledGet = true; GC.SuppressFinalize(this); } exception.Throw(); } public UniTaskStatus GetStatus(short token) { return UniTaskStatus.Faulted; } public UniTaskStatus UnsafeGetStatus() { return UniTaskStatus.Faulted; } public void OnCompleted(Action<object> continuation, object state, short token) { continuation(state); } ~ExceptionResultSource() { if (!calledGet) { UniTaskScheduler.PublishUnobservedTaskException(exception.SourceException); } } } private sealed class ExceptionResultSource<T> : IUniTaskSource<T>, IUniTaskSource { private readonly ExceptionDispatchInfo exception; private bool calledGet; public ExceptionResultSource(Exception exception) { this.exception = ExceptionDispatchInfo.Capture(exception); } public T GetResult(short token) { if (!calledGet) { calledGet = true; GC.SuppressFinalize(this); } exception.Throw(); return default(T); } void IUniTaskSource.GetResult(short token) { if (!calledGet) { calledGet = true; GC.SuppressFinalize(this); } exception.Throw(); } public UniTaskStatus GetStatus(short token) { return UniTaskStatus.Faulted; } public UniTaskStatus UnsafeGetStatus() { return UniTaskStatus.Faulted; } public void OnCompleted(Action<object> continuation, object state, short token) { continuation(state); } ~ExceptionResultSource() { if (!calledGet) { UniTaskScheduler.PublishUnobservedTaskException(exception.SourceException); } } } private sealed class CanceledResultSource : IUniTaskSource { private readonly CancellationToken cancellationToken; public CanceledResultSource(CancellationToken cancellationToken) { this.cancellationToken = cancellationToken; } public void GetResult(short token) { throw new OperationCanceledException(cancellationToken); } public UniTaskStatus GetStatus(short token) { return UniTaskStatus.Canceled; } public UniTaskStatus UnsafeGetStatus() { return UniTaskStatus.Canceled; } public void OnCompleted(Action<object> continuation, object state, short token) { continuation(state); } } private sealed class CanceledResultSource<T> : IUniTaskSource<T>, IUniTaskSource { private readonly CancellationToken cancellationToken; public CanceledResultSource(CancellationToken cancellationToken) { this.cancellationToken = cancellationToken; } public T GetResult(short token) { throw new OperationCanceledException(cancellationToken); } void IUniTaskSource.GetResult(short token) { throw new OperationCanceledException(cancellationToken); } public UniTaskStatus GetStatus(short token) { return UniTaskStatus.Canceled; } public UniTaskStatus UnsafeGetStatus() { return UniTaskStatus.Canceled; } public void OnCompleted(Action<object> continuation, object state, short token) { continuation(state); } } private sealed class DeferPromise : IUniTaskSource { private Func<UniTask> factory; private UniTask task; private Awaiter awaiter; public DeferPromise(Func<UniTask> factory) { this.factory = factory; } public void GetResult(short token) { awaiter.GetResult(); } public UniTaskStatus GetStatus(short token) { Func<UniTask> func = Interlocked.Exchange(ref factory, null); if (func != null) { task = func(); awaiter = task.GetAwaiter(); } return task.Status; } public void OnCompleted(Action<object> continuation, object state, short token) { awaiter.SourceOnCompleted(continuation, state); } public UniTaskStatus UnsafeGetStatus() { return task.Status; } } private sealed class DeferPromise<T> : IUniTaskSource<T>, IUniTaskSource { private Func<UniTask<T>> factory; private UniTask<T> task; private UniTask<T>.Awaiter awaiter; public DeferPromise(Func<UniTask<T>> factory) { this.factory = factory; } public T GetResult(short token) { return awaiter.GetResult(); } void IUniTaskSource.GetResult(short token) { awaiter.GetResult(); } public UniTaskStatus GetStatus(short token) { Func<UniTask<T>> func = Interlocked.Exchange(ref factory, null); if (func != null) { task = func(); awaiter = task.GetAwaiter(); } return task.Status; } public void OnCompleted(Action<object> continuation, object state, short token) { awaiter.SourceOnCompleted(continuation, state); } public UniTaskStatus UnsafeGetStatus() { return task.Status; } } private sealed class DeferPromiseWithState<TState> : IUniTaskSource { private Func<TState, UniTask> factory; private TState argument; private UniTask task; private Awaiter awaiter; public DeferPromiseWithState(TState argument, Func<TState, UniTask> factory) { this.argument = argument; this.factory = factory; } public void GetResult(short token) { awaiter.GetResult(); } public UniTaskStatus GetStatus(short token) { Func<TState, UniTask> func = Interlocked.Exchange(ref factory, null); if (func != null) { task = func(argument); awaiter = task.GetAwaiter(); } return task.Status; } public void OnCompleted(Action<object> continuation, object state, short token) { awaiter.SourceOnCompleted(continuation, state); } public UniTaskStatus UnsafeGetStatus() { return task.Status; } } private sealed class DeferPromiseWithState<TState, TResult> : IUniTaskSource<TResult>, IUniTaskSource { private Func<TState, UniTask<TResult>> factory; private TState argument; private UniTask<TResult> task; private UniTask<TResult>.Awaiter awaiter; public DeferPromiseWithState(TState argument, Func<TState, UniTask<TResult>> factory) { this.argument = argument; this.factory = factory; } public TResult GetResult(short token) { return awaiter.GetResult(); } void IUniTaskSource.GetResult(short token) { awaiter.GetResult(); } public UniTaskStatus GetStatus(short token) { Func<TState, UniTask<TResult>> func = Interlocked.Exchange(ref factory, null); if (func != null) { task = func(argument); awaiter = task.GetAwaiter(); } return task.Status; } public void OnCompleted(Action<object> continuation, object state, short token) { awaiter.SourceOnCompleted(continuation, state); } public UniTaskStatus UnsafeGetStatus() { return task.Status; } } private sealed class NeverPromise<T> : IUniTaskSource<T>, IUniTaskSource { private static readonly Action<object> cancellationCallback = CancellationCallback; private CancellationToken cancellationToken; private UniTaskCompletionSourceCore<T> core; public NeverPromise(CancellationToken cancellationToken) { this.cancellationToken = cancellationToken; if (this.cancellationToken.CanBeCanceled) { this.cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallback, this); } } private static void CancellationCallback(object state) { NeverPromise<T> neverPromise = (NeverPromise<T>)state; neverPromise.core.TrySetCanceled(neverPromise.cancellationToken); } public T GetResult(short token) { return core.GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } void IUniTaskSource.GetResult(short token) { core.GetResult(token); } } private sealed class WhenAllPromise<T> : IUniTaskSource<T[]>, IUniTaskSource { private T[] result; private int completeCount; private UniTaskCompletionSourceCore<T[]> core; public WhenAllPromise(UniTask<T>[] tasks, int tasksLength) { completeCount = 0; if (tasksLength == 0) { result = Array.Empty<T>(); core.TrySetResult(result); return; } result = new T[tasksLength]; for (int i = 0; i < tasksLength; i++) { UniTask<T>.Awaiter awaiter; try { awaiter = tasks[i].GetAwaiter(); } catch (Exception error) { core.TrySetException(error); continue; } if (awaiter.IsCompleted) { TryInvokeContinuation(this, in awaiter, i); continue; } awaiter.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T>, UniTask<T>.Awaiter, int> stateTuple = (StateTuple<WhenAllPromise<T>, UniTask<T>.Awaiter, int>)state; TryInvokeContinuation(stateTuple.Item1, in stateTuple.Item2, stateTuple.Item3); }, StateTuple.Create(this, awaiter, i)); } } private static void TryInvokeContinuation(WhenAllPromise<T> self, in UniTask<T>.Awaiter awaiter, int i) { try { self.result[i] = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completeCount) == self.result.Length) { self.core.TrySetResult(self.result); } } public T[] GetResult(short token) { GC.SuppressFinalize(this); return core.GetResult(token); } void IUniTaskSource.GetResult(short token) { GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } } private sealed class WhenAllPromise : IUniTaskSource { private int completeCount; private int tasksLength; private UniTaskCompletionSourceCore<AsyncUnit> core; public WhenAllPromise(UniTask[] tasks, int tasksLength) { this.tasksLength = tasksLength; completeCount = 0; if (tasksLength == 0) { core.TrySetResult(AsyncUnit.Default); return; } for (int i = 0; i < tasksLength; i++) { Awaiter awaiter; try { awaiter = tasks[i].GetAwaiter(); } catch (Exception error) { core.TrySetException(error); continue; } if (awaiter.IsCompleted) { TryInvokeContinuation(this, in awaiter); continue; } awaiter.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise, Awaiter> stateTuple = (StateTuple<WhenAllPromise, Awaiter>)state; TryInvokeContinuation(stateTuple.Item1, in stateTuple.Item2); }, StateTuple.Create(this, awaiter)); } } private static void TryInvokeContinuation(WhenAllPromise self, in Awaiter awaiter) { try { awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completeCount) == self.tasksLength) { self.core.TrySetResult(AsyncUnit.Default); } } public void GetResult(short token) { GC.SuppressFinalize(this); core.GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } } private sealed class WhenAllPromise<T1, T2> : IUniTaskSource<(T1, T2)>, IUniTaskSource { private T1 t1; private T2 t2; private int completedCount; private UniTaskCompletionSourceCore<(T1, T2)> core; public WhenAllPromise(UniTask<T1> task1, UniTask<T2> task2) { completedCount = 0; UniTask<T1>.Awaiter awaiter = task1.GetAwaiter(); if (awaiter.IsCompleted) { TryInvokeContinuationT1(this, in awaiter); } else { awaiter.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2>, UniTask<T1>.Awaiter> stateTuple2 = (StateTuple<WhenAllPromise<T1, T2>, UniTask<T1>.Awaiter>)state; TryInvokeContinuationT1(stateTuple2.Item1, in stateTuple2.Item2); }, StateTuple.Create(this, awaiter)); } UniTask<T2>.Awaiter awaiter2 = task2.GetAwaiter(); if (awaiter2.IsCompleted) { TryInvokeContinuationT2(this, in awaiter2); return; } awaiter2.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2>, UniTask<T2>.Awaiter> stateTuple = (StateTuple<WhenAllPromise<T1, T2>, UniTask<T2>.Awaiter>)state; TryInvokeContinuationT2(stateTuple.Item1, in stateTuple.Item2); }, StateTuple.Create(this, awaiter2)); } private static void TryInvokeContinuationT1(WhenAllPromise<T1, T2> self, in UniTask<T1>.Awaiter awaiter) { try { self.t1 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 2) { self.core.TrySetResult((self.t1, self.t2)); } } private static void TryInvokeContinuationT2(WhenAllPromise<T1, T2> self, in UniTask<T2>.Awaiter awaiter) { try { self.t2 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 2) { self.core.TrySetResult((self.t1, self.t2)); } } public (T1, T2) GetResult(short token) { GC.SuppressFinalize(this); return core.GetResult(token); } void IUniTaskSource.GetResult(short token) { GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } } private sealed class WhenAllPromise<T1, T2, T3> : IUniTaskSource<(T1, T2, T3)>, IUniTaskSource { private T1 t1; private T2 t2; private T3 t3; private int completedCount; private UniTaskCompletionSourceCore<(T1, T2, T3)> core; public WhenAllPromise(UniTask<T1> task1, UniTask<T2> task2, UniTask<T3> task3) { completedCount = 0; UniTask<T1>.Awaiter awaiter = task1.GetAwaiter(); if (awaiter.IsCompleted) { TryInvokeContinuationT1(this, in awaiter); } else { awaiter.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3>, UniTask<T1>.Awaiter> stateTuple3 = (StateTuple<WhenAllPromise<T1, T2, T3>, UniTask<T1>.Awaiter>)state; TryInvokeContinuationT1(stateTuple3.Item1, in stateTuple3.Item2); }, StateTuple.Create(this, awaiter)); } UniTask<T2>.Awaiter awaiter2 = task2.GetAwaiter(); if (awaiter2.IsCompleted) { TryInvokeContinuationT2(this, in awaiter2); } else { awaiter2.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3>, UniTask<T2>.Awaiter> stateTuple2 = (StateTuple<WhenAllPromise<T1, T2, T3>, UniTask<T2>.Awaiter>)state; TryInvokeContinuationT2(stateTuple2.Item1, in stateTuple2.Item2); }, StateTuple.Create(this, awaiter2)); } UniTask<T3>.Awaiter awaiter3 = task3.GetAwaiter(); if (awaiter3.IsCompleted) { TryInvokeContinuationT3(this, in awaiter3); return; } awaiter3.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3>, UniTask<T3>.Awaiter> stateTuple = (StateTuple<WhenAllPromise<T1, T2, T3>, UniTask<T3>.Awaiter>)state; TryInvokeContinuationT3(stateTuple.Item1, in stateTuple.Item2); }, StateTuple.Create(this, awaiter3)); } private static void TryInvokeContinuationT1(WhenAllPromise<T1, T2, T3> self, in UniTask<T1>.Awaiter awaiter) { try { self.t1 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 3) { self.core.TrySetResult((self.t1, self.t2, self.t3)); } } private static void TryInvokeContinuationT2(WhenAllPromise<T1, T2, T3> self, in UniTask<T2>.Awaiter awaiter) { try { self.t2 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 3) { self.core.TrySetResult((self.t1, self.t2, self.t3)); } } private static void TryInvokeContinuationT3(WhenAllPromise<T1, T2, T3> self, in UniTask<T3>.Awaiter awaiter) { try { self.t3 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 3) { self.core.TrySetResult((self.t1, self.t2, self.t3)); } } public (T1, T2, T3) GetResult(short token) { GC.SuppressFinalize(this); return core.GetResult(token); } void IUniTaskSource.GetResult(short token) { GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } } private sealed class WhenAllPromise<T1, T2, T3, T4> : IUniTaskSource<(T1, T2, T3, T4)>, IUniTaskSource { private T1 t1; private T2 t2; private T3 t3; private T4 t4; private int completedCount; private UniTaskCompletionSourceCore<(T1, T2, T3, T4)> core; public WhenAllPromise(UniTask<T1> task1, UniTask<T2> task2, UniTask<T3> task3, UniTask<T4> task4) { completedCount = 0; UniTask<T1>.Awaiter awaiter = task1.GetAwaiter(); if (awaiter.IsCompleted) { TryInvokeContinuationT1(this, in awaiter); } else { awaiter.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4>, UniTask<T1>.Awaiter> stateTuple4 = (StateTuple<WhenAllPromise<T1, T2, T3, T4>, UniTask<T1>.Awaiter>)state; TryInvokeContinuationT1(stateTuple4.Item1, in stateTuple4.Item2); }, StateTuple.Create(this, awaiter)); } UniTask<T2>.Awaiter awaiter2 = task2.GetAwaiter(); if (awaiter2.IsCompleted) { TryInvokeContinuationT2(this, in awaiter2); } else { awaiter2.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4>, UniTask<T2>.Awaiter> stateTuple3 = (StateTuple<WhenAllPromise<T1, T2, T3, T4>, UniTask<T2>.Awaiter>)state; TryInvokeContinuationT2(stateTuple3.Item1, in stateTuple3.Item2); }, StateTuple.Create(this, awaiter2)); } UniTask<T3>.Awaiter awaiter3 = task3.GetAwaiter(); if (awaiter3.IsCompleted) { TryInvokeContinuationT3(this, in awaiter3); } else { awaiter3.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4>, UniTask<T3>.Awaiter> stateTuple2 = (StateTuple<WhenAllPromise<T1, T2, T3, T4>, UniTask<T3>.Awaiter>)state; TryInvokeContinuationT3(stateTuple2.Item1, in stateTuple2.Item2); }, StateTuple.Create(this, awaiter3)); } UniTask<T4>.Awaiter awaiter4 = task4.GetAwaiter(); if (awaiter4.IsCompleted) { TryInvokeContinuationT4(this, in awaiter4); return; } awaiter4.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4>, UniTask<T4>.Awaiter> stateTuple = (StateTuple<WhenAllPromise<T1, T2, T3, T4>, UniTask<T4>.Awaiter>)state; TryInvokeContinuationT4(stateTuple.Item1, in stateTuple.Item2); }, StateTuple.Create(this, awaiter4)); } private static void TryInvokeContinuationT1(WhenAllPromise<T1, T2, T3, T4> self, in UniTask<T1>.Awaiter awaiter) { try { self.t1 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 4) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4)); } } private static void TryInvokeContinuationT2(WhenAllPromise<T1, T2, T3, T4> self, in UniTask<T2>.Awaiter awaiter) { try { self.t2 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 4) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4)); } } private static void TryInvokeContinuationT3(WhenAllPromise<T1, T2, T3, T4> self, in UniTask<T3>.Awaiter awaiter) { try { self.t3 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 4) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4)); } } private static void TryInvokeContinuationT4(WhenAllPromise<T1, T2, T3, T4> self, in UniTask<T4>.Awaiter awaiter) { try { self.t4 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 4) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4)); } } public (T1, T2, T3, T4) GetResult(short token) { GC.SuppressFinalize(this); return core.GetResult(token); } void IUniTaskSource.GetResult(short token) { GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } } private sealed class WhenAllPromise<T1, T2, T3, T4, T5> : IUniTaskSource<(T1, T2, T3, T4, T5)>, IUniTaskSource { private T1 t1; private T2 t2; private T3 t3; private T4 t4; private T5 t5; private int completedCount; private UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5)> core; public WhenAllPromise(UniTask<T1> task1, UniTask<T2> task2, UniTask<T3> task3, UniTask<T4> task4, UniTask<T5> task5) { completedCount = 0; UniTask<T1>.Awaiter awaiter = task1.GetAwaiter(); if (awaiter.IsCompleted) { TryInvokeContinuationT1(this, in awaiter); } else { awaiter.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5>, UniTask<T1>.Awaiter> stateTuple5 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5>, UniTask<T1>.Awaiter>)state; TryInvokeContinuationT1(stateTuple5.Item1, in stateTuple5.Item2); }, StateTuple.Create(this, awaiter)); } UniTask<T2>.Awaiter awaiter2 = task2.GetAwaiter(); if (awaiter2.IsCompleted) { TryInvokeContinuationT2(this, in awaiter2); } else { awaiter2.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5>, UniTask<T2>.Awaiter> stateTuple4 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5>, UniTask<T2>.Awaiter>)state; TryInvokeContinuationT2(stateTuple4.Item1, in stateTuple4.Item2); }, StateTuple.Create(this, awaiter2)); } UniTask<T3>.Awaiter awaiter3 = task3.GetAwaiter(); if (awaiter3.IsCompleted) { TryInvokeContinuationT3(this, in awaiter3); } else { awaiter3.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5>, UniTask<T3>.Awaiter> stateTuple3 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5>, UniTask<T3>.Awaiter>)state; TryInvokeContinuationT3(stateTuple3.Item1, in stateTuple3.Item2); }, StateTuple.Create(this, awaiter3)); } UniTask<T4>.Awaiter awaiter4 = task4.GetAwaiter(); if (awaiter4.IsCompleted) { TryInvokeContinuationT4(this, in awaiter4); } else { awaiter4.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5>, UniTask<T4>.Awaiter> stateTuple2 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5>, UniTask<T4>.Awaiter>)state; TryInvokeContinuationT4(stateTuple2.Item1, in stateTuple2.Item2); }, StateTuple.Create(this, awaiter4)); } UniTask<T5>.Awaiter awaiter5 = task5.GetAwaiter(); if (awaiter5.IsCompleted) { TryInvokeContinuationT5(this, in awaiter5); return; } awaiter5.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5>, UniTask<T5>.Awaiter> stateTuple = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5>, UniTask<T5>.Awaiter>)state; TryInvokeContinuationT5(stateTuple.Item1, in stateTuple.Item2); }, StateTuple.Create(this, awaiter5)); } private static void TryInvokeContinuationT1(WhenAllPromise<T1, T2, T3, T4, T5> self, in UniTask<T1>.Awaiter awaiter) { try { self.t1 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 5) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5)); } } private static void TryInvokeContinuationT2(WhenAllPromise<T1, T2, T3, T4, T5> self, in UniTask<T2>.Awaiter awaiter) { try { self.t2 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 5) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5)); } } private static void TryInvokeContinuationT3(WhenAllPromise<T1, T2, T3, T4, T5> self, in UniTask<T3>.Awaiter awaiter) { try { self.t3 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 5) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5)); } } private static void TryInvokeContinuationT4(WhenAllPromise<T1, T2, T3, T4, T5> self, in UniTask<T4>.Awaiter awaiter) { try { self.t4 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 5) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5)); } } private static void TryInvokeContinuationT5(WhenAllPromise<T1, T2, T3, T4, T5> self, in UniTask<T5>.Awaiter awaiter) { try { self.t5 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 5) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5)); } } public (T1, T2, T3, T4, T5) GetResult(short token) { GC.SuppressFinalize(this); return core.GetResult(token); } void IUniTaskSource.GetResult(short token) { GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } } private sealed class WhenAllPromise<T1, T2, T3, T4, T5, T6> : IUniTaskSource<(T1, T2, T3, T4, T5, T6)>, IUniTaskSource { private T1 t1; private T2 t2; private T3 t3; private T4 t4; private T5 t5; private T6 t6; private int completedCount; private UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6)> core; public WhenAllPromise(UniTask<T1> task1, UniTask<T2> task2, UniTask<T3> task3, UniTask<T4> task4, UniTask<T5> task5, UniTask<T6> task6) { completedCount = 0; UniTask<T1>.Awaiter awaiter = task1.GetAwaiter(); if (awaiter.IsCompleted) { TryInvokeContinuationT1(this, in awaiter); } else { awaiter.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6>, UniTask<T1>.Awaiter> stateTuple6 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6>, UniTask<T1>.Awaiter>)state; TryInvokeContinuationT1(stateTuple6.Item1, in stateTuple6.Item2); }, StateTuple.Create(this, awaiter)); } UniTask<T2>.Awaiter awaiter2 = task2.GetAwaiter(); if (awaiter2.IsCompleted) { TryInvokeContinuationT2(this, in awaiter2); } else { awaiter2.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6>, UniTask<T2>.Awaiter> stateTuple5 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6>, UniTask<T2>.Awaiter>)state; TryInvokeContinuationT2(stateTuple5.Item1, in stateTuple5.Item2); }, StateTuple.Create(this, awaiter2)); } UniTask<T3>.Awaiter awaiter3 = task3.GetAwaiter(); if (awaiter3.IsCompleted) { TryInvokeContinuationT3(this, in awaiter3); } else { awaiter3.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6>, UniTask<T3>.Awaiter> stateTuple4 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6>, UniTask<T3>.Awaiter>)state; TryInvokeContinuationT3(stateTuple4.Item1, in stateTuple4.Item2); }, StateTuple.Create(this, awaiter3)); } UniTask<T4>.Awaiter awaiter4 = task4.GetAwaiter(); if (awaiter4.IsCompleted) { TryInvokeContinuationT4(this, in awaiter4); } else { awaiter4.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6>, UniTask<T4>.Awaiter> stateTuple3 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6>, UniTask<T4>.Awaiter>)state; TryInvokeContinuationT4(stateTuple3.Item1, in stateTuple3.Item2); }, StateTuple.Create(this, awaiter4)); } UniTask<T5>.Awaiter awaiter5 = task5.GetAwaiter(); if (awaiter5.IsCompleted) { TryInvokeContinuationT5(this, in awaiter5); } else { awaiter5.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6>, UniTask<T5>.Awaiter> stateTuple2 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6>, UniTask<T5>.Awaiter>)state; TryInvokeContinuationT5(stateTuple2.Item1, in stateTuple2.Item2); }, StateTuple.Create(this, awaiter5)); } UniTask<T6>.Awaiter awaiter6 = task6.GetAwaiter(); if (awaiter6.IsCompleted) { TryInvokeContinuationT6(this, in awaiter6); return; } awaiter6.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6>, UniTask<T6>.Awaiter> stateTuple = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6>, UniTask<T6>.Awaiter>)state; TryInvokeContinuationT6(stateTuple.Item1, in stateTuple.Item2); }, StateTuple.Create(this, awaiter6)); } private static void TryInvokeContinuationT1(WhenAllPromise<T1, T2, T3, T4, T5, T6> self, in UniTask<T1>.Awaiter awaiter) { try { self.t1 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 6) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6)); } } private static void TryInvokeContinuationT2(WhenAllPromise<T1, T2, T3, T4, T5, T6> self, in UniTask<T2>.Awaiter awaiter) { try { self.t2 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 6) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6)); } } private static void TryInvokeContinuationT3(WhenAllPromise<T1, T2, T3, T4, T5, T6> self, in UniTask<T3>.Awaiter awaiter) { try { self.t3 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 6) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6)); } } private static void TryInvokeContinuationT4(WhenAllPromise<T1, T2, T3, T4, T5, T6> self, in UniTask<T4>.Awaiter awaiter) { try { self.t4 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 6) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6)); } } private static void TryInvokeContinuationT5(WhenAllPromise<T1, T2, T3, T4, T5, T6> self, in UniTask<T5>.Awaiter awaiter) { try { self.t5 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 6) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6)); } } private static void TryInvokeContinuationT6(WhenAllPromise<T1, T2, T3, T4, T5, T6> self, in UniTask<T6>.Awaiter awaiter) { try { self.t6 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 6) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6)); } } public (T1, T2, T3, T4, T5, T6) GetResult(short token) { GC.SuppressFinalize(this); return core.GetResult(token); } void IUniTaskSource.GetResult(short token) { GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } } private sealed class WhenAllPromise<T1, T2, T3, T4, T5, T6, T7> : IUniTaskSource<(T1, T2, T3, T4, T5, T6, T7)>, IUniTaskSource { private T1 t1; private T2 t2; private T3 t3; private T4 t4; private T5 t5; private T6 t6; private T7 t7; private int completedCount; private UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6, T7)> core; public WhenAllPromise(UniTask<T1> task1, UniTask<T2> task2, UniTask<T3> task3, UniTask<T4> task4, UniTask<T5> task5, UniTask<T6> task6, UniTask<T7> task7) { completedCount = 0; UniTask<T1>.Awaiter awaiter = task1.GetAwaiter(); if (awaiter.IsCompleted) { TryInvokeContinuationT1(this, in awaiter); } else { awaiter.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7>, UniTask<T1>.Awaiter> stateTuple7 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7>, UniTask<T1>.Awaiter>)state; TryInvokeContinuationT1(stateTuple7.Item1, in stateTuple7.Item2); }, StateTuple.Create(this, awaiter)); } UniTask<T2>.Awaiter awaiter2 = task2.GetAwaiter(); if (awaiter2.IsCompleted) { TryInvokeContinuationT2(this, in awaiter2); } else { awaiter2.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7>, UniTask<T2>.Awaiter> stateTuple6 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7>, UniTask<T2>.Awaiter>)state; TryInvokeContinuationT2(stateTuple6.Item1, in stateTuple6.Item2); }, StateTuple.Create(this, awaiter2)); } UniTask<T3>.Awaiter awaiter3 = task3.GetAwaiter(); if (awaiter3.IsCompleted) { TryInvokeContinuationT3(this, in awaiter3); } else { awaiter3.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7>, UniTask<T3>.Awaiter> stateTuple5 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7>, UniTask<T3>.Awaiter>)state; TryInvokeContinuationT3(stateTuple5.Item1, in stateTuple5.Item2); }, StateTuple.Create(this, awaiter3)); } UniTask<T4>.Awaiter awaiter4 = task4.GetAwaiter(); if (awaiter4.IsCompleted) { TryInvokeContinuationT4(this, in awaiter4); } else { awaiter4.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7>, UniTask<T4>.Awaiter> stateTuple4 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7>, UniTask<T4>.Awaiter>)state; TryInvokeContinuationT4(stateTuple4.Item1, in stateTuple4.Item2); }, StateTuple.Create(this, awaiter4)); } UniTask<T5>.Awaiter awaiter5 = task5.GetAwaiter(); if (awaiter5.IsCompleted) { TryInvokeContinuationT5(this, in awaiter5); } else { awaiter5.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7>, UniTask<T5>.Awaiter> stateTuple3 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7>, UniTask<T5>.Awaiter>)state; TryInvokeContinuationT5(stateTuple3.Item1, in stateTuple3.Item2); }, StateTuple.Create(this, awaiter5)); } UniTask<T6>.Awaiter awaiter6 = task6.GetAwaiter(); if (awaiter6.IsCompleted) { TryInvokeContinuationT6(this, in awaiter6); } else { awaiter6.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7>, UniTask<T6>.Awaiter> stateTuple2 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7>, UniTask<T6>.Awaiter>)state; TryInvokeContinuationT6(stateTuple2.Item1, in stateTuple2.Item2); }, StateTuple.Create(this, awaiter6)); } UniTask<T7>.Awaiter awaiter7 = task7.GetAwaiter(); if (awaiter7.IsCompleted) { TryInvokeContinuationT7(this, in awaiter7); return; } awaiter7.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7>, UniTask<T7>.Awaiter> stateTuple = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7>, UniTask<T7>.Awaiter>)state; TryInvokeContinuationT7(stateTuple.Item1, in stateTuple.Item2); }, StateTuple.Create(this, awaiter7)); } private static void TryInvokeContinuationT1(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7> self, in UniTask<T1>.Awaiter awaiter) { try { self.t1 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 7) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7)); } } private static void TryInvokeContinuationT2(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7> self, in UniTask<T2>.Awaiter awaiter) { try { self.t2 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 7) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7)); } } private static void TryInvokeContinuationT3(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7> self, in UniTask<T3>.Awaiter awaiter) { try { self.t3 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 7) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7)); } } private static void TryInvokeContinuationT4(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7> self, in UniTask<T4>.Awaiter awaiter) { try { self.t4 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 7) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7)); } } private static void TryInvokeContinuationT5(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7> self, in UniTask<T5>.Awaiter awaiter) { try { self.t5 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 7) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7)); } } private static void TryInvokeContinuationT6(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7> self, in UniTask<T6>.Awaiter awaiter) { try { self.t6 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 7) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7)); } } private static void TryInvokeContinuationT7(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7> self, in UniTask<T7>.Awaiter awaiter) { try { self.t7 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 7) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7)); } } public (T1, T2, T3, T4, T5, T6, T7) GetResult(short token) { GC.SuppressFinalize(this); return core.GetResult(token); } void IUniTaskSource.GetResult(short token) { GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } } private sealed class WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8> : IUniTaskSource<(T1, T2, T3, T4, T5, T6, T7, T8)>, IUniTaskSource { private T1 t1; private T2 t2; private T3 t3; private T4 t4; private T5 t5; private T6 t6; private T7 t7; private T8 t8; private int completedCount; private UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6, T7, T8)> core; public WhenAllPromise(UniTask<T1> task1, UniTask<T2> task2, UniTask<T3> task3, UniTask<T4> task4, UniTask<T5> task5, UniTask<T6> task6, UniTask<T7> task7, UniTask<T8> task8) { completedCount = 0; UniTask<T1>.Awaiter awaiter = task1.GetAwaiter(); if (awaiter.IsCompleted) { TryInvokeContinuationT1(this, in awaiter); } else { awaiter.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T1>.Awaiter> stateTuple8 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T1>.Awaiter>)state; TryInvokeContinuationT1(stateTuple8.Item1, in stateTuple8.Item2); }, StateTuple.Create(this, awaiter)); } UniTask<T2>.Awaiter awaiter2 = task2.GetAwaiter(); if (awaiter2.IsCompleted) { TryInvokeContinuationT2(this, in awaiter2); } else { awaiter2.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T2>.Awaiter> stateTuple7 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T2>.Awaiter>)state; TryInvokeContinuationT2(stateTuple7.Item1, in stateTuple7.Item2); }, StateTuple.Create(this, awaiter2)); } UniTask<T3>.Awaiter awaiter3 = task3.GetAwaiter(); if (awaiter3.IsCompleted) { TryInvokeContinuationT3(this, in awaiter3); } else { awaiter3.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T3>.Awaiter> stateTuple6 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T3>.Awaiter>)state; TryInvokeContinuationT3(stateTuple6.Item1, in stateTuple6.Item2); }, StateTuple.Create(this, awaiter3)); } UniTask<T4>.Awaiter awaiter4 = task4.GetAwaiter(); if (awaiter4.IsCompleted) { TryInvokeContinuationT4(this, in awaiter4); } else { awaiter4.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T4>.Awaiter> stateTuple5 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T4>.Awaiter>)state; TryInvokeContinuationT4(stateTuple5.Item1, in stateTuple5.Item2); }, StateTuple.Create(this, awaiter4)); } UniTask<T5>.Awaiter awaiter5 = task5.GetAwaiter(); if (awaiter5.IsCompleted) { TryInvokeContinuationT5(this, in awaiter5); } else { awaiter5.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T5>.Awaiter> stateTuple4 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T5>.Awaiter>)state; TryInvokeContinuationT5(stateTuple4.Item1, in stateTuple4.Item2); }, StateTuple.Create(this, awaiter5)); } UniTask<T6>.Awaiter awaiter6 = task6.GetAwaiter(); if (awaiter6.IsCompleted) { TryInvokeContinuationT6(this, in awaiter6); } else { awaiter6.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T6>.Awaiter> stateTuple3 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T6>.Awaiter>)state; TryInvokeContinuationT6(stateTuple3.Item1, in stateTuple3.Item2); }, StateTuple.Create(this, awaiter6)); } UniTask<T7>.Awaiter awaiter7 = task7.GetAwaiter(); if (awaiter7.IsCompleted) { TryInvokeContinuationT7(this, in awaiter7); } else { awaiter7.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T7>.Awaiter> stateTuple2 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T7>.Awaiter>)state; TryInvokeContinuationT7(stateTuple2.Item1, in stateTuple2.Item2); }, StateTuple.Create(this, awaiter7)); } UniTask<T8>.Awaiter awaiter8 = task8.GetAwaiter(); if (awaiter8.IsCompleted) { TryInvokeContinuationT8(this, in awaiter8); return; } awaiter8.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T8>.Awaiter> stateTuple = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8>, UniTask<T8>.Awaiter>)state; TryInvokeContinuationT8(stateTuple.Item1, in stateTuple.Item2); }, StateTuple.Create(this, awaiter8)); } private static void TryInvokeContinuationT1(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8> self, in UniTask<T1>.Awaiter awaiter) { try { self.t1 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 8) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); } } private static void TryInvokeContinuationT2(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8> self, in UniTask<T2>.Awaiter awaiter) { try { self.t2 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 8) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); } } private static void TryInvokeContinuationT3(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8> self, in UniTask<T3>.Awaiter awaiter) { try { self.t3 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 8) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); } } private static void TryInvokeContinuationT4(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8> self, in UniTask<T4>.Awaiter awaiter) { try { self.t4 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 8) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); } } private static void TryInvokeContinuationT5(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8> self, in UniTask<T5>.Awaiter awaiter) { try { self.t5 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 8) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); } } private static void TryInvokeContinuationT6(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8> self, in UniTask<T6>.Awaiter awaiter) { try { self.t6 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 8) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); } } private static void TryInvokeContinuationT7(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8> self, in UniTask<T7>.Awaiter awaiter) { try { self.t7 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 8) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); } } private static void TryInvokeContinuationT8(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8> self, in UniTask<T8>.Awaiter awaiter) { try { self.t8 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 8) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); } } public (T1, T2, T3, T4, T5, T6, T7, T8) GetResult(short token) { GC.SuppressFinalize(this); return core.GetResult(token); } void IUniTaskSource.GetResult(short token) { GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } } private sealed class WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9> : IUniTaskSource<(T1, T2, T3, T4, T5, T6, T7, T8, T9)>, IUniTaskSource { private T1 t1; private T2 t2; private T3 t3; private T4 t4; private T5 t5; private T6 t6; private T7 t7; private T8 t8; private T9 t9; private int completedCount; private UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6, T7, T8, T9)> core; public WhenAllPromise(UniTask<T1> task1, UniTask<T2> task2, UniTask<T3> task3, UniTask<T4> task4, UniTask<T5> task5, UniTask<T6> task6, UniTask<T7> task7, UniTask<T8> task8, UniTask<T9> task9) { completedCount = 0; UniTask<T1>.Awaiter awaiter = task1.GetAwaiter(); if (awaiter.IsCompleted) { TryInvokeContinuationT1(this, in awaiter); } else { awaiter.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T1>.Awaiter> stateTuple9 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T1>.Awaiter>)state; TryInvokeContinuationT1(stateTuple9.Item1, in stateTuple9.Item2); }, StateTuple.Create(this, awaiter)); } UniTask<T2>.Awaiter awaiter2 = task2.GetAwaiter(); if (awaiter2.IsCompleted) { TryInvokeContinuationT2(this, in awaiter2); } else { awaiter2.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T2>.Awaiter> stateTuple8 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T2>.Awaiter>)state; TryInvokeContinuationT2(stateTuple8.Item1, in stateTuple8.Item2); }, StateTuple.Create(this, awaiter2)); } UniTask<T3>.Awaiter awaiter3 = task3.GetAwaiter(); if (awaiter3.IsCompleted) { TryInvokeContinuationT3(this, in awaiter3); } else { awaiter3.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T3>.Awaiter> stateTuple7 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T3>.Awaiter>)state; TryInvokeContinuationT3(stateTuple7.Item1, in stateTuple7.Item2); }, StateTuple.Create(this, awaiter3)); } UniTask<T4>.Awaiter awaiter4 = task4.GetAwaiter(); if (awaiter4.IsCompleted) { TryInvokeContinuationT4(this, in awaiter4); } else { awaiter4.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T4>.Awaiter> stateTuple6 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T4>.Awaiter>)state; TryInvokeContinuationT4(stateTuple6.Item1, in stateTuple6.Item2); }, StateTuple.Create(this, awaiter4)); } UniTask<T5>.Awaiter awaiter5 = task5.GetAwaiter(); if (awaiter5.IsCompleted) { TryInvokeContinuationT5(this, in awaiter5); } else { awaiter5.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T5>.Awaiter> stateTuple5 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T5>.Awaiter>)state; TryInvokeContinuationT5(stateTuple5.Item1, in stateTuple5.Item2); }, StateTuple.Create(this, awaiter5)); } UniTask<T6>.Awaiter awaiter6 = task6.GetAwaiter(); if (awaiter6.IsCompleted) { TryInvokeContinuationT6(this, in awaiter6); } else { awaiter6.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T6>.Awaiter> stateTuple4 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T6>.Awaiter>)state; TryInvokeContinuationT6(stateTuple4.Item1, in stateTuple4.Item2); }, StateTuple.Create(this, awaiter6)); } UniTask<T7>.Awaiter awaiter7 = task7.GetAwaiter(); if (awaiter7.IsCompleted) { TryInvokeContinuationT7(this, in awaiter7); } else { awaiter7.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T7>.Awaiter> stateTuple3 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T7>.Awaiter>)state; TryInvokeContinuationT7(stateTuple3.Item1, in stateTuple3.Item2); }, StateTuple.Create(this, awaiter7)); } UniTask<T8>.Awaiter awaiter8 = task8.GetAwaiter(); if (awaiter8.IsCompleted) { TryInvokeContinuationT8(this, in awaiter8); } else { awaiter8.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T8>.Awaiter> stateTuple2 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T8>.Awaiter>)state; TryInvokeContinuationT8(stateTuple2.Item1, in stateTuple2.Item2); }, StateTuple.Create(this, awaiter8)); } UniTask<T9>.Awaiter awaiter9 = task9.GetAwaiter(); if (awaiter9.IsCompleted) { TryInvokeContinuationT9(this, in awaiter9); return; } awaiter9.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T9>.Awaiter> stateTuple = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9>, UniTask<T9>.Awaiter>)state; TryInvokeContinuationT9(stateTuple.Item1, in stateTuple.Item2); }, StateTuple.Create(this, awaiter9)); } private static void TryInvokeContinuationT1(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9> self, in UniTask<T1>.Awaiter awaiter) { try { self.t1 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 9) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); } } private static void TryInvokeContinuationT2(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9> self, in UniTask<T2>.Awaiter awaiter) { try { self.t2 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 9) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); } } private static void TryInvokeContinuationT3(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9> self, in UniTask<T3>.Awaiter awaiter) { try { self.t3 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 9) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); } } private static void TryInvokeContinuationT4(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9> self, in UniTask<T4>.Awaiter awaiter) { try { self.t4 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 9) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); } } private static void TryInvokeContinuationT5(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9> self, in UniTask<T5>.Awaiter awaiter) { try { self.t5 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 9) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); } } private static void TryInvokeContinuationT6(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9> self, in UniTask<T6>.Awaiter awaiter) { try { self.t6 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 9) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); } } private static void TryInvokeContinuationT7(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9> self, in UniTask<T7>.Awaiter awaiter) { try { self.t7 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 9) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); } } private static void TryInvokeContinuationT8(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9> self, in UniTask<T8>.Awaiter awaiter) { try { self.t8 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 9) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); } } private static void TryInvokeContinuationT9(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9> self, in UniTask<T9>.Awaiter awaiter) { try { self.t9 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 9) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); } } public (T1, T2, T3, T4, T5, T6, T7, T8, T9) GetResult(short token) { GC.SuppressFinalize(this); return core.GetResult(token); } void IUniTaskSource.GetResult(short token) { GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } } private sealed class WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> : IUniTaskSource<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)>, IUniTaskSource { private T1 t1; private T2 t2; private T3 t3; private T4 t4; private T5 t5; private T6 t6; private T7 t7; private T8 t8; private T9 t9; private T10 t10; private int completedCount; private UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)> core; public WhenAllPromise(UniTask<T1> task1, UniTask<T2> task2, UniTask<T3> task3, UniTask<T4> task4, UniTask<T5> task5, UniTask<T6> task6, UniTask<T7> task7, UniTask<T8> task8, UniTask<T9> task9, UniTask<T10> task10) { completedCount = 0; UniTask<T1>.Awaiter awaiter = task1.GetAwaiter(); if (awaiter.IsCompleted) { TryInvokeContinuationT1(this, in awaiter); } else { awaiter.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T1>.Awaiter> stateTuple10 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T1>.Awaiter>)state; TryInvokeContinuationT1(stateTuple10.Item1, in stateTuple10.Item2); }, StateTuple.Create(this, awaiter)); } UniTask<T2>.Awaiter awaiter2 = task2.GetAwaiter(); if (awaiter2.IsCompleted) { TryInvokeContinuationT2(this, in awaiter2); } else { awaiter2.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T2>.Awaiter> stateTuple9 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T2>.Awaiter>)state; TryInvokeContinuationT2(stateTuple9.Item1, in stateTuple9.Item2); }, StateTuple.Create(this, awaiter2)); } UniTask<T3>.Awaiter awaiter3 = task3.GetAwaiter(); if (awaiter3.IsCompleted) { TryInvokeContinuationT3(this, in awaiter3); } else { awaiter3.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T3>.Awaiter> stateTuple8 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T3>.Awaiter>)state; TryInvokeContinuationT3(stateTuple8.Item1, in stateTuple8.Item2); }, StateTuple.Create(this, awaiter3)); } UniTask<T4>.Awaiter awaiter4 = task4.GetAwaiter(); if (awaiter4.IsCompleted) { TryInvokeContinuationT4(this, in awaiter4); } else { awaiter4.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T4>.Awaiter> stateTuple7 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T4>.Awaiter>)state; TryInvokeContinuationT4(stateTuple7.Item1, in stateTuple7.Item2); }, StateTuple.Create(this, awaiter4)); } UniTask<T5>.Awaiter awaiter5 = task5.GetAwaiter(); if (awaiter5.IsCompleted) { TryInvokeContinuationT5(this, in awaiter5); } else { awaiter5.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T5>.Awaiter> stateTuple6 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T5>.Awaiter>)state; TryInvokeContinuationT5(stateTuple6.Item1, in stateTuple6.Item2); }, StateTuple.Create(this, awaiter5)); } UniTask<T6>.Awaiter awaiter6 = task6.GetAwaiter(); if (awaiter6.IsCompleted) { TryInvokeContinuationT6(this, in awaiter6); } else { awaiter6.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T6>.Awaiter> stateTuple5 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T6>.Awaiter>)state; TryInvokeContinuationT6(stateTuple5.Item1, in stateTuple5.Item2); }, StateTuple.Create(this, awaiter6)); } UniTask<T7>.Awaiter awaiter7 = task7.GetAwaiter(); if (awaiter7.IsCompleted) { TryInvokeContinuationT7(this, in awaiter7); } else { awaiter7.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T7>.Awaiter> stateTuple4 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T7>.Awaiter>)state; TryInvokeContinuationT7(stateTuple4.Item1, in stateTuple4.Item2); }, StateTuple.Create(this, awaiter7)); } UniTask<T8>.Awaiter awaiter8 = task8.GetAwaiter(); if (awaiter8.IsCompleted) { TryInvokeContinuationT8(this, in awaiter8); } else { awaiter8.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T8>.Awaiter> stateTuple3 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T8>.Awaiter>)state; TryInvokeContinuationT8(stateTuple3.Item1, in stateTuple3.Item2); }, StateTuple.Create(this, awaiter8)); } UniTask<T9>.Awaiter awaiter9 = task9.GetAwaiter(); if (awaiter9.IsCompleted) { TryInvokeContinuationT9(this, in awaiter9); } else { awaiter9.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T9>.Awaiter> stateTuple2 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T9>.Awaiter>)state; TryInvokeContinuationT9(stateTuple2.Item1, in stateTuple2.Item2); }, StateTuple.Create(this, awaiter9)); } UniTask<T10>.Awaiter awaiter10 = task10.GetAwaiter(); if (awaiter10.IsCompleted) { TryInvokeContinuationT10(this, in awaiter10); return; } awaiter10.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T10>.Awaiter> stateTuple = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, UniTask<T10>.Awaiter>)state; TryInvokeContinuationT10(stateTuple.Item1, in stateTuple.Item2); }, StateTuple.Create(this, awaiter10)); } private static void TryInvokeContinuationT1(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> self, in UniTask<T1>.Awaiter awaiter) { try { self.t1 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 10) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); } } private static void TryInvokeContinuationT2(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> self, in UniTask<T2>.Awaiter awaiter) { try { self.t2 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 10) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); } } private static void TryInvokeContinuationT3(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> self, in UniTask<T3>.Awaiter awaiter) { try { self.t3 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 10) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); } } private static void TryInvokeContinuationT4(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> self, in UniTask<T4>.Awaiter awaiter) { try { self.t4 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 10) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); } } private static void TryInvokeContinuationT5(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> self, in UniTask<T5>.Awaiter awaiter) { try { self.t5 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 10) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); } } private static void TryInvokeContinuationT6(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> self, in UniTask<T6>.Awaiter awaiter) { try { self.t6 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 10) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); } } private static void TryInvokeContinuationT7(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> self, in UniTask<T7>.Awaiter awaiter) { try { self.t7 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 10) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); } } private static void TryInvokeContinuationT8(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> self, in UniTask<T8>.Awaiter awaiter) { try { self.t8 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 10) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); } } private static void TryInvokeContinuationT9(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> self, in UniTask<T9>.Awaiter awaiter) { try { self.t9 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 10) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); } } private static void TryInvokeContinuationT10(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> self, in UniTask<T10>.Awaiter awaiter) { try { self.t10 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 10) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); } } public (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) GetResult(short token) { GC.SuppressFinalize(this); return core.GetResult(token); } void IUniTaskSource.GetResult(short token) { GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } } private sealed class WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> : IUniTaskSource<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)>, IUniTaskSource { private T1 t1; private T2 t2; private T3 t3; private T4 t4; private T5 t5; private T6 t6; private T7 t7; private T8 t8; private T9 t9; private T10 t10; private T11 t11; private int completedCount; private UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)> core; public WhenAllPromise(UniTask<T1> task1, UniTask<T2> task2, UniTask<T3> task3, UniTask<T4> task4, UniTask<T5> task5, UniTask<T6> task6, UniTask<T7> task7, UniTask<T8> task8, UniTask<T9> task9, UniTask<T10> task10, UniTask<T11> task11) { completedCount = 0; UniTask<T1>.Awaiter awaiter = task1.GetAwaiter(); if (awaiter.IsCompleted) { TryInvokeContinuationT1(this, in awaiter); } else { awaiter.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T1>.Awaiter> stateTuple11 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T1>.Awaiter>)state; TryInvokeContinuationT1(stateTuple11.Item1, in stateTuple11.Item2); }, StateTuple.Create(this, awaiter)); } UniTask<T2>.Awaiter awaiter2 = task2.GetAwaiter(); if (awaiter2.IsCompleted) { TryInvokeContinuationT2(this, in awaiter2); } else { awaiter2.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T2>.Awaiter> stateTuple10 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T2>.Awaiter>)state; TryInvokeContinuationT2(stateTuple10.Item1, in stateTuple10.Item2); }, StateTuple.Create(this, awaiter2)); } UniTask<T3>.Awaiter awaiter3 = task3.GetAwaiter(); if (awaiter3.IsCompleted) { TryInvokeContinuationT3(this, in awaiter3); } else { awaiter3.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T3>.Awaiter> stateTuple9 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T3>.Awaiter>)state; TryInvokeContinuationT3(stateTuple9.Item1, in stateTuple9.Item2); }, StateTuple.Create(this, awaiter3)); } UniTask<T4>.Awaiter awaiter4 = task4.GetAwaiter(); if (awaiter4.IsCompleted) { TryInvokeContinuationT4(this, in awaiter4); } else { awaiter4.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T4>.Awaiter> stateTuple8 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T4>.Awaiter>)state; TryInvokeContinuationT4(stateTuple8.Item1, in stateTuple8.Item2); }, StateTuple.Create(this, awaiter4)); } UniTask<T5>.Awaiter awaiter5 = task5.GetAwaiter(); if (awaiter5.IsCompleted) { TryInvokeContinuationT5(this, in awaiter5); } else { awaiter5.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T5>.Awaiter> stateTuple7 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T5>.Awaiter>)state; TryInvokeContinuationT5(stateTuple7.Item1, in stateTuple7.Item2); }, StateTuple.Create(this, awaiter5)); } UniTask<T6>.Awaiter awaiter6 = task6.GetAwaiter(); if (awaiter6.IsCompleted) { TryInvokeContinuationT6(this, in awaiter6); } else { awaiter6.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T6>.Awaiter> stateTuple6 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T6>.Awaiter>)state; TryInvokeContinuationT6(stateTuple6.Item1, in stateTuple6.Item2); }, StateTuple.Create(this, awaiter6)); } UniTask<T7>.Awaiter awaiter7 = task7.GetAwaiter(); if (awaiter7.IsCompleted) { TryInvokeContinuationT7(this, in awaiter7); } else { awaiter7.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T7>.Awaiter> stateTuple5 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T7>.Awaiter>)state; TryInvokeContinuationT7(stateTuple5.Item1, in stateTuple5.Item2); }, StateTuple.Create(this, awaiter7)); } UniTask<T8>.Awaiter awaiter8 = task8.GetAwaiter(); if (awaiter8.IsCompleted) { TryInvokeContinuationT8(this, in awaiter8); } else { awaiter8.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T8>.Awaiter> stateTuple4 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T8>.Awaiter>)state; TryInvokeContinuationT8(stateTuple4.Item1, in stateTuple4.Item2); }, StateTuple.Create(this, awaiter8)); } UniTask<T9>.Awaiter awaiter9 = task9.GetAwaiter(); if (awaiter9.IsCompleted) { TryInvokeContinuationT9(this, in awaiter9); } else { awaiter9.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T9>.Awaiter> stateTuple3 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T9>.Awaiter>)state; TryInvokeContinuationT9(stateTuple3.Item1, in stateTuple3.Item2); }, StateTuple.Create(this, awaiter9)); } UniTask<T10>.Awaiter awaiter10 = task10.GetAwaiter(); if (awaiter10.IsCompleted) { TryInvokeContinuationT10(this, in awaiter10); } else { awaiter10.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T10>.Awaiter> stateTuple2 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T10>.Awaiter>)state; TryInvokeContinuationT10(stateTuple2.Item1, in stateTuple2.Item2); }, StateTuple.Create(this, awaiter10)); } UniTask<T11>.Awaiter awaiter11 = task11.GetAwaiter(); if (awaiter11.IsCompleted) { TryInvokeContinuationT11(this, in awaiter11); return; } awaiter11.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T11>.Awaiter> stateTuple = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, UniTask<T11>.Awaiter>)state; TryInvokeContinuationT11(stateTuple.Item1, in stateTuple.Item2); }, StateTuple.Create(this, awaiter11)); } private static void TryInvokeContinuationT1(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> self, in UniTask<T1>.Awaiter awaiter) { try { self.t1 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 11) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); } } private static void TryInvokeContinuationT2(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> self, in UniTask<T2>.Awaiter awaiter) { try { self.t2 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 11) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); } } private static void TryInvokeContinuationT3(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> self, in UniTask<T3>.Awaiter awaiter) { try { self.t3 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 11) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); } } private static void TryInvokeContinuationT4(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> self, in UniTask<T4>.Awaiter awaiter) { try { self.t4 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 11) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); } } private static void TryInvokeContinuationT5(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> self, in UniTask<T5>.Awaiter awaiter) { try { self.t5 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 11) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); } } private static void TryInvokeContinuationT6(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> self, in UniTask<T6>.Awaiter awaiter) { try { self.t6 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 11) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); } } private static void TryInvokeContinuationT7(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> self, in UniTask<T7>.Awaiter awaiter) { try { self.t7 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 11) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); } } private static void TryInvokeContinuationT8(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> self, in UniTask<T8>.Awaiter awaiter) { try { self.t8 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 11) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); } } private static void TryInvokeContinuationT9(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> self, in UniTask<T9>.Awaiter awaiter) { try { self.t9 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 11) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); } } private static void TryInvokeContinuationT10(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> self, in UniTask<T10>.Awaiter awaiter) { try { self.t10 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 11) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); } } private static void TryInvokeContinuationT11(WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> self, in UniTask<T11>.Awaiter awaiter) { try { self.t11 = awaiter.GetResult(); } catch (Exception error) { self.core.TrySetException(error); return; } if (Interlocked.Increment(ref self.completedCount) == 11) { self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); } } public (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) GetResult(short token) { GC.SuppressFinalize(this); return core.GetResult(token); } void IUniTaskSource.GetResult(short token) { GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } } private sealed class WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> : IUniTaskSource<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12)>, IUniTaskSource { private T1 t1; private T2 t2; private T3 t3; private T4 t4; private T5 t5; private T6 t6; private T7 t7; private T8 t8; private T9 t9; private T10 t10; private T11 t11; private T12 t12; private int completedCount; private UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12)> core; public WhenAllPromise(UniTask<T1> task1, UniTask<T2> task2, UniTask<T3> task3, UniTask<T4> task4, UniTask<T5> task5, UniTask<T6> task6, UniTask<T7> task7, UniTask<T8> task8, UniTask<T9> task9, UniTask<T10> task10, UniTask<T11> task11, UniTask<T12> task12) { completedCount = 0; UniTask<T1>.Awaiter awaiter = task1.GetAwaiter(); if (awaiter.IsCompleted) { TryInvokeContinuationT1(this, in awaiter); } else { awaiter.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T1>.Awaiter> stateTuple12 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T1>.Awaiter>)state; TryInvokeContinuationT1(stateTuple12.Item1, in stateTuple12.Item2); }, StateTuple.Create(this, awaiter)); } UniTask<T2>.Awaiter awaiter2 = task2.GetAwaiter(); if (awaiter2.IsCompleted) { TryInvokeContinuationT2(this, in awaiter2); } else { awaiter2.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T2>.Awaiter> stateTuple11 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T2>.Awaiter>)state; TryInvokeContinuationT2(stateTuple11.Item1, in stateTuple11.Item2); }, StateTuple.Create(this, awaiter2)); } UniTask<T3>.Awaiter awaiter3 = task3.GetAwaiter(); if (awaiter3.IsCompleted) { TryInvokeContinuationT3(this, in awaiter3); } else { awaiter3.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T3>.Awaiter> stateTuple10 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T3>.Awaiter>)state; TryInvokeContinuationT3(stateTuple10.Item1, in stateTuple10.Item2); }, StateTuple.Create(this, awaiter3)); } UniTask<T4>.Awaiter awaiter4 = task4.GetAwaiter(); if (awaiter4.IsCompleted) { TryInvokeContinuationT4(this, in awaiter4); } else { awaiter4.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T4>.Awaiter> stateTuple9 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T4>.Awaiter>)state; TryInvokeContinuationT4(stateTuple9.Item1, in stateTuple9.Item2); }, StateTuple.Create(this, awaiter4)); } UniTask<T5>.Awaiter awaiter5 = task5.GetAwaiter(); if (awaiter5.IsCompleted) { TryInvokeContinuationT5(this, in awaiter5); } else { awaiter5.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T5>.Awaiter> stateTuple8 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T5>.Awaiter>)state; TryInvokeContinuationT5(stateTuple8.Item1, in stateTuple8.Item2); }, StateTuple.Create(this, awaiter5)); } UniTask<T6>.Awaiter awaiter6 = task6.GetAwaiter(); if (awaiter6.IsCompleted) { TryInvokeContinuationT6(this, in awaiter6); } else { awaiter6.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T6>.Awaiter> stateTuple7 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T6>.Awaiter>)state; TryInvokeContinuationT6(stateTuple7.Item1, in stateTuple7.Item2); }, StateTuple.Create(this, awaiter6)); } UniTask<T7>.Awaiter awaiter7 = task7.GetAwaiter(); if (awaiter7.IsCompleted) { TryInvokeContinuationT7(this, in awaiter7); } else { awaiter7.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T7>.Awaiter> stateTuple6 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T7>.Awaiter>)state; TryInvokeContinuationT7(stateTuple6.Item1, in stateTuple6.Item2); }, StateTuple.Create(this, awaiter7)); } UniTask<T8>.Awaiter awaiter8 = task8.GetAwaiter(); if (awaiter8.IsCompleted) { TryInvokeContinuationT8(this, in awaiter8); } else { awaiter8.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T8>.Awaiter> stateTuple5 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T8>.Awaiter>)state; TryInvokeContinuationT8(stateTuple5.Item1, in stateTuple5.Item2); }, StateTuple.Create(this, awaiter8)); } UniTask<T9>.Awaiter awaiter9 = task9.GetAwaiter(); if (awaiter9.IsCompleted) { TryInvokeContinuationT9(this, in awaiter9); } else { awaiter9.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T9>.Awaiter> stateTuple4 = (StateTuple<WhenAllPromise<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, UniTask<T9>.Awaiter>)state; TryInvokeContinuationT9(stateTuple4.Item1, in stateTuple4.Item2); }, StateTuple.Create(this, awaiter9)); } UniTask<T10>.Awaiter awaiter10 = task10.GetAwaiter(); if (awaiter10.IsCompleted) { TryInvokeContinuationT10(this, in awaiter10); } else { awaiter10.SourceOnCompleted(delegate(object state) { using StateTuple<WhenAllPromise<T1, T2, T3, T4,
websocket-sharp.dll
Decompiled 11 hours 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.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Security.Principal; using System.Text; using System.Threading; using System.Timers; using WebSocketSharp.Net; using WebSocketSharp.Net.WebSockets; [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("sta")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("sta.blockhead")] [assembly: AssemblyDescription("websocket-sharp provides the WebSocket protocol client and server.\r\n\r\nIt supports:\r\n- RFC 6455\r\n- WebSocket Client and Server\r\n- Per-message Compression extension\r\n- Secure Connection\r\n- HTTP Authentication (Basic/Digest)\r\n- Query String, Origin header and Cookies\r\n- Connecting through the HTTP Proxy server\r\n- .NET 3.5 or later (includes compatible)")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyInformationalVersion("1.0.1")] [assembly: AssemblyProduct("websocket-sharp")] [assembly: AssemblyTitle("websocket-sharp")] [assembly: AssemblyVersion("1.0.1.0")] namespace WebSocketSharp { public enum ByteOrder { Little, Big } public class CloseEventArgs : EventArgs { private bool _clean; private PayloadData _payloadData; internal PayloadData PayloadData => _payloadData; public ushort Code => _payloadData.Code; public string Reason => _payloadData.Reason ?? string.Empty; public bool WasClean { get { return _clean; } internal set { _clean = value; } } internal CloseEventArgs() { _payloadData = PayloadData.Empty; } internal CloseEventArgs(ushort code) : this(code, null) { } internal CloseEventArgs(CloseStatusCode code) : this((ushort)code, null) { } internal CloseEventArgs(PayloadData payloadData) { _payloadData = payloadData; } internal CloseEventArgs(ushort code, string reason) { _payloadData = new PayloadData(code, reason); } internal CloseEventArgs(CloseStatusCode code, string reason) : this((ushort)code, reason) { } } public enum CloseStatusCode : ushort { Normal = 1000, Away = 1001, ProtocolError = 1002, UnsupportedData = 1003, Undefined = 1004, NoStatus = 1005, Abnormal = 1006, InvalidData = 1007, PolicyViolation = 1008, TooBig = 1009, MandatoryExtension = 1010, ServerError = 1011, TlsHandshakeFailure = 1015 } public enum CompressionMethod : byte { None, Deflate } public class ErrorEventArgs : EventArgs { private Exception _exception; private string _message; public Exception Exception => _exception; public string Message => _message; internal ErrorEventArgs(string message) : this(message, null) { } internal ErrorEventArgs(string message, Exception exception) { _message = message; _exception = exception; } } public static class Ext { private static readonly byte[] _last = new byte[1]; private static readonly int _retry = 5; private const string _tspecials = "()<>@,;:\\\"/[]?={} \t"; private static byte[] compress(this byte[] data) { if (data.LongLength == 0L) { return data; } using MemoryStream stream = new MemoryStream(data); return stream.compressToArray(); } private static MemoryStream compress(this Stream stream) { MemoryStream memoryStream = new MemoryStream(); if (stream.Length == 0L) { return memoryStream; } stream.Position = 0L; using DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress, leaveOpen: true); stream.CopyTo(deflateStream, 1024); deflateStream.Close(); memoryStream.Write(_last, 0, 1); memoryStream.Position = 0L; return memoryStream; } private static byte[] compressToArray(this Stream stream) { using MemoryStream memoryStream = stream.compress(); memoryStream.Close(); return memoryStream.ToArray(); } private static byte[] decompress(this byte[] data) { if (data.LongLength == 0L) { return data; } using MemoryStream stream = new MemoryStream(data); return stream.decompressToArray(); } private static MemoryStream decompress(this Stream stream) { MemoryStream memoryStream = new MemoryStream(); if (stream.Length == 0L) { return memoryStream; } stream.Position = 0L; using DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress, leaveOpen: true); deflateStream.CopyTo(memoryStream, 1024); memoryStream.Position = 0L; return memoryStream; } private static byte[] decompressToArray(this Stream stream) { using MemoryStream memoryStream = stream.decompress(); memoryStream.Close(); return memoryStream.ToArray(); } private static void times(this ulong n, Action action) { for (ulong num = 0uL; num < n; num++) { action(); } } internal static byte[] Append(this ushort code, string reason) { byte[] array = code.InternalToByteArray(ByteOrder.Big); if (reason != null && reason.Length > 0) { List<byte> list = new List<byte>(array); list.AddRange(Encoding.UTF8.GetBytes(reason)); array = list.ToArray(); } return array; } internal static void Close(this WebSocketSharp.Net.HttpListenerResponse response, WebSocketSharp.Net.HttpStatusCode code) { response.StatusCode = (int)code; response.OutputStream.Close(); } internal static void CloseWithAuthChallenge(this WebSocketSharp.Net.HttpListenerResponse response, string challenge) { response.Headers.InternalSet("WWW-Authenticate", challenge, response: true); response.Close(WebSocketSharp.Net.HttpStatusCode.Unauthorized); } internal static byte[] Compress(this byte[] data, CompressionMethod method) { if (method != CompressionMethod.Deflate) { return data; } return data.compress(); } internal static Stream Compress(this Stream stream, CompressionMethod method) { if (method != CompressionMethod.Deflate) { return stream; } return stream.compress(); } internal static byte[] CompressToArray(this Stream stream, CompressionMethod method) { if (method != CompressionMethod.Deflate) { return stream.ToByteArray(); } return stream.compressToArray(); } internal static bool Contains<T>(this IEnumerable<T> source, Func<T, bool> condition) { foreach (T item in source) { if (condition(item)) { return true; } } return false; } internal static bool ContainsTwice(this string[] values) { int len = values.Length; int end = len - 1; Func<int, bool> seek = null; seek = delegate(int idx) { if (idx == end) { return false; } string text = values[idx]; for (int i = idx + 1; i < len; i++) { if (values[i] == text) { return true; } } return seek(++idx); }; return seek(0); } internal static T[] Copy<T>(this T[] source, int length) { T[] array = new T[length]; Array.Copy(source, 0, array, 0, length); return array; } internal static T[] Copy<T>(this T[] source, long length) { T[] array = new T[length]; Array.Copy(source, 0L, array, 0L, length); return array; } internal static void CopyTo(this Stream source, Stream destination, int bufferLength) { byte[] buffer = new byte[bufferLength]; int num = 0; while ((num = source.Read(buffer, 0, bufferLength)) > 0) { destination.Write(buffer, 0, num); } } internal static void CopyToAsync(this Stream source, Stream destination, int bufferLength, Action completed, Action<Exception> error) { byte[] buff = new byte[bufferLength]; AsyncCallback callback = null; callback = delegate(IAsyncResult ar) { try { int num = source.EndRead(ar); if (num <= 0) { if (completed != null) { completed(); } } else { destination.Write(buff, 0, num); source.BeginRead(buff, 0, bufferLength, callback, null); } } catch (Exception obj2) { if (error != null) { error(obj2); } } }; try { source.BeginRead(buff, 0, bufferLength, callback, null); } catch (Exception obj) { if (error != null) { error(obj); } } } internal static byte[] Decompress(this byte[] data, CompressionMethod method) { if (method != CompressionMethod.Deflate) { return data; } return data.decompress(); } internal static Stream Decompress(this Stream stream, CompressionMethod method) { if (method != CompressionMethod.Deflate) { return stream; } return stream.decompress(); } internal static byte[] DecompressToArray(this Stream stream, CompressionMethod method) { if (method != CompressionMethod.Deflate) { return stream.ToByteArray(); } return stream.decompressToArray(); } internal static bool EqualsWith(this int value, char c, Action<int> action) { action(value); return value == c; } internal static string GetAbsolutePath(this Uri uri) { if (uri.IsAbsoluteUri) { return uri.AbsolutePath; } string originalString = uri.OriginalString; if (originalString[0] != '/') { return null; } int num = originalString.IndexOfAny(new char[2] { '?', '#' }); if (num <= 0) { return originalString; } return originalString.Substring(0, num); } internal static string GetDnsSafeHost(this Uri uri, bool bracketIPv6) { if (!bracketIPv6 || uri.HostNameType != UriHostNameType.IPv6) { return uri.DnsSafeHost; } return uri.Host; } internal static string GetMessage(this CloseStatusCode code) { return code switch { CloseStatusCode.TlsHandshakeFailure => "An error has occurred during a TLS handshake.", CloseStatusCode.ServerError => "WebSocket server got an internal error.", CloseStatusCode.MandatoryExtension => "WebSocket client didn't receive expected extension(s).", CloseStatusCode.TooBig => "A too big message has been received.", CloseStatusCode.PolicyViolation => "A policy violation has occurred.", CloseStatusCode.InvalidData => "Invalid data has been received.", CloseStatusCode.Abnormal => "An exception has occurred.", CloseStatusCode.UnsupportedData => "Unsupported data has been received.", CloseStatusCode.ProtocolError => "A WebSocket protocol error has occurred.", _ => string.Empty, }; } internal static string GetName(this string nameAndValue, char separator) { int num = nameAndValue.IndexOf(separator); if (num <= 0) { return null; } return nameAndValue.Substring(0, num).Trim(); } internal static string GetValue(this string nameAndValue, char separator) { int num = nameAndValue.IndexOf(separator); if (num <= -1 || num >= nameAndValue.Length - 1) { return null; } return nameAndValue.Substring(num + 1).Trim(); } internal static string GetValue(this string nameAndValue, char separator, bool unquote) { int num = nameAndValue.IndexOf(separator); if (num < 0 || num == nameAndValue.Length - 1) { return null; } string text = nameAndValue.Substring(num + 1).Trim(); if (!unquote) { return text; } return text.Unquote(); } internal static byte[] InternalToByteArray(this ushort value, ByteOrder order) { byte[] bytes = BitConverter.GetBytes(value); if (!order.IsHostOrder()) { Array.Reverse((Array)bytes); } return bytes; } internal static byte[] InternalToByteArray(this ulong value, ByteOrder order) { byte[] bytes = BitConverter.GetBytes(value); if (!order.IsHostOrder()) { Array.Reverse((Array)bytes); } return bytes; } internal static bool IsCompressionExtension(this string value, CompressionMethod method) { return value.StartsWith(method.ToExtensionString()); } internal static bool IsControl(this byte opcode) { if (opcode > 7) { return opcode < 16; } return false; } internal static bool IsControl(this Opcode opcode) { return (int)opcode >= 8; } internal static bool IsData(this byte opcode) { if (opcode != 1) { return opcode == 2; } return true; } internal static bool IsData(this Opcode opcode) { if (opcode != Opcode.Text) { return opcode == Opcode.Binary; } return true; } internal static bool IsPortNumber(this int value) { if (value > 0) { return value < 65536; } return false; } internal static bool IsReserved(this ushort code) { if (code != 1004 && code != 1005 && code != 1006) { return code == 1015; } return true; } internal static bool IsReserved(this CloseStatusCode code) { if (code != CloseStatusCode.Undefined && code != CloseStatusCode.NoStatus && code != CloseStatusCode.Abnormal) { return code == CloseStatusCode.TlsHandshakeFailure; } return true; } internal static bool IsSupported(this byte opcode) { return Enum.IsDefined(typeof(Opcode), opcode); } internal static bool IsText(this string value) { int length = value.Length; for (int i = 0; i < length; i++) { char c = value[i]; if (c < ' ') { if (!Contains("\r\n\t", c)) { return false; } if (c == '\n') { i++; if (i == length) { break; } c = value[i]; if (!Contains(" \t", c)) { return false; } } } else if (c == '\u007f') { return false; } } return true; } internal static bool IsToken(this string value) { foreach (char c in value) { if (c < ' ') { return false; } if (c >= '\u007f') { return false; } if (Contains("()<>@,;:\\\"/[]?={} \t", c)) { return false; } } return true; } internal static string Quote(this string value) { return string.Format("\"{0}\"", value.Replace("\"", "\\\"")); } internal static byte[] ReadBytes(this Stream stream, int length) { byte[] array = new byte[length]; int num = 0; try { int num2 = 0; while (length > 0) { num2 = stream.Read(array, num, length); if (num2 != 0) { num += num2; length -= num2; continue; } break; } } catch { } return array.SubArray(0, num); } internal static byte[] ReadBytes(this Stream stream, long length, int bufferLength) { using MemoryStream memoryStream = new MemoryStream(); try { byte[] buffer = new byte[bufferLength]; int num = 0; while (length > 0) { if (length < bufferLength) { bufferLength = (int)length; } num = stream.Read(buffer, 0, bufferLength); if (num != 0) { memoryStream.Write(buffer, 0, num); length -= num; continue; } break; } } catch { } memoryStream.Close(); return memoryStream.ToArray(); } internal static void ReadBytesAsync(this Stream stream, int length, Action<byte[]> completed, Action<Exception> error) { byte[] buff = new byte[length]; int offset = 0; int retry = 0; AsyncCallback callback = null; callback = delegate(IAsyncResult ar) { try { int num = stream.EndRead(ar); if (num == 0 && retry < _retry) { retry++; stream.BeginRead(buff, offset, length, callback, null); } else if (num == 0 || num == length) { if (completed != null) { completed(buff.SubArray(0, offset + num)); } } else { retry = 0; offset += num; length -= num; stream.BeginRead(buff, offset, length, callback, null); } } catch (Exception obj2) { if (error != null) { error(obj2); } } }; try { stream.BeginRead(buff, offset, length, callback, null); } catch (Exception obj) { if (error != null) { error(obj); } } } internal static void ReadBytesAsync(this Stream stream, long length, int bufferLength, Action<byte[]> completed, Action<Exception> error) { MemoryStream dest = new MemoryStream(); byte[] buff = new byte[bufferLength]; int retry = 0; Action<long> read = null; read = delegate(long len) { if (len < bufferLength) { bufferLength = (int)len; } stream.BeginRead(buff, 0, bufferLength, delegate(IAsyncResult ar) { try { int num = stream.EndRead(ar); if (num > 0) { dest.Write(buff, 0, num); } if (num == 0 && retry < _retry) { int num2 = retry; retry = num2 + 1; read(len); } else if (num == 0 || num == len) { if (completed != null) { dest.Close(); completed(dest.ToArray()); } dest.Dispose(); } else { retry = 0; read(len - num); } } catch (Exception obj2) { dest.Dispose(); if (error != null) { error(obj2); } } }, null); }; try { read(length); } catch (Exception obj) { dest.Dispose(); if (error != null) { error(obj); } } } internal static string RemovePrefix(this string value, params string[] prefixes) { int num = 0; foreach (string text in prefixes) { if (value.StartsWith(text)) { num = text.Length; break; } } if (num <= 0) { return value; } return value.Substring(num); } internal static T[] Reverse<T>(this T[] array) { int num = array.Length; T[] array2 = new T[num]; int num2 = num - 1; for (int i = 0; i <= num2; i++) { array2[i] = array[num2 - i]; } return array2; } internal static IEnumerable<string> SplitHeaderValue(this string value, params char[] separators) { int len = value.Length; string seps = new string(separators); StringBuilder buff = new StringBuilder(32); bool escaped = false; bool quoted = false; for (int i = 0; i < len; i++) { char c = value[i]; switch (c) { case '"': if (escaped) { escaped = !escaped; } else { quoted = !quoted; } break; case '\\': if (i < len - 1 && value[i + 1] == '"') { escaped = true; } break; default: if (Contains(seps, c) && !quoted) { yield return buff.ToString(); buff.Length = 0; continue; } break; } buff.Append(c); } if (buff.Length > 0) { yield return buff.ToString(); } } internal static byte[] ToByteArray(this Stream stream) { using MemoryStream memoryStream = new MemoryStream(); stream.Position = 0L; stream.CopyTo(memoryStream, 1024); memoryStream.Close(); return memoryStream.ToArray(); } internal static CompressionMethod ToCompressionMethod(this string value) { foreach (CompressionMethod value2 in Enum.GetValues(typeof(CompressionMethod))) { if (value2.ToExtensionString() == value) { return value2; } } return CompressionMethod.None; } internal static string ToExtensionString(this CompressionMethod method, params string[] parameters) { if (method == CompressionMethod.None) { return string.Empty; } string text = $"permessage-{method.ToString().ToLower()}"; if (parameters == null || parameters.Length == 0) { return text; } return string.Format("{0}; {1}", text, parameters.ToString("; ")); } internal static IPAddress ToIPAddress(this string value) { if (value == null || value.Length == 0) { return null; } if (IPAddress.TryParse(value, out IPAddress address)) { return address; } try { return Dns.GetHostAddresses(value)[0]; } catch { return null; } } internal static List<TSource> ToList<TSource>(this IEnumerable<TSource> source) { return new List<TSource>(source); } internal static string ToString(this IPAddress address, bool bracketIPv6) { if (!bracketIPv6 || address.AddressFamily != AddressFamily.InterNetworkV6) { return address.ToString(); } return $"[{address.ToString()}]"; } internal static ushort ToUInt16(this byte[] source, ByteOrder sourceOrder) { return BitConverter.ToUInt16(source.ToHostOrder(sourceOrder), 0); } internal static ulong ToUInt64(this byte[] source, ByteOrder sourceOrder) { return BitConverter.ToUInt64(source.ToHostOrder(sourceOrder), 0); } internal static string TrimSlashFromEnd(this string value) { string text = value.TrimEnd(new char[1] { '/' }); if (text.Length <= 0) { return "/"; } return text; } internal static string TrimSlashOrBackslashFromEnd(this string value) { string text = value.TrimEnd('/', '\\'); if (text.Length <= 0) { return value[0].ToString(); } return text; } internal static bool TryCreateWebSocketUri(this string uriString, out Uri result, out string message) { result = null; message = null; Uri uri = uriString.ToUri(); if (uri == null) { message = "An invalid URI string."; return false; } if (!uri.IsAbsoluteUri) { message = "A relative URI."; return false; } string scheme = uri.Scheme; if (!(scheme == "ws") && !(scheme == "wss")) { message = "The scheme part is not 'ws' or 'wss'."; return false; } int port = uri.Port; if (port == 0) { message = "The port part is zero."; return false; } if (uri.Fragment.Length > 0) { message = "It includes the fragment component."; return false; } result = ((port != -1) ? uri : new Uri(string.Format("{0}://{1}:{2}{3}", scheme, uri.Host, (scheme == "ws") ? 80 : 443, uri.PathAndQuery))); return true; } internal static bool TryGetUTF8DecodedString(this byte[] bytes, out string s) { s = null; try { s = Encoding.UTF8.GetString(bytes); } catch { return false; } return true; } internal static bool TryGetUTF8EncodedBytes(this string s, out byte[] bytes) { bytes = null; try { bytes = Encoding.UTF8.GetBytes(s); } catch { return false; } return true; } internal static bool TryOpenRead(this FileInfo fileInfo, out FileStream fileStream) { fileStream = null; try { fileStream = fileInfo.OpenRead(); } catch { return false; } return true; } internal static string Unquote(this string value) { int num = value.IndexOf('"'); if (num < 0) { return value; } int num2 = value.LastIndexOf('"') - num - 1; if (num2 >= 0) { if (num2 != 0) { return value.Substring(num + 1, num2).Replace("\\\"", "\""); } return string.Empty; } return value; } internal static string UTF8Decode(this byte[] bytes) { try { return Encoding.UTF8.GetString(bytes); } catch { return null; } } internal static byte[] UTF8Encode(this string s) { return Encoding.UTF8.GetBytes(s); } internal static void WriteBytes(this Stream stream, byte[] bytes, int bufferLength) { using MemoryStream memoryStream = new MemoryStream(bytes); memoryStream.CopyTo(stream, bufferLength); } internal static void WriteBytesAsync(this Stream stream, byte[] bytes, int bufferLength, Action completed, Action<Exception> error) { MemoryStream input = new MemoryStream(bytes); input.CopyToAsync(stream, bufferLength, delegate { if (completed != null) { completed(); } input.Dispose(); }, delegate(Exception ex) { input.Dispose(); if (error != null) { error(ex); } }); } public static bool Contains(this string value, params char[] chars) { if (chars != null && chars.Length != 0) { if (value != null && value.Length != 0) { return value.IndexOfAny(chars) > -1; } return false; } return true; } public static bool Contains(this NameValueCollection collection, string name) { if (collection == null || collection.Count <= 0) { return false; } return collection[name] != null; } public static bool Contains(this NameValueCollection collection, string name, string value) { if (collection == null || collection.Count == 0) { return false; } string text = collection[name]; if (text == null) { return false; } string[] array = text.Split(new char[1] { ',' }); for (int i = 0; i < array.Length; i++) { if (array[i].Trim().Equals(value, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } public static void Emit(this EventHandler eventHandler, object sender, EventArgs e) { eventHandler?.Invoke(sender, e); } public static void Emit<TEventArgs>(this EventHandler<TEventArgs> eventHandler, object sender, TEventArgs e) where TEventArgs : EventArgs { eventHandler?.Invoke(sender, e); } public static WebSocketSharp.Net.CookieCollection GetCookies(this NameValueCollection headers, bool response) { string name = (response ? "Set-Cookie" : "Cookie"); if (headers == null || !headers.Contains(name)) { return new WebSocketSharp.Net.CookieCollection(); } return WebSocketSharp.Net.CookieCollection.Parse(headers[name], response); } public static string GetDescription(this WebSocketSharp.Net.HttpStatusCode code) { return ((int)code).GetStatusDescription(); } public static string GetStatusDescription(this int code) { return code switch { 100 => "Continue", 101 => "Switching Protocols", 102 => "Processing", 200 => "OK", 201 => "Created", 202 => "Accepted", 203 => "Non-Authoritative Information", 204 => "No Content", 205 => "Reset Content", 206 => "Partial Content", 207 => "Multi-Status", 300 => "Multiple Choices", 301 => "Moved Permanently", 302 => "Found", 303 => "See Other", 304 => "Not Modified", 305 => "Use Proxy", 307 => "Temporary Redirect", 400 => "Bad Request", 401 => "Unauthorized", 402 => "Payment Required", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 406 => "Not Acceptable", 407 => "Proxy Authentication Required", 408 => "Request Timeout", 409 => "Conflict", 410 => "Gone", 411 => "Length Required", 412 => "Precondition Failed", 413 => "Request Entity Too Large", 414 => "Request-Uri Too Long", 415 => "Unsupported Media Type", 416 => "Requested Range Not Satisfiable", 417 => "Expectation Failed", 422 => "Unprocessable Entity", 423 => "Locked", 424 => "Failed Dependency", 500 => "Internal Server Error", 501 => "Not Implemented", 502 => "Bad Gateway", 503 => "Service Unavailable", 504 => "Gateway Timeout", 505 => "Http Version Not Supported", 507 => "Insufficient Storage", _ => string.Empty, }; } public static bool IsCloseStatusCode(this ushort value) { if (value > 999) { return value < 5000; } return false; } public static bool IsEnclosedIn(this string value, char c) { if (value != null && value.Length > 1 && value[0] == c) { return value[value.Length - 1] == c; } return false; } public static bool IsHostOrder(this ByteOrder order) { return BitConverter.IsLittleEndian == (order == ByteOrder.Little); } public static bool IsLocal(this IPAddress address) { if (address == null) { return false; } if (address.Equals(IPAddress.Any)) { return true; } if (address.Equals(IPAddress.Loopback)) { return true; } if (Socket.OSSupportsIPv6) { if (address.Equals(IPAddress.IPv6Any)) { return true; } if (address.Equals(IPAddress.IPv6Loopback)) { return true; } } IPAddress[] hostAddresses = Dns.GetHostAddresses(Dns.GetHostName()); foreach (IPAddress obj in hostAddresses) { if (address.Equals(obj)) { return true; } } return false; } public static bool IsNullOrEmpty(this string value) { if (value != null) { return value.Length == 0; } return true; } public static bool IsPredefinedScheme(this string value) { if (value == null || value.Length < 2) { return false; } switch (value[0]) { case 'h': if (!(value == "http")) { return value == "https"; } return true; case 'w': if (!(value == "ws")) { return value == "wss"; } return true; case 'f': if (!(value == "file")) { return value == "ftp"; } return true; case 'g': return value == "gopher"; case 'm': return value == "mailto"; case 'n': { char c = value[1]; if (c != 'e') { return value == "nntp"; } if (!(value == "news") && !(value == "net.pipe")) { return value == "net.tcp"; } return true; } default: return false; } } public static bool IsUpgradeTo(this WebSocketSharp.Net.HttpListenerRequest request, string protocol) { if (request == null) { throw new ArgumentNullException("request"); } if (protocol == null) { throw new ArgumentNullException("protocol"); } if (protocol.Length == 0) { throw new ArgumentException("An empty string.", "protocol"); } if (request.Headers.Contains("Upgrade", protocol)) { return request.Headers.Contains("Connection", "Upgrade"); } return false; } public static bool MaybeUri(this string value) { if (value == null || value.Length == 0) { return false; } int num = value.IndexOf(':'); if (num == -1) { return false; } if (num >= 10) { return false; } return value.Substring(0, num).IsPredefinedScheme(); } public static T[] SubArray<T>(this T[] array, int startIndex, int length) { int num; if (array == null || (num = array.Length) == 0) { return new T[0]; } if (startIndex < 0 || length <= 0 || startIndex + length > num) { return new T[0]; } if (startIndex == 0 && length == num) { return array; } T[] array2 = new T[length]; Array.Copy(array, startIndex, array2, 0, length); return array2; } public static T[] SubArray<T>(this T[] array, long startIndex, long length) { long num; if (array == null || (num = array.LongLength) == 0L) { return new T[0]; } if (startIndex < 0 || length <= 0 || startIndex + length > num) { return new T[0]; } if (startIndex == 0L && length == num) { return array; } T[] array2 = new T[length]; Array.Copy(array, startIndex, array2, 0L, length); return array2; } public static void Times(this int n, Action action) { if (n > 0 && action != null) { ((ulong)n).times(action); } } public static void Times(this long n, Action action) { if (n > 0 && action != null) { ((ulong)n).times(action); } } public static void Times(this uint n, Action action) { if (n != 0 && action != null) { times(n, action); } } public static void Times(this ulong n, Action action) { if (n != 0 && action != null) { n.times(action); } } public static void Times(this int n, Action<int> action) { if (n > 0 && action != null) { for (int i = 0; i < n; i++) { action(i); } } } public static void Times(this long n, Action<long> action) { if (n > 0 && action != null) { for (long num = 0L; num < n; num++) { action(num); } } } public static void Times(this uint n, Action<uint> action) { if (n != 0 && action != null) { for (uint num = 0u; num < n; num++) { action(num); } } } public static void Times(this ulong n, Action<ulong> action) { if (n != 0 && action != null) { for (ulong num = 0uL; num < n; num++) { action(num); } } } public static T To<T>(this byte[] source, ByteOrder sourceOrder) where T : struct { if (source == null) { throw new ArgumentNullException("source"); } if (source.Length == 0) { return default(T); } Type typeFromHandle = typeof(T); byte[] value = source.ToHostOrder(sourceOrder); if (!(typeFromHandle == typeof(bool))) { if (!(typeFromHandle == typeof(char))) { if (!(typeFromHandle == typeof(double))) { if (!(typeFromHandle == typeof(short))) { if (!(typeFromHandle == typeof(int))) { if (!(typeFromHandle == typeof(long))) { if (!(typeFromHandle == typeof(float))) { if (!(typeFromHandle == typeof(ushort))) { if (!(typeFromHandle == typeof(uint))) { if (!(typeFromHandle == typeof(ulong))) { return default(T); } return (T)(object)BitConverter.ToUInt64(value, 0); } return (T)(object)BitConverter.ToUInt32(value, 0); } return (T)(object)BitConverter.ToUInt16(value, 0); } return (T)(object)BitConverter.ToSingle(value, 0); } return (T)(object)BitConverter.ToInt64(value, 0); } return (T)(object)BitConverter.ToInt32(value, 0); } return (T)(object)BitConverter.ToInt16(value, 0); } return (T)(object)BitConverter.ToDouble(value, 0); } return (T)(object)BitConverter.ToChar(value, 0); } return (T)(object)BitConverter.ToBoolean(value, 0); } public static byte[] ToByteArray<T>(this T value, ByteOrder order) where T : struct { Type typeFromHandle = typeof(T); byte[] array = ((typeFromHandle == typeof(bool)) ? BitConverter.GetBytes((bool)(object)value) : ((!(typeFromHandle == typeof(byte))) ? ((typeFromHandle == typeof(char)) ? BitConverter.GetBytes((char)(object)value) : ((typeFromHandle == typeof(double)) ? BitConverter.GetBytes((double)(object)value) : ((typeFromHandle == typeof(short)) ? BitConverter.GetBytes((short)(object)value) : ((typeFromHandle == typeof(int)) ? BitConverter.GetBytes((int)(object)value) : ((typeFromHandle == typeof(long)) ? BitConverter.GetBytes((long)(object)value) : ((typeFromHandle == typeof(float)) ? BitConverter.GetBytes((float)(object)value) : ((typeFromHandle == typeof(ushort)) ? BitConverter.GetBytes((ushort)(object)value) : ((typeFromHandle == typeof(uint)) ? BitConverter.GetBytes((uint)(object)value) : ((typeFromHandle == typeof(ulong)) ? BitConverter.GetBytes((ulong)(object)value) : WebSocket.EmptyBytes))))))))) : new byte[1] { (byte)(object)value })); if (array.Length > 1 && !order.IsHostOrder()) { Array.Reverse((Array)array); } return array; } public static byte[] ToHostOrder(this byte[] source, ByteOrder sourceOrder) { if (source == null) { throw new ArgumentNullException("source"); } if (source.Length <= 1 || sourceOrder.IsHostOrder()) { return source; } return source.Reverse(); } public static string ToString<T>(this T[] array, string separator) { if (array == null) { throw new ArgumentNullException("array"); } int num = array.Length; if (num == 0) { return string.Empty; } if (separator == null) { separator = string.Empty; } StringBuilder buff = new StringBuilder(64); (num - 1).Times(delegate(int i) { buff.AppendFormat("{0}{1}", array[i].ToString(), separator); }); buff.Append(array[num - 1].ToString()); return buff.ToString(); } public static Uri ToUri(this string value) { Uri.TryCreate(value, value.MaybeUri() ? UriKind.Absolute : UriKind.Relative, out Uri result); return result; } public static string UrlDecode(this string value) { if (value == null || value.Length <= 0) { return value; } return HttpUtility.UrlDecode(value); } public static string UrlEncode(this string value) { if (value == null || value.Length <= 0) { return value; } return HttpUtility.UrlEncode(value); } public static void WriteContent(this WebSocketSharp.Net.HttpListenerResponse response, byte[] content) { if (response == null) { throw new ArgumentNullException("response"); } if (content == null) { throw new ArgumentNullException("content"); } long num = content.LongLength; if (num == 0L) { response.Close(); return; } response.ContentLength64 = num; Stream outputStream = response.OutputStream; if (num <= int.MaxValue) { outputStream.Write(content, 0, (int)num); } else { outputStream.WriteBytes(content, 1024); } outputStream.Close(); } } internal enum Fin : byte { More, Final } internal abstract class HttpBase { private NameValueCollection _headers; private const int _headersMaxLength = 8192; private Version _version; internal byte[] EntityBodyData; protected const string CrLf = "\r\n"; public string EntityBody { get { if (EntityBodyData == null || EntityBodyData.LongLength == 0L) { return string.Empty; } Encoding encoding = null; string text = _headers["Content-Type"]; if (text != null && text.Length > 0) { encoding = HttpUtility.GetEncoding(text); } return (encoding ?? Encoding.UTF8).GetString(EntityBodyData); } } public NameValueCollection Headers => _headers; public Version ProtocolVersion => _version; protected HttpBase(Version version, NameValueCollection headers) { _version = version; _headers = headers; } private static byte[] readEntityBody(Stream stream, string length) { if (!long.TryParse(length, out var result)) { throw new ArgumentException("Cannot be parsed.", "length"); } if (result < 0) { throw new ArgumentOutOfRangeException("length", "Less than zero."); } if (result <= 1024) { if (result <= 0) { return null; } return stream.ReadBytes((int)result); } return stream.ReadBytes(result, 1024); } private static string[] readHeaders(Stream stream, int maxLength) { List<byte> buff = new List<byte>(); int cnt = 0; Action<int> action = delegate(int i) { if (i == -1) { throw new EndOfStreamException("The header cannot be read from the data source."); } buff.Add((byte)i); cnt++; }; bool flag = false; while (cnt < maxLength) { if (stream.ReadByte().EqualsWith('\r', action) && stream.ReadByte().EqualsWith('\n', action) && stream.ReadByte().EqualsWith('\r', action) && stream.ReadByte().EqualsWith('\n', action)) { flag = true; break; } } if (!flag) { throw new WebSocketException("The length of header part is greater than the max length."); } return Encoding.UTF8.GetString(buff.ToArray()).Replace("\r\n ", " ").Replace("\r\n\t", " ") .Split(new string[1] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); } protected static T Read<T>(Stream stream, Func<string[], T> parser, int millisecondsTimeout) where T : HttpBase { bool timeout = false; System.Threading.Timer timer = new System.Threading.Timer(delegate { timeout = true; stream.Close(); }, null, millisecondsTimeout, -1); T val = null; Exception ex = null; try { val = parser(readHeaders(stream, 8192)); string text = val.Headers["Content-Length"]; if (text != null && text.Length > 0) { val.EntityBodyData = readEntityBody(stream, text); } } catch (Exception ex2) { ex = ex2; } finally { timer.Change(-1, -1); timer.Dispose(); } string text2 = (timeout ? "A timeout has occurred while reading an HTTP request/response." : ((ex != null) ? "An exception has occurred while reading an HTTP request/response." : null)); if (text2 != null) { throw new WebSocketException(text2, ex); } return val; } public byte[] ToByteArray() { return Encoding.UTF8.GetBytes(ToString()); } } internal class HttpRequest : HttpBase { private string _method; private string _uri; private bool _websocketRequest; private bool _websocketRequestSet; public AuthenticationResponse AuthenticationResponse { get { string text = base.Headers["Authorization"]; if (text == null || text.Length <= 0) { return null; } return AuthenticationResponse.Parse(text); } } public WebSocketSharp.Net.CookieCollection Cookies => base.Headers.GetCookies(response: false); public string HttpMethod => _method; public bool IsWebSocketRequest { get { if (!_websocketRequestSet) { NameValueCollection headers = base.Headers; _websocketRequest = _method == "GET" && base.ProtocolVersion > WebSocketSharp.Net.HttpVersion.Version10 && headers.Contains("Upgrade", "websocket") && headers.Contains("Connection", "Upgrade"); _websocketRequestSet = true; } return _websocketRequest; } } public string RequestUri => _uri; private HttpRequest(string method, string uri, Version version, NameValueCollection headers) : base(version, headers) { _method = method; _uri = uri; } internal HttpRequest(string method, string uri) : this(method, uri, WebSocketSharp.Net.HttpVersion.Version11, new NameValueCollection()) { base.Headers["User-Agent"] = "websocket-sharp/1.0"; } internal static HttpRequest CreateConnectRequest(Uri uri) { string dnsSafeHost = uri.DnsSafeHost; int port = uri.Port; string text = $"{dnsSafeHost}:{port}"; HttpRequest httpRequest = new HttpRequest("CONNECT", text); httpRequest.Headers["Host"] = ((port == 80) ? dnsSafeHost : text); return httpRequest; } internal static HttpRequest CreateWebSocketRequest(Uri uri) { HttpRequest httpRequest = new HttpRequest("GET", uri.PathAndQuery); NameValueCollection headers = httpRequest.Headers; int port = uri.Port; string scheme = uri.Scheme; headers["Host"] = (((port == 80 && scheme == "ws") || (port == 443 && scheme == "wss")) ? uri.DnsSafeHost : uri.Authority); headers["Upgrade"] = "websocket"; headers["Connection"] = "Upgrade"; return httpRequest; } internal HttpResponse GetResponse(Stream stream, int millisecondsTimeout) { byte[] array = ToByteArray(); stream.Write(array, 0, array.Length); return HttpBase.Read(stream, HttpResponse.Parse, millisecondsTimeout); } internal static HttpRequest Parse(string[] headerParts) { string[] array = headerParts[0].Split(new char[1] { ' ' }, 3); if (array.Length != 3) { throw new ArgumentException("Invalid request line: " + headerParts[0]); } WebSocketSharp.Net.WebHeaderCollection webHeaderCollection = new WebSocketSharp.Net.WebHeaderCollection(); for (int i = 1; i < headerParts.Length; i++) { webHeaderCollection.InternalSet(headerParts[i], response: false); } return new HttpRequest(array[0], array[1], new Version(array[2].Substring(5)), webHeaderCollection); } internal static HttpRequest Read(Stream stream, int millisecondsTimeout) { return HttpBase.Read(stream, Parse, millisecondsTimeout); } public void SetCookies(WebSocketSharp.Net.CookieCollection cookies) { if (cookies == null || cookies.Count == 0) { return; } StringBuilder stringBuilder = new StringBuilder(64); foreach (WebSocketSharp.Net.Cookie item in cookies.Sorted) { if (!item.Expired) { stringBuilder.AppendFormat("{0}; ", item.ToString()); } } int length = stringBuilder.Length; if (length > 2) { stringBuilder.Length = length - 2; base.Headers["Cookie"] = stringBuilder.ToString(); } } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(64); stringBuilder.AppendFormat("{0} {1} HTTP/{2}{3}", _method, _uri, base.ProtocolVersion, "\r\n"); NameValueCollection headers = base.Headers; string[] allKeys = headers.AllKeys; foreach (string text in allKeys) { stringBuilder.AppendFormat("{0}: {1}{2}", text, headers[text], "\r\n"); } stringBuilder.Append("\r\n"); string entityBody = base.EntityBody; if (entityBody.Length > 0) { stringBuilder.Append(entityBody); } return stringBuilder.ToString(); } } internal class HttpResponse : HttpBase { private string _code; private string _reason; public WebSocketSharp.Net.CookieCollection Cookies => base.Headers.GetCookies(response: true); public bool HasConnectionClose => base.Headers.Contains("Connection", "close"); public bool IsProxyAuthenticationRequired => _code == "407"; public bool IsRedirect { get { if (!(_code == "301")) { return _code == "302"; } return true; } } public bool IsUnauthorized => _code == "401"; public bool IsWebSocketResponse { get { NameValueCollection headers = base.Headers; if (base.ProtocolVersion > WebSocketSharp.Net.HttpVersion.Version10 && _code == "101" && headers.Contains("Upgrade", "websocket")) { return headers.Contains("Connection", "Upgrade"); } return false; } } public string Reason => _reason; public string StatusCode => _code; private HttpResponse(string code, string reason, Version version, NameValueCollection headers) : base(version, headers) { _code = code; _reason = reason; } internal HttpResponse(WebSocketSharp.Net.HttpStatusCode code) : this(code, code.GetDescription()) { } internal HttpResponse(WebSocketSharp.Net.HttpStatusCode code, string reason) : this(((int)code).ToString(), reason, WebSocketSharp.Net.HttpVersion.Version11, new NameValueCollection()) { base.Headers["Server"] = "websocket-sharp/1.0"; } internal static HttpResponse CreateCloseResponse(WebSocketSharp.Net.HttpStatusCode code) { HttpResponse httpResponse = new HttpResponse(code); httpResponse.Headers["Connection"] = "close"; return httpResponse; } internal static HttpResponse CreateUnauthorizedResponse(string challenge) { HttpResponse httpResponse = new HttpResponse(WebSocketSharp.Net.HttpStatusCode.Unauthorized); httpResponse.Headers["WWW-Authenticate"] = challenge; return httpResponse; } internal static HttpResponse CreateWebSocketResponse() { HttpResponse httpResponse = new HttpResponse(WebSocketSharp.Net.HttpStatusCode.SwitchingProtocols); NameValueCollection headers = httpResponse.Headers; headers["Upgrade"] = "websocket"; headers["Connection"] = "Upgrade"; return httpResponse; } internal static HttpResponse Parse(string[] headerParts) { string[] array = headerParts[0].Split(new char[1] { ' ' }, 3); if (array.Length != 3) { throw new ArgumentException("Invalid status line: " + headerParts[0]); } WebSocketSharp.Net.WebHeaderCollection webHeaderCollection = new WebSocketSharp.Net.WebHeaderCollection(); for (int i = 1; i < headerParts.Length; i++) { webHeaderCollection.InternalSet(headerParts[i], response: true); } return new HttpResponse(array[1], array[2], new Version(array[0].Substring(5)), webHeaderCollection); } internal static HttpResponse Read(Stream stream, int millisecondsTimeout) { return HttpBase.Read(stream, Parse, millisecondsTimeout); } public void SetCookies(WebSocketSharp.Net.CookieCollection cookies) { if (cookies == null || cookies.Count == 0) { return; } NameValueCollection headers = base.Headers; foreach (WebSocketSharp.Net.Cookie item in cookies.Sorted) { headers.Add("Set-Cookie", item.ToResponseString()); } } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(64); stringBuilder.AppendFormat("HTTP/{0} {1} {2}{3}", base.ProtocolVersion, _code, _reason, "\r\n"); NameValueCollection headers = base.Headers; string[] allKeys = headers.AllKeys; foreach (string text in allKeys) { stringBuilder.AppendFormat("{0}: {1}{2}", text, headers[text], "\r\n"); } stringBuilder.Append("\r\n"); string entityBody = base.EntityBody; if (entityBody.Length > 0) { stringBuilder.Append(entityBody); } return stringBuilder.ToString(); } } public class LogData { private StackFrame _caller; private DateTime _date; private LogLevel _level; private string _message; public StackFrame Caller => _caller; public DateTime Date => _date; public LogLevel Level => _level; public string Message => _message; internal LogData(LogLevel level, StackFrame caller, string message) { _level = level; _caller = caller; _message = message ?? string.Empty; _date = DateTime.Now; } public override string ToString() { string text = $"{_date}|{_level,-5}|"; MethodBase method = _caller.GetMethod(); Type declaringType = method.DeclaringType; string arg = $"{text}{declaringType.Name}.{method.Name}|"; string[] array = _message.Replace("\r\n", "\n").TrimEnd(new char[1] { '\n' }).Split(new char[1] { '\n' }); if (array.Length <= 1) { return $"{arg}{_message}"; } StringBuilder stringBuilder = new StringBuilder($"{arg}{array[0]}\n", 64); string format = $"{{0,{text.Length}}}{{1}}\n"; for (int i = 1; i < array.Length; i++) { stringBuilder.AppendFormat(format, "", array[i]); } stringBuilder.Length--; return stringBuilder.ToString(); } } public class Logger { private volatile string _file; private volatile LogLevel _level; private Action<LogData, string> _output; private object _sync; public string File { get { return _file; } set { lock (_sync) { _file = value; Warn($"The current path to the log file has been changed to {_file}."); } } } public LogLevel Level { get { return _level; } set { lock (_sync) { _level = value; Warn($"The current logging level has been changed to {_level}."); } } } public Action<LogData, string> Output { get { return _output; } set { lock (_sync) { _output = value ?? new Action<LogData, string>(defaultOutput); Warn("The current output action has been changed."); } } } public Logger() : this(LogLevel.Error, null, null) { } public Logger(LogLevel level) : this(level, null, null) { } public Logger(LogLevel level, string file, Action<LogData, string> output) { _level = level; _file = file; _output = output ?? new Action<LogData, string>(defaultOutput); _sync = new object(); } private static void defaultOutput(LogData data, string path) { string value = data.ToString(); Console.WriteLine(value); if (path != null && path.Length > 0) { writeToFile(value, path); } } private void output(string message, LogLevel level) { lock (_sync) { if (_level > level) { return; } LogData logData = null; try { logData = new LogData(level, new StackFrame(2, needFileInfo: true), message); _output(logData, _file); } catch (Exception ex) { logData = new LogData(LogLevel.Fatal, new StackFrame(0, needFileInfo: true), ex.Message); Console.WriteLine(logData.ToString()); } } } private static void writeToFile(string value, string path) { using StreamWriter writer = new StreamWriter(path, append: true); using TextWriter textWriter = TextWriter.Synchronized(writer); textWriter.WriteLine(value); } public void Debug(string message) { if (_level <= LogLevel.Debug) { output(message, LogLevel.Debug); } } public void Error(string message) { if (_level <= LogLevel.Error) { output(message, LogLevel.Error); } } public void Fatal(string message) { output(message, LogLevel.Fatal); } public void Info(string message) { if (_level <= LogLevel.Info) { output(message, LogLevel.Info); } } public void Trace(string message) { if (_level <= LogLevel.Trace) { output(message, LogLevel.Trace); } } public void Warn(string message) { if (_level <= LogLevel.Warn) { output(message, LogLevel.Warn); } } } public enum LogLevel { Trace, Debug, Info, Warn, Error, Fatal } internal enum Mask : byte { Off, On } public class MessageEventArgs : EventArgs { private string _data; private bool _dataSet; private Opcode _opcode; private byte[] _rawData; internal Opcode Opcode => _opcode; public string Data { get { setData(); return _data; } } public bool IsBinary => _opcode == Opcode.Binary; public bool IsPing => _opcode == Opcode.Ping; public bool IsText => _opcode == Opcode.Text; public byte[] RawData { get { setData(); return _rawData; } } internal MessageEventArgs(WebSocketFrame frame) { _opcode = frame.Opcode; _rawData = frame.PayloadData.ApplicationData; } internal MessageEventArgs(Opcode opcode, byte[] rawData) { if ((ulong)rawData.LongLength > PayloadData.MaxLength) { throw new WebSocketException(CloseStatusCode.TooBig); } _opcode = opcode; _rawData = rawData; } private void setData() { if (!_dataSet) { if (_opcode == Opcode.Binary) { _dataSet = true; return; } _data = _rawData.UTF8Decode(); _dataSet = true; } } } internal enum Opcode : byte { Cont = 0, Text = 1, Binary = 2, Close = 8, Ping = 9, Pong = 10 } internal class PayloadData : IEnumerable<byte>, IEnumerable { private ushort _code; private bool _codeSet; private byte[] _data; private long _extDataLength; private long _length; private string _reason; private bool _reasonSet; public static readonly PayloadData Empty; public static readonly ulong MaxLength; internal ushort Code { get { if (!_codeSet) { _code = (ushort)((_length > 1) ? _data.SubArray(0, 2).ToUInt16(ByteOrder.Big) : 1005); _codeSet = true; } return _code; } } internal long ExtensionDataLength { get { return _extDataLength; } set { _extDataLength = value; } } internal bool HasReservedCode { get { if (_length > 1) { return Code.IsReserved(); } return false; } } internal string Reason { get { if (!_reasonSet) { _reason = ((_length > 2) ? _data.SubArray(2L, _length - 2).UTF8Decode() : string.Empty); _reasonSet = true; } return _reason; } } public byte[] ApplicationData { get { if (_extDataLength <= 0) { return _data; } return _data.SubArray(_extDataLength, _length - _extDataLength); } } public byte[] ExtensionData { get { if (_extDataLength <= 0) { return WebSocket.EmptyBytes; } return _data.SubArray(0L, _extDataLength); } } public ulong Length => (ulong)_length; static PayloadData() { Empty = new PayloadData(); MaxLength = 9223372036854775807uL; } internal PayloadData() { _code = 1005; _reason = string.Empty; _data = WebSocket.EmptyBytes; _codeSet = true; _reasonSet = true; } internal PayloadData(byte[] data) : this(data, data.LongLength) { } internal PayloadData(byte[] data, long length) { _data = data; _length = length; } internal PayloadData(ushort code, string reason) { _code = code; _reason = reason ?? string.Empty; _data = code.Append(reason); _length = _data.LongLength; _codeSet = true; _reasonSet = true; } internal void Mask(byte[] key) { for (long num = 0L; num < _length; num++) { _data[num] ^= key[num % 4]; } } public IEnumerator<byte> GetEnumerator() { byte[] data = _data; for (int i = 0; i < data.Length; i++) { yield return data[i]; } } public byte[] ToArray() { return _data; } public override string ToString() { return BitConverter.ToString(_data); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal enum Rsv : byte { Off, On } public class WebSocket : IDisposable { private AuthenticationChallenge _authChallenge; private string _base64Key; private bool _client; private Action _closeContext; private CompressionMethod _compression; private WebSocketContext _context; private WebSocketSharp.Net.CookieCollection _cookies; private WebSocketSharp.Net.NetworkCredential _credentials; private bool _emitOnPing; private bool _enableRedirection; private string _extensions; private bool _extensionsRequested; private object _forMessageEventQueue; private object _forPing; private object _forSend; private object _forState; private MemoryStream _fragmentsBuffer; private bool _fragmentsCompressed; private Opcode _fragmentsOpcode; private const string _guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private Func<WebSocketContext, string> _handshakeRequestChecker; private bool _ignoreExtensions; private bool _inContinuation; private volatile bool _inMessage; private volatile Logger _logger; private static readonly int _maxRetryCountForConnect; private Action<MessageEventArgs> _message; private Queue<MessageEventArgs> _messageEventQueue; private uint _nonceCount; private string _origin; private ManualResetEvent _pongReceived; private bool _preAuth; private string _protocol; private string[] _protocols; private bool _protocolsRequested; private WebSocketSharp.Net.NetworkCredential _proxyCredentials; private Uri _proxyUri; private volatile WebSocketState _readyState; private ManualResetEvent _receivingExited; private int _retryCountForConnect; private bool _secure; private ClientSslConfiguration _sslConfig; private Stream _stream; private TcpClient _tcpClient; private Uri _uri; private const string _version = "13"; private TimeSpan _waitTime; internal static readonly byte[] EmptyBytes; public static int FragmentLength; internal static readonly RandomNumberGenerator RandomNumber; internal WebSocketSharp.Net.CookieCollection CookieCollection => _cookies; internal Func<WebSocketContext, string> CustomHandshakeRequestChecker { get { return _handshakeRequestChecker; } set { _handshakeRequestChecker = value; } } internal bool HasMessage { get { lock (_forMessageEventQueue) { return _messageEventQueue.Count > 0; } } } internal bool IgnoreExtensions { get { return _ignoreExtensions; } set { _ignoreExtensions = value; } } internal bool IsConnected { get { if (_readyState != WebSocketState.Open) { return _readyState == WebSocketState.Closing; } return true; } } public CompressionMethod Compression { get { return _compression; } set { string text = null; if (!_client) { text = "The set operation cannot be used by servers."; throw new InvalidOperationException(text); } if (!canSet(out text)) { _logger.Warn(text); return; } lock (_forState) { if (!canSet(out text)) { _logger.Warn(text); } else { _compression = value; } } } } public IEnumerable<WebSocketSharp.Net.Cookie> Cookies { get { lock (_cookies.SyncRoot) { foreach (WebSocketSharp.Net.Cookie cookie in _cookies) { yield return cookie; } } } } public WebSocketSharp.Net.NetworkCredential Credentials => _credentials; public bool EmitOnPing { get { return _emitOnPing; } set { _emitOnPing = value; } } public bool EnableRedirection { get { return _enableRedirection; } set { string text = null; if (!_client) { text = "The set operation cannot be used by servers."; throw new InvalidOperationException(text); } if (!canSet(out text)) { _logger.Warn(text); return; } lock (_forState) { if (!canSet(out text)) { _logger.Warn(text); } else { _enableRedirection = value; } } } } public string Extensions => _extensions ?? string.Empty; public bool IsAlive => ping(EmptyBytes); public bool IsSecure => _secure; public Logger Log { get { return _logger; } internal set { _logger = value; } } public string Origin { get { return _origin; } set { string text = null; if (!_client) { text = "This instance is not a client."; throw new InvalidOperationException(text); } if (!value.IsNullOrEmpty()) { if (!Uri.TryCreate(value, UriKind.Absolute, out Uri result)) { text = "Not an absolute URI string."; throw new ArgumentException(text, value); } if (result.Segments.Length > 1) { text = "It includes the path segments."; throw new ArgumentException(text, value); } } if (!canSet(out text)) { _logger.Warn(text); return; } lock (_forState) { if (!canSet(out text)) { _logger.Warn(text); return; } _origin = ((!value.IsNullOrEmpty()) ? value.TrimEnd(new char[1] { '/' }) : value); } } } public string Protocol { get { return _protocol ?? string.Empty; } internal set { _protocol = value; } } public WebSocketState ReadyState => _readyState; public ClientSslConfiguration SslConfiguration { get { if (!_client) { throw new InvalidOperationException("This instance is not a client."); } if (!_secure) { throw new InvalidOperationException("This instance does not use a secure connection."); } if (_sslConfig == null) { _sslConfig = new ClientSslConfiguration(_uri.DnsSafeHost); } return _sslConfig; } } public Uri Url { get { if (!_client) { return _context.RequestUri; } return _uri; } } public TimeSpan WaitTime { get { return _waitTime; } set { if (value <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException("value", "Zero or less."); } if (!canSet(out var text)) { _logger.Warn(text); return; } lock (_forState) { if (!canSet(out text)) { _logger.Warn(text); } else { _waitTime = value; } } } } public event EventHandler<CloseEventArgs> OnClose; public event EventHandler<ErrorEventArgs> OnError; public event EventHandler<MessageEventArgs> OnMessage; public event EventHandler OnOpen; static WebSocket() { _maxRetryCountForConnect = 10; EmptyBytes = new byte[0]; FragmentLength = 1016; RandomNumber = new RNGCryptoServiceProvider(); } internal WebSocket(HttpListenerWebSocketContext context, string protocol) { _context = context; _protocol = protocol; _closeContext = context.Close; _logger = context.Log; _message = messages; _secure = context.IsSecureConnection; _stream = context.Stream; _waitTime = TimeSpan.FromSeconds(1.0); init(); } internal WebSocket(TcpListenerWebSocketContext context, string protocol) { _context = context; _protocol = protocol; _closeContext = context.Close; _logger = context.Log; _message = messages; _secure = context.IsSecureConnection; _stream = context.Stream; _waitTime = TimeSpan.FromSeconds(1.0); init(); } public WebSocket(string url, params string[] protocols) { if (url == null) { throw new ArgumentNullException("url"); } if (url.Length == 0) { throw new ArgumentException("An empty string.", "url"); } if (!url.TryCreateWebSocketUri(out _uri, out var text)) { throw new ArgumentException(text, "url"); } if (protocols != null && protocols.Length != 0) { if (!checkProtocols(protocols, out text)) { throw new ArgumentException(text, "protocols"); } _protocols = protocols; } _base64Key = CreateBase64Key(); _client = true; _logger = new Logger(); _message = messagec; _secure = _uri.Scheme == "wss"; _waitTime = TimeSpan.FromSeconds(5.0); init(); } private bool accept() { lock (_forState) { if (!checkIfAvailable(connecting: true, open: false, closing: false, closed: false, out var text)) { _logger.Error(text); error("An error has occurred in accepting.", null); return false; } try { if (!acceptHandshake()) { return false; } _readyState = WebSocketState.Open; } catch (Exception ex) { _logger.Fatal(ex.ToString()); fatal("An exception has occurred while accepting.", ex); return false; } return true; } } private bool acceptHandshake() { _logger.Debug($"A request from {_context.UserEndPoint}:\n{_context}"); if (!checkHandshakeRequest(_context, out var text)) { sendHttpResponse(createHandshakeFailureResponse(WebSocketSharp.Net.HttpStatusCode.BadRequest)); _logger.Fatal(text); fatal("An error has occurred while accepting.", CloseStatusCode.ProtocolError); return false; } if (!customCheckHandshakeRequest(_context, out text)) { sendHttpResponse(createHandshakeFailureResponse(WebSocketSharp.Net.HttpStatusCode.BadRequest)); _logger.Fatal(text); fatal("An error has occurred while accepting.", CloseStatusCode.PolicyViolation); return false; } _base64Key = _context.Headers["Sec-WebSocket-Key"]; if (_protocol != null) { processSecWebSocketProtocolHeader(_context.SecWebSocketProtocols); } if (!_ignoreExtensions) { processSecWebSocketExtensionsClientHeader(_context.Headers["Sec-WebSocket-Extensions"]); } return sendHttpResponse(createHandshakeResponse()); } private bool canSet(out string message) { message = null; if (_readyState == WebSocketState.Open) { message = "The connection has already been established."; return false; } if (_readyState == WebSocketState.Closing) { message = "The connection is closing."; return false; } return true; } private bool checkHandshakeRequest(WebSocketContext context, out string message) { message = null; if (context.RequestUri == null) { message = "Specifies an invalid Request-URI."; return false; } if (!context.IsWebSocketRequest) { message = "Not a WebSocket handshake request."; return false; } NameValueCollection headers = context.Headers; if (!validateSecWebSocketKeyHeader(headers["Sec-WebSocket-Key"])) { message = "Includes no Sec-WebSocket-Key header, or it has an invalid value."; return false; } if (!validateSecWebSocketVersionClientHeader(headers["Sec-WebSocket-Version"])) { message = "Includes no Sec-WebSocket-Version header, or it has an invalid value."; return false; } if (!validateSecWebSocketProtocolClientHeader(headers["Sec-WebSocket-Protocol"])) { message = "Includes an invalid Sec-WebSocket-Protocol header."; return false; } if (!_ignoreExtensions && !validateSecWebSocketExtensionsClientHeader(headers["Sec-WebSocket-Extensions"])) { message = "Includes an invalid Sec-WebSocket-Extensions header."; return false; } return true; } private bool checkHandshakeResponse(HttpResponse response, out string message) { message = null; if (response.IsRedirect) { message = "Indicates the redirection."; return false; } if (response.IsUnauthorized) { message = "Requires the authentication."; return false; } if (!response.IsWebSocketResponse) { message = "Not a WebSocket handshake response."; return false; } NameValueCollection headers = response.Headers; if (!validateSecWebSocketAcceptHeader(headers["Sec-WebSocket-Accept"])) { message = "Includes no Sec-WebSocket-Accept header, or it has an invalid value."; return false; } if (!validateSecWebSocketProtocolServerHeader(headers["Sec-WebSocket-Protocol"])) { message = "Includes no Sec-WebSocket-Protocol header, or it has an invalid value."; return false; } if (!validateSecWebSocketExtensionsServerHeader(headers["Sec-WebSocket-Extensions"])) { message = "Includes an invalid Sec-WebSocket-Extensions header."; return false; } if (!validateSecWebSocketVersionServerHeader(headers["Sec-WebSocket-Version"])) { message = "Includes an invalid Sec-WebSocket-Version header."; return false; } return true; } private bool checkIfAvailable(bool connecting, bool open, bool closing, bool closed, out string message) { message = null; if (!connecting && _readyState == WebSocketState.Connecting) { message = "This operation is not available in: connecting"; return false; } if (!open && _readyState == WebSocketState.Open) { message = "This operation is not available in: open"; return false; } if (!closing && _readyState == WebSocketState.Closing) { message = "This operation is not available in: closing"; return false; } if (!closed && _readyState == WebSocketState.Closed) { message = "This operation is not available in: closed"; return false; } return true; } private bool checkIfAvailable(bool client, bool server, bool connecting, bool open, bool closing, bool closed, out string message) { message = null; if (!client && _client) { message = "This operation is not available in: client"; return false; } if (!server && !_client) { message = "This operation is not available in: server"; return false; } return checkIfAvailable(connecting, open, closing, closed, out message); } private static bool checkParametersForSetCredentials(string username, string password, out string message) { message = null; if (username.IsNullOrEmpty()) { return true; } if (Ext.Contains(username, ':') || !username.IsText()) { message = "'username' contains an invalid character."; return false; } if (password.IsNullOrEmpty()) { return true; } if (!password.IsText()) { message = "'password' contains an invalid character."; return false; } return true; } private static bool checkParametersForSetProxy(string url, string username, string password, out string message) { message = null; if (url.IsNullOrEmpty()) { return true; } if (!Uri.TryCreate(url, UriKind.Absolute, out Uri result) || result.Scheme != "http" || result.Segments.Length > 1) { message = "'url' is an invalid URL."; return false; } if (username.IsNullOrEmpty()) { return true; } if (Ext.Contains(username, ':') || !username.IsText()) { message = "'username' contains an invalid character."; return false; } if (password.IsNullOrEmpty()) { return true; } if (!password.IsText()) { message = "'password' contains an invalid character."; return false; } return true; } private static bool checkProtocols(string[] protocols, out string message) { message = null; Func<string, bool> condition = (string protocol) => protocol.IsNullOrEmpty() || !protocol.IsToken(); if (protocols.Contains(condition)) { message = "It contains a value that is not a token."; return false; } if (protocols.ContainsTwice()) { message = "It contains a value twice."; return false; } return true; } private bool checkReceivedFrame(WebSocketFrame frame, out string message) { message = null; bool isMasked = frame.IsMasked; if (_client && isMasked) { message = "A frame from the server is masked."; return false; } if (!_client && !isMasked) { message = "A frame from a client is not masked."; return false; } if (_inContinuation && frame.IsData) { message = "A data frame has been received while receiving continuation frames."; return false; } if (frame.IsCompressed && _compression == CompressionMethod.None) { message = "A compressed frame has been received without any agreement for it."; return false; } if (frame.Rsv2 == Rsv.On) { message = "The RSV2 of a frame is non-zero without any negotiation for it."; return false; } if (frame.Rsv3 == Rsv.On) { message = "The RSV3 of a frame is non-zero without any negotiation for it."; return false; } return true; } private void close(ushort code, string reason) { if (_readyState == WebSocketState.Closing) { _logger.Info("The closing is already in progress."); return; } if (_readyState == WebSocketState.Closed) { _logger.Info("The connection has already been closed."); return; } if (code == 1005) { close(PayloadData.Empty, send: true, receive: true, received: false); return; } bool receive = !code.IsReserved(); close(new PayloadData(code, reason), receive, receive, received: false); } private void close(PayloadData payloadData, bool send, bool receive, bool received) { lock (_forState) { if (_readyState == WebSocketState.Closing) { _logger.Info("The closing is already in progress."); return; } if (_readyState == WebSocketState.Closed) { _logger.Info("The connection has already been closed."); return; } send = send && _readyState == WebSocketState.Open; receive = send && receive; _readyState = WebSocketState.Closing; } _logger.Trace("Begin closing the connection."); bool wasClean = closeHandshake(payloadData, send, receive, received); releaseResources(); _logger.Trace("End closing the connection."); _readyState = WebSocketState.Closed; CloseEventArgs closeEventArgs = new CloseEventArgs(payloadData); closeEventArgs.WasClean = wasClean; try { this.OnClose.Emit(this, closeEventArgs); } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during the OnClose event.", ex); } } private void closeAsync(ushort code, string reason) { if (_readyState == WebSocketState.Closing) { _logger.Info("The closing is already in progress."); return; } if (_readyState == WebSocketState.Closed) { _logger.Info("The connection has already been closed."); return; } if (code == 1005) { closeAsync(PayloadData.Empty, send: true, receive: true, received: false); return; } bool receive = !code.IsReserved(); closeAsync(new PayloadData(code, reason), receive, receive, received: false); } private void closeAsync(PayloadData payloadData, bool send, bool receive, bool received) { Action<PayloadData, bool, bool, bool> closer = close; closer.BeginInvoke(payloadData, send, receive, received, delegate(IAsyncResult ar) { closer.EndInvoke(ar); }, null); } private bool closeHandshake(byte[] frameAsBytes, bool receive, bool received) { bool flag = frameAsBytes != null && sendBytes(frameAsBytes); if (!received && flag && receive && _receivingExited != null) { received = _receivingExited.WaitOne(_waitTime); } bool flag2 = flag && received; _logger.Debug($"Was clean?: {flag2}\n sent: {flag}\n received: {received}"); return flag2; } private bool closeHandshake(PayloadData payloadData, bool send, bool receive, bool received) { bool flag = false; if (send) { WebSocketFrame webSocketFrame = WebSocketFrame.CreateCloseFrame(payloadData, _client); flag = sendBytes(webSocketFrame.ToArray()); if (_client) { webSocketFrame.Unmask(); } } if (!received && flag && receive && _receivingExited != null) { received = _receivingExited.WaitOne(_waitTime); } bool flag2 = flag && received; _logger.Debug($"Was clean?: {flag2}\n sent: {flag}\n received: {received}"); return flag2; } private bool connect() { lock (_forState) { if (!checkIfAvailable(connecting: true, open: false, closing: false, closed: true, out var text)) { _logger.Error(text); error("An error has occurred in connecting.", null); return false; } if (_retryCountForConnect > _maxRetryCountForConnect) { _retryCountForConnect = 0; _logger.Fatal("A series of reconnecting has failed."); return false; } _readyState = WebSocketState.Connecting; try { doHandshake(); } catch (Exception ex) { _retryCountForConnect++; _logger.Fatal(ex.ToString()); fatal("An exception has occurred while connecting.", ex); return false; } _retryCountForConnect = 1; _readyState = WebSocketState.Open; return true; } } private string createExtensions() { StringBuilder stringBuilder = new StringBuilder(80); if (_compression != 0) { string arg = _compression.ToExtensionString("server_no_context_takeover", "client_no_context_takeover"); stringBuilder.AppendFormat("{0}, ", arg); } int length = stringBuilder.Length; if (length > 2) { stringBuilder.Length = length - 2; return stringBuilder.ToString(); } return null; } private HttpResponse createHandshakeFailureResponse(WebSocketSharp.Net.HttpStatusCode code) { HttpResponse httpResponse = HttpResponse.CreateCloseResponse(code); httpResponse.Headers["Sec-WebSocket-Version"] = "13"; return httpResponse; } private HttpRequest createHandshakeRequest() { HttpRequest httpRequest = HttpRequest.CreateWebSocketRequest(_uri); NameValueCollection headers = httpRequest.Headers; if (!_origin.IsNullOrEmpty()) { headers["Origin"] = _origin; } headers["Sec-WebSocket-Key"] = _base64Key; _protocolsRequested = _protocols != null; if (_protocolsRequested) { headers["Sec-WebSocket-Protocol"] = _protocols.ToString(", "); } _extensionsRequested = _compression != CompressionMethod.None; if (_extensionsRequested) { headers["Sec-WebSocket-Extensions"] = createExtensions(); } headers["Sec-WebSocket-Version"] = "13"; AuthenticationResponse authenticationResponse = null; if (_authChallenge != null && _credentials != null) { authenticationResponse = new AuthenticationResponse(_authChallenge, _credentials, _nonceCount); _nonceCount = authenticationResponse.NonceCount; } else if (_preAuth) { authenticationResponse = new AuthenticationResponse(_credentials); } if (authenticationResponse != null) { headers["Authorization"] = authenticationResponse.ToString(); } if (_cookies.Count > 0) { httpRequest.SetCookies(_cookies); } return httpRequest; } private HttpResponse createHandshakeResponse() { HttpResponse httpResponse = HttpResponse.CreateWebSocketResponse(); NameValueCollection headers = httpResponse.Headers; headers["Sec-WebSocket-Accept"] = CreateResponseKey(_base64Key); if (_protocol != null) { headers["Sec-WebSocket-Protocol"] = _protocol; } if (_extensions != null) { headers["Sec-WebSocket-Extensions"] = _extensions; } if (_cookies.Count > 0) { httpResponse.SetCookies(_cookies); } return httpResponse; } private bool customCheckHandshakeRequest(WebSocketContext context, out string message) { message = null; if (_handshakeRequestChecker != null) { return (message = _handshakeRequestChecker(context)) == null; } return true; } private MessageEventArgs dequeueFromMessageEventQueue() { lock (_forMessageEventQueue) { return (_messageEventQueue.Count > 0) ? _messageEventQueue.Dequeue() : null; } } private void doHandshake() { setClientStream(); HttpResponse httpResponse = sendHandshakeRequest(); if (!checkHandshakeResponse(httpResponse, out var text)) { throw new WebSocketException(CloseStatusCode.ProtocolError, text); } if (_protocolsRequested) { _protocol = httpResponse.Headers["Sec-WebSocket-Protocol"]; } if (_extensionsRequested) { processSecWebSocketExtensionsServerHeader(httpResponse.Headers["Sec-WebSocket-Extensions"]); } processCookies(httpResponse.Cookies); } private void enqueueToMessageEventQueue(MessageEventArgs e) { lock (_forMessageEventQueue) { _messageEventQueue.Enqueue(e); } } private void error(string message, Exception exception) { try { this.OnError.Emit(this, new ErrorEventArgs(message, exception)); } catch (Exception ex) { _logger.Error(ex.ToString()); } } private void fatal(string message, Exception exception) { CloseStatusCode code = ((exception is WebSocketException) ? ((WebSocketException)exception).Code : CloseStatusCode.Abnormal); fatal(message, (ushort)code); } private void fatal(string message, ushort code) { PayloadData payloadData = new PayloadData(code, message); close(payloadData, !code.IsReserved(), receive: false, received: false); } private void fatal(string message, CloseStatusCode code) { fatal(message, (ushort)code); } private void init() { _compression = CompressionMethod.None; _cookies = new WebSocketSharp.Net.CookieCollection(); _forPing = new object(); _forSend = new object(); _forState = new object(); _messageEventQueue = new Queue<MessageEventArgs>(); _forMessageEventQueue = ((ICollection)_messageEventQueue).SyncRoot; _readyState = WebSocketState.Connecting; } private void message() { MessageEventArgs obj = null; lock (_forMessageEventQueue) { if (_inMessage || _messageEventQueue.Count == 0 || _readyState != WebSocketState.Open) { return; } _inMessage = true; obj = _messageEventQueue.Dequeue(); } _message(obj); } private void messagec(MessageEventArgs e) { while (true) { try { this.OnMessage.Emit(this, e); } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during an OnMessage event.", ex); } lock (_forMessageEventQueue) { if (_messageEventQueue.Count == 0 || _readyState != WebSocketState.Open) { _inMessage = false; break; } e = _messageEventQueue.Dequeue(); } } } private void messages(MessageEventArgs e) { try { this.OnMessage.Emit(this, e); } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during an OnMessage event.", ex); } lock (_forMessageEventQueue) { if (_messageEventQueue.Count == 0 || _readyState != WebSocketState.Open) { _inMessage = false; return; } e = _messageEventQueue.Dequeue(); } ThreadPool.QueueUserWorkItem(delegate { messages(e); }); } private void open() { _inMessage = true; startReceiving(); try { this.OnOpen.Emit(this, EventArgs.Empty); } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during the OnOpen event.", ex); } MessageEventArgs obj = null; lock (_forMessageEventQueue) { if (_messageEventQueue.Count == 0 || _readyState != WebSocketState.Open) { _inMessage = false; return; } obj = _messageEventQueue.Dequeue(); } _message.BeginInvoke(obj, delegate(IAsyncResult ar) { _message.EndInvoke(ar); }, null); } private bool ping(byte[] data) { if (_readyState != WebSocketState.Open) { return false; } ManualResetEvent pongReceived = _pongReceived; if (pongReceived == null) { return false; } lock (_forPing) { try { pongReceived.Reset(); if (!send(Fin.Final, Opcode.Ping, data, compressed: false)) { return false; } return pongReceived.WaitOne(_waitTime); } catch (ObjectDisposedException) { return false; } } } private bool processCloseFrame(WebSocketFrame frame) { PayloadData payloadData = frame.PayloadData; close(payloadData, !payloadData.HasReservedCode, receive: false, received: true); return false; } private void processCookies(WebSocketSharp.Net.CookieCollection cookies) { if (cookies.Count != 0) { _cookies.SetOrRemove(cookies); } } private bool processDataFrame(WebSocketFrame frame) { enqueueToMessageEventQueue(frame.IsCompressed ? new MessageEventArgs(frame.Opcode, frame.PayloadData.ApplicationData.Decompress(_compression)) : new MessageEventArgs(frame)); return true; } private bool processFragmentFrame(WebSocketFrame frame) { if (!_inContinuation) { if (frame.IsContinuation) { return true; } _fragmentsOpcode = frame.Opcode; _fragmentsCompressed = frame.IsCompressed; _fragmentsBuffer = new MemoryStream(); _inContinuation = true; } _fragmentsBuffer.WriteBytes(frame.PayloadData.ApplicationData, 1024); if (frame.IsFinal) { using (_fragmentsBuffer) { byte[] rawData = (_fragmentsCompressed ? _fragmentsBuffer.DecompressToArray(_compression) : _fragmentsBuffer.ToArray()); enqueueToMessageEventQueue(new MessageEventArgs(_fragmentsOpcode, rawData)); } _fragmentsBuffer = null; _inContinuation = false; } return true; } private bool processPingFrame(WebSocketFrame frame) { _logger.Trace("A ping was received."); WebSocketFrame webSocketFrame = WebSocketFrame.CreatePongFrame(frame.PayloadData, _client); lock (_forState) { if (_readyState != WebSocketState.Open) { _logger.Error("The connection is closing."); return true; } if (!sendBytes(webSocketFrame.ToArray())) { return false; } } _logger.Trace("A pong to this ping has been sent."); if (_emitOnPing) { if (_client) { webSocketFrame.Unmask(); } enqueueToMessageEventQueue(new MessageEventArgs(frame)); } return true; } private bool processPongFrame(WebSocketFrame frame) { _logger.Trace("A pong was received."); try { _pongReceived.Set(); } catch (NullReferenceException ex) { _logger.Error(ex.Message); _logger.Debug(ex.ToString()); return false; } catch (ObjectDisposedException ex2) { _logger.Error(ex2.Message); _logger.Debug(ex2.ToString()); return false; } _logger.Trace("It has been signaled."); return true; } private bool processReceivedFrame(WebSocketFrame frame) { if (!checkReceivedFrame(frame, out var text)) { throw new WebSocketException(CloseStatusCode.ProtocolError, text); } frame.Unmask(); if (!frame.IsFragment) { if (!frame.IsData) { if (!frame.IsPing) { if (!frame.IsPong) { if (!frame.IsClose) { return processUnsupportedFrame(frame); } return processCloseFrame(frame); } return processPongFrame(frame); } return processPingFrame(frame); } return processDataFrame(frame); } return processFragmentFrame(frame); } private void processSecWebSocketExtensionsClientHeader(string value) { if (value == null) { return; } StringBuilder stringBuilder = new StringBuilder(80); bool flag = false; foreach (string item in value.SplitHeaderValue(',')) { string value2 = item.Trim(); if (!flag && value2.IsCompressionExtension(CompressionMethod.Deflate)) { _compression = CompressionMethod.Deflate; stringBuilder.AppendFormat("{0}, ", _compression.ToExtensionString("client_no_context_takeover", "server_no_context_takeover")); flag = true; } } int length = stringBuilder.Length; if (length > 2) { stringBuilder.Length = length - 2; _extensions = stringBuilder.ToString(); } } private void processSecWebSocketExtensionsServerHeader(string value) { if (value == null) { _compression = CompressionMethod.None; } else { _extensions = value; } } private void processSecWebSocketProtocolHeader(IEnumerable<string> values) { if (!values.Contains((string p) => p == _protocol)) { _protocol = null; } } private bool processUnsupportedFrame(WebSocketFrame frame) { _logger.Fatal("An unsupported frame:" + frame.PrintToString(dumped: false)); fatal("There is no way to handle it.", CloseStatusCode.PolicyViolation); return false; } private void releaseClientResources() { if (_stream != null) { _stream.Dispose(); _stream = null; } if (_tcpClient != null) { _tcpClient.Close(); _tcpClient = null; } } private void releaseCommonResources() { if (_fragmentsBuffer != null) { _fragmentsBuffer.Dispose(); _fragmentsBuffer = null; _inContinuation = false; } if (_pongReceived != null) { _pongReceived.Close(); _pongReceived = null; } if (_receivingExited != null) { _receivingExited.Close(); _receivingExited = null; } } private void releaseResources() { if (_client) { releaseClientResources(); } else { releaseServerResources(); } releaseCommonResources(); } private void releaseServerResources() { if (_closeContext != null) { _closeContext(); _closeContext = null; _stream = null; _context = null; } } private bool send(Opcode opcode, Stream stream) { lock (_forSend) { Stream stream2 = stream; bool flag = false; bool flag2 = false; try { if (_compression != 0) { stream = stream.Compress(_compression); flag = true; } flag2 = send(opcode, stream, flag); if (!flag2) { error("A send has been interrupted.", null); } } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during a send.", ex); } finally { if (flag) { stream.Dispose(); } stream2.Dispose(); } return flag2; } } private bool send(Opcode opcode, Stream stream, bool compressed) { long length = stream.Length; if (length == 0L) { return send(Fin.Final, opcode, EmptyBytes, compressed: false); } long num = length / FragmentLength; int num2 = (int)(length % FragmentLength); byte[] array = null; switch (num) { case 0L: array = new byte[num2]; if (stream.Read(array, 0, num2) == num2) { return send(Fin.Final, opcode, array, compressed); } return false; case 1L: if (num2 == 0) { array = new byte[FragmentLength]; if (stream.Read(array, 0, FragmentLength) == FragmentLength) { return send(Fin.Final, opcode, array, compressed); } return false; } break; } array = new byte[FragmentLength]; if (stream.Read(array, 0, FragmentLength) != FragmentLength || !send(Fin.More, opcode, array, compressed)) { return false; } long num3 = ((num2 == 0) ? (num - 2) : (num - 1)); for (long num4 = 0L; num4 < num3; num4++) { if (stream.Read(array, 0, FragmentLength) != FragmentLength || !send(Fin.More, Opcode.Cont, array, compressed: false)) { return false; } } if (num2 == 0) { num2 = FragmentLength; } else { array = new byte[num2]; } if (stream.Read(array, 0, num2) == num2) { return send(Fin.Final, Opcode.Cont, array, compressed: false); } return false; } private bool send(Fin fin, Opcode opcode, byte[] data, bool compressed) { lock (_forState) { if (_readyState != WebSocketState.Open) { _logger.Error("The connection is closing."); return false; } WebSocketFrame webSocketFrame = new WebSocketFrame(fin, opcode, data, compressed, _client); return sendBytes(webSocketFrame.ToArray()); } } private void sendAsync(Opcode opcode, Stream stream, Action<bool> completed) { Func<Opcode, Stream, bool> sender = send; sender.BeginInvoke(opcode, stream, delegate(IAsyncResult ar) { try { bool obj = sender.EndInvoke(ar); if (completed != null) { completed(obj); } } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during the callback for an async send.", ex); } }, null); } private bool sendBytes(byte[] bytes) { try { _stream.Write(bytes, 0, bytes.Length); } catch (Exception ex) { _logger.Error(ex.Message); _logger.Debug(ex.ToString()); return false; } return true; } private HttpResponse sendHandshakeRequest() { HttpRequest httpRequest = createHandshakeRequest(); HttpResponse httpResponse = sendHttpRequest(httpRequest, 90000); if (httpResponse.IsUnauthorized) { string text = httpResponse.Headers["WWW-Authenticate"]; _logger.Warn($"Received an authentication requirement for '{text}'."); if (text.IsNullOrEmpty()) { _logger.Error("No authentication challenge is specified."); return httpResponse; } _authChallenge = AuthenticationChallenge.Parse(text); if (_authChallenge == null) { _logger.Error("An invalid authentication challenge is specified."); return httpResponse; } if (_credentials != null && (!_preAuth || _authChallenge.Scheme == WebSocketSharp.Net.AuthenticationSchemes.Digest)) { if (httpResponse.HasConnectionClose) { releaseClientResources(); setClientStream(); } AuthenticationResponse authenticationResponse = new AuthenticationResponse(_authChallenge, _credentials, _nonceCount); _nonceCount = authenticationResponse.NonceCount; httpRequest.Headers["Authorization"] = authenticationResponse.ToString(); httpResponse = sendHttpRequest(httpRequest, 15000); } } if (httpResponse.IsRedirect) { string text2 = httpResponse.Headers["Location"]; _logger.Warn($"Received a redirection to '{text2}'."); if (_enableRedirection) { if (text2.IsNullOrEmpty()) { _logger.Error("No url to redirect is located."); return httpResponse; } if (!text2.TryCreateWebSocketUri(out var result, out var text3)) { _logger.Error("An invalid url to redirect is located: " + text3); return httpResponse; } releaseClientResources(); _uri = result; _secure = result.Scheme == "wss"; setClientStream(); return sendHandshakeRequest(); } } return httpResponse; } private HttpResponse sendHttpRequest(HttpRequest request, int millisecondsTimeout) { _logger.Debug("A request to the server:\n" + request.ToString()); HttpResponse response = request.GetResponse(_stream, millisecondsTimeout); _logger.Debug("A response to this request:\n" + response.ToString()); return response; } private bool sendHttpResponse(HttpResponse response) { _logger.Debug("A response to this request:\n" + response.ToString()); return sendBytes(response.ToByteArray()); } private void sendProxyConnectRequest() { HttpRequest httpRequest = HttpRequest.CreateConnectRequest(_uri); HttpResponse httpResponse = sendHttpRequest(httpRequest, 90000); if (httpResponse.IsProxyAuthenticationRequired) { string text = httpResponse.Headers["Proxy-Authenticate"]; _logger.Warn($"Received a proxy authentication requirement for '{text}'."); if (text.IsNullOrEmpty()) { throw new WebSocketException("No proxy authentication challenge is specified."); } AuthenticationChallenge authenticationChallenge = AuthenticationChallenge.Parse(text); if (authenticationChallenge == null) { throw new WebSocketException("An invalid proxy authentication challenge is specified."); } if (_proxyCredentials != null) { if (httpResponse.HasConnectionClose) { releaseClientResources(); _tcpClient = new TcpClient(_proxyUri.DnsSafeHost, _proxyUri.Port); _stream = _tcpClient.GetStream(); } AuthenticationResponse authenticationResponse = new AuthenticationResponse(authenticationChallenge, _proxyCredentials, 0u); httpRequest.Headers["Proxy-Authorization"] = authenticationResponse.ToString(); httpResponse = sendHttpRequest(httpRequest, 15000); } if (httpResponse.IsProxyAuthenticationRequired) { throw new WebSocketException("A proxy authentication is required."); } } if (httpResponse.StatusCode[0] != '2') { throw new WebSocketException("The proxy has failed a connection to the requested host and port."); } } private void setClientStream() { if (_proxyUri != null) { _tcpClient = new TcpClient(_proxyUri.DnsSafeHost, _proxyUri.Port); _stream = _tcpClient.GetStream(); sendProxyConnectRequest(); } else { _tcpClient = new TcpClient(_uri.DnsSafeHost, _uri.Port); _stream = _tcpClient.GetStream(); } if (_secure) { ClientSslConfiguration sslConfiguration = SslConfiguration; string targetHost = sslConfiguration.TargetHost; if (targetHost != _uri.DnsSafeHost) { throw new WebSocketException(CloseStatusCode.TlsHandshakeFailure, "An invalid host name is specified."); } try { SslStream sslStream = new SslStream(_stream, leaveInnerStreamOpen: false, sslConfiguration.ServerCertificateValidationCallback, sslConfiguration.ClientCertificateSelectionCallback); sslStream.AuthenticateAsClient(targetHost, sslConfiguration.ClientCertificates, sslConfiguration.EnabledSslProtocols, sslConfiguration.CheckCertificateRevocation); _stream = sslStream; } catch (Exception innerException) { throw new WebSocketException(CloseStatusCode.TlsHandshakeFailure, innerException); } } } private void startReceiving() { if (_messageEventQueue.Count > 0) { _messageEventQueue.Clear(); } _pongReceived = new ManualResetEvent(initialState: false); _receivingExited = new ManualResetEvent(initialState: false); Action receive = null; receive = delegate { WebSocketFrame.ReadFrameAsync(_stream, unmask: false, delegate(WebSocketFrame frame) { if (!processReceivedFrame(frame) || _readyState == WebSocketState.Closed) { _receivingExited?.Set(); } else { receive(); if (!_inMessage && HasMessage && _readyState == WebSocketState.Open) { message(); } } }, delegate(Exception ex) { _logger.Fatal(ex.ToString()); fatal("An exception has occurred while receiving.", ex); }); }; receive(); } private bool validateSecWebSocketAcceptHeader(string value) { if (value != null) { return value == CreateResponseKey(_base64Key); } return false; } private bool validateSecWebSocketExtensionsClientHeader(string value) { if (value != null) { return value.Length > 0; } return true; } private bool validateSecWebSocketExtensionsServerHeader(string value) { if (value == null) { return true; } if (value.Length == 0) { return false; } if (!_extensionsRequested) { return false; } bool flag = _compression != CompressionMethod.None; foreach (string item in value.SplitHeaderValue(',')) { string text = item.Trim(); if (flag && text.IsCompressionExtension(_compression)) { if (!text.Contains("server_no_context_takeover")) { _logger.Error("The server hasn't sent back 'server_no_context_takeover'."); return false; } if (!text.Contains("client_no_context_takeover")) { _logger.Warn("The server hasn't sent back 'client_no_context_takeover'."); } string method = _compression.ToExtensionString(); if (text.SplitHeaderValue(';').Contains(delegate(string t) { t = t.Trim(); return t != method && t != "server_no_context_takeover" && t != "client_no_context_takeover"; })) { return false; } continue; } return false; } return true; } private bool validateSecWebSocketKeyHeader(string value) { if (value != null) { return value.Length > 0; } return false; } private bool validateSecWebSocketProtocolClientHeader(string value) { if (value != null) { return value.Length > 0; } return true; } private bool validateSecWebSocketProtocolServerHeader(string value) { if (value == null) { return !_protocolsRequested; } if (value.Length == 0) { return false; } if (_protocolsRequested) { return _protocols.Contains((string p) => p == value); } return false; } private bool validateSecWebSocketVersionClientHeader(string value) { if (value != null) { return value == "13"; } return false; } private bool validateSecWebSocketVersionServerHeader(string value) { if (value != null) { return value == "13"; } return true; } internal void Close(HttpResponse response) { _readyState = Web