Decompiled source of ValheimTwitch v0.5.0

BepInEx/plugins/ValheimTwitch/Newtonsoft.Json.dll

Decompiled 21 hours ago
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

BepInEx/plugins/ValheimTwitch/ValheimTwitch.dll

Decompiled 21 hours ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Managers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Splatform;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using ValheimTwitch.Commands;
using ValheimTwitch.Configuration;
using ValheimTwitch.Networking;
using ValheimTwitch.Portraits;
using ValheimTwitch.Spawning;
using ValheimTwitch.UI;
using WebSocketSharp;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyCompany("ValheimTwitch")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.4.0.0")]
[assembly: AssemblyInformationalVersion("0.4.0")]
[assembly: AssemblyProduct("ValheimTwitch")]
[assembly: AssemblyTitle("ValheimTwitch")]
[assembly: AssemblyVersion("0.4.0.0")]
namespace ValheimTwitch
{
	[BepInPlugin("CodeWithTD.ValheimTwitch", "ValheimTwitch", "0.5.0")]
	public class ValheimTwitchPlugin : BaseUnityPlugin
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static ConsoleOptionsFetcher <>9__16_1;

			internal List<string> <RegisterRequestCommand>b__16_1()
			{
				return new List<string>(PrefabCatalog.Items);
			}
		}

		public const string PluginGuid = "CodeWithTD.ValheimTwitch";

		public const string PluginName = "ValheimTwitch";

		public const string PluginVersion = "0.5.0";

		internal static ManualLogSource Log;

		private ModConfig _config;

		private StreamerBotClient _client;

		private CommandRouter _router;

		private NotificationManager _notifications;

		private Spawner _spawner;

		private RaidManager _raids;

		private PortraitManager _portraits;

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			_config = new ModConfig(((BaseUnityPlugin)this).Config);
			MainThreadDispatcher.Init(Log);
			_notifications = new NotificationManager(_config);
			_spawner = new Spawner(_config);
			_raids = new RaidManager(_config);
			_portraits = new PortraitManager(_config);
			_router = new CommandRouter(_config, _notifications, _spawner, _raids, _portraits);
			RegisterRequestCommand();
			_client = new StreamerBotClient(_config);
			_client.EventReceived += OnStreamerBotEvent;
			if (_config.WebSocketEnabled.Value)
			{
				_client.Connect();
			}
			else
			{
				Log.LogInfo((object)"ValheimTwitch: WebSocket integration is disabled in the configuration.");
			}
			Log.LogInfo((object)"ValheimTwitch v0.5.0 loaded.");
		}

		private void Update()
		{
			_client?.Tick();
			MainThreadDispatcher.InvokePending();
		}

		private void OnDestroy()
		{
			_client?.Close();
			MainThreadDispatcher.Clear();
		}

		private void OnStreamerBotEvent(StreamerBotEvent evt)
		{
			string title;
			string message;
			if (evt.Source == "General" && evt.Type == "Custom")
			{
				RouteCustomCommand(evt.Data);
			}
			else if (TwitchEventFormatter.TryFormatNotification(evt, out title, out message))
			{
				_notifications.ShowTopLeft(title, message);
			}
		}

		private void RouteCustomCommand(JObject data)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Invalid comparison between Unknown and I4
			if (data == null)
			{
				return;
			}
			JToken val = data["action"];
			if (val != null && (int)val.Type == 8)
			{
				string text = Extensions.Value<string>((IEnumerable<JToken>)val);
				CommandResult commandResult = _router.Execute(text, data);
				if (commandResult.Success)
				{
					Log.LogInfo((object)("Command '" + text + "' succeeded: " + commandResult.Message));
				}
				else
				{
					Log.LogWarning((object)("Command '" + text + "' rejected: " + commandResult.Message));
				}
			}
		}

		private void RegisterRequestCommand()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_003e: 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_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			ConsoleEvent val = delegate(ConsoleEventArgs args)
			{
				HandleRequestCommand(args);
			};
			object obj = <>c.<>9__16_1;
			if (obj == null)
			{
				ConsoleOptionsFetcher val2 = () => new List<string>(PrefabCatalog.Items);
				<>c.<>9__16_1 = val2;
				obj = (object)val2;
			}
			new ConsoleCommand("request", "ValheimTwitch: forward an item request to Streamer.bot (/request <item>)", val, false, false, false, false, false, false, (ConsoleOptionsFetcher)obj, false, false, false);
		}

		private void HandleRequestCommand(ConsoleEventArgs args)
		{
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			if (args.Args.Length < 2)
			{
				Terminal context = args.Context;
				if (context != null)
				{
					context.AddString("Usage: /request <item>");
				}
				return;
			}
			if (!_config.RequestsEnabled.Value)
			{
				Terminal context2 = args.Context;
				if (context2 != null)
				{
					context2.AddString("Item requests are disabled in the configuration.");
				}
				return;
			}
			string text = string.Join(" ", args.Args, 1, args.Args.Length - 1).Trim();
			if (text.Length == 0)
			{
				Terminal context3 = args.Context;
				if (context3 != null)
				{
					context3.AddString("Usage: /request <item>");
				}
				return;
			}
			string text2 = NormalizeItemName(text);
			JObject val = new JObject
			{
				["item"] = JToken.op_Implicit(text2),
				["amount"] = JToken.op_Implicit(GetItemStackSize(text2)),
				["player"] = JToken.op_Implicit(GetLocalPlayerName())
			};
			if (!_client.DoAction(_config.RequestActionName.Value, val))
			{
				Terminal context4 = args.Context;
				if (context4 != null)
				{
					context4.AddString("Could not send the request: not connected to Streamer.bot (still connecting, reconnecting, or disabled).");
				}
				return;
			}
			Terminal context5 = args.Context;
			if (context5 != null)
			{
				context5.AddString(string.Format("Item request sent: {0} x {1}", val["amount"], text2));
			}
			Log.LogInfo((object)("Item request for '" + text2 + "' forwarded to Streamer.bot action '" + _config.RequestActionName.Value + "'."));
		}

		private static string NormalizeItemName(string requested)
		{
			if (PrefabCatalog.TryResolveItem(requested, out var canonical))
			{
				return canonical;
			}
			string text = requested.Replace(" ", string.Empty);
			if (PrefabCatalog.TryResolveItem(text, out canonical))
			{
				return canonical;
			}
			return text;
		}

		private static int GetItemStackSize(string item)
		{
			if ((Object)(object)ZNetScene.instance == (Object)null)
			{
				return 1;
			}
			GameObject prefab = ZNetScene.instance.GetPrefab(item);
			int valueOrDefault = ((((Object)(object)prefab != (Object)null) ? prefab.GetComponent<ItemDrop>() : null)?.m_itemData?.m_shared?.m_maxStackSize).GetValueOrDefault();
			if (valueOrDefault >= 1)
			{
				return valueOrDefault;
			}
			return 1;
		}

		private static string GetLocalPlayerName()
		{
			if (!((Object)(object)Player.m_localPlayer != (Object)null))
			{
				return "Server";
			}
			return Player.m_localPlayer.GetPlayerName();
		}
	}
}
namespace ValheimTwitch.UI
{
	public class NotificationManager
	{
		private readonly ModConfig _config;

		public NotificationManager(ModConfig config)
		{
			_config = config;
		}

		public void ShowTopLeft(string title, string message)
		{
			MessageHud val = RequireHud();
			if (!((Object)(object)val == (Object)null))
			{
				if (!string.IsNullOrEmpty(title))
				{
					val.ShowMessage((MessageType)1, title, 0, (Sprite)null, false, true);
				}
				if (!string.IsNullOrEmpty(message))
				{
					val.ShowMessage((MessageType)1, message, 0, (Sprite)null, false, true);
				}
			}
		}

		public void ShowCenter(string message)
		{
			MessageHud val = RequireHud();
			if (!((Object)(object)val == (Object)null) && !string.IsNullOrEmpty(message))
			{
				val.ShowMessage((MessageType)2, message, 0, (Sprite)null, false, true);
			}
		}

		private MessageHud RequireHud()
		{
			if (_config == null || !_config.NotificationsEnabled.Value)
			{
				return null;
			}
			MessageHud instance = MessageHud.instance;
			if ((Object)(object)instance == (Object)null)
			{
				ValheimTwitchPlugin.Log.LogDebug((object)"MessageHud not loaded; notification skipped.");
				return null;
			}
			return instance;
		}
	}
}
namespace ValheimTwitch.Spawning
{
	public static class PrefabCatalog
	{
		public static readonly Dictionary<string, string[]> Mobs = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)
		{
			{
				"Greydwarf",
				new string[4] { "Greyling", "Greydwarf", "Greydwarf_Shaman", "Greydwarf_Brute" }
			},
			{
				"Skeleton",
				new string[2] { "Skeleton", "Skeleton_Poison" }
			},
			{
				"Draugr",
				new string[3] { "Draugr", "Draugr_Ranged", "Draugr_Elite" }
			},
			{
				"Goblin",
				new string[4] { "Goblin", "GoblinArcher", "GoblinBrute", "GoblinShaman" }
			},
			{
				"Blob",
				new string[2] { "Blob", "BlobTar" }
			},
			{
				"Ghost",
				new string[1] { "Ghost" }
			},
			{
				"Troll",
				new string[1] { "Troll" }
			},
			{
				"Neck",
				new string[1] { "Neck" }
			},
			{
				"Boar",
				new string[1] { "Boar" }
			},
			{
				"Wolf",
				new string[1] { "Wolf" }
			},
			{
				"Hatchling",
				new string[1] { "Hatchling" }
			},
			{
				"Golem",
				new string[1] { "Golem" }
			},
			{
				"Fenring",
				new string[1] { "Fenring" }
			},
			{
				"Lox",
				new string[1] { "Lox" }
			},
			{
				"Deathsquito",
				new string[1] { "Deathsquito" }
			},
			{
				"Serpent",
				new string[1] { "Serpent" }
			}
		};

		public static readonly string[] Items = new string[31]
		{
			"Wood", "Stone", "Flint", "FineWood", "Coal", "LeatherScraps", "DeerHide", "WolfPelt", "TinOre", "CopperOre",
			"IronScrap", "SilverOre", "Bronze", "Iron", "Silver", "Gold", "Coins", "Amber", "AmberPearl", "Ruby",
			"RawMeat", "CookedMeat", "Raspberry", "Blueberries", "Mushroom", "Honey", "Torch", "SwordBronze", "SwordIron", "SwordSilver",
			"SwordBlackmetal"
		};

		public static bool TryResolveEnemy(string enemy, out string canonical)
		{
			foreach (string[] value in Mobs.Values)
			{
				foreach (string text in value)
				{
					if (string.Equals(text, enemy, StringComparison.OrdinalIgnoreCase))
					{
						canonical = text;
						return true;
					}
				}
			}
			canonical = null;
			return false;
		}

		public static bool TryResolveItem(string item, out string canonical)
		{
			string[] items = Items;
			foreach (string text in items)
			{
				if (string.Equals(text, item, StringComparison.OrdinalIgnoreCase))
				{
					canonical = text;
					return true;
				}
			}
			canonical = null;
			return false;
		}
	}
	public class RaidManager
	{
		private readonly ModConfig _config;

		public RaidManager(ModConfig config)
		{
			_config = config;
		}

		public CommandResult StartRaid(string raidName)
		{
			if (!TryGetContext(out var events, out var error))
			{
				return CommandResult.Fail(error);
			}
			RandomEvent currentRandomEvent = events.GetCurrentRandomEvent();
			if (currentRandomEvent != null)
			{
				return CommandResult.Fail("The raid '" + currentRandomEvent.m_name + "' is already in progress. Use raid_stop first.");
			}
			if (!string.IsNullOrEmpty(raidName))
			{
				return StartNamedRaid(events, raidName);
			}
			return StartRandomRaid(events);
		}

		public CommandResult StopRaid()
		{
			if (!TryGetContext(out var events, out var error))
			{
				return CommandResult.Fail(error);
			}
			RandomEvent currentRandomEvent = events.GetCurrentRandomEvent();
			if (currentRandomEvent == null)
			{
				return CommandResult.Fail("No raid is currently in progress.");
			}
			events.ResetRandomEvent();
			return CommandResult.Ok("Stopped raid '" + currentRandomEvent.m_name + "'.");
		}

		private CommandResult StartRandomRaid(RandEventSystem events)
		{
			events.StartRandomEvent();
			RandomEvent currentRandomEvent = events.GetCurrentRandomEvent();
			if (currentRandomEvent == null)
			{
				return CommandResult.Fail("No raid is currently possible (biome, base or progression conditions exclude every raid). Trigger a specific raid by name instead.");
			}
			return CommandResult.Ok("Started random raid '" + currentRandomEvent.m_name + "'" + Describe(currentRandomEvent));
		}

		private CommandResult StartNamedRaid(RandEventSystem events, string raidName)
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			RandomEvent val = null;
			List<string> list = new List<string>();
			foreach (RandomEvent @event in events.m_events)
			{
				if (@event.m_enabled)
				{
					list.Add(@event.m_name);
					if (val == null && string.Equals(@event.m_name, raidName, StringComparison.OrdinalIgnoreCase))
					{
						val = @event;
					}
				}
			}
			if (val == null)
			{
				return CommandResult.Fail("Unknown raid '" + raidName + "'. Available raids: " + string.Join(", ", list) + ".");
			}
			events.SetRandomEventByName(val.m_name, GetRaidCenter());
			return CommandResult.Ok("Started raid '" + val.m_name + "'" + Describe(val));
		}

		private static string Describe(RandomEvent evt)
		{
			if (!string.IsNullOrEmpty(evt.m_startMessage))
			{
				return " (" + evt.m_startMessage + ")";
			}
			return "";
		}

		private static Vector3 GetRaidCenter()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer != (Object)null))
			{
				return ZNet.instance.GetReferencePosition();
			}
			return ((Component)localPlayer).transform.position;
		}

		private bool TryGetContext(out RandEventSystem events, out string error)
		{
			events = null;
			if (!_config.RaidsEnabled.Value)
			{
				error = "Raids are disabled in the configuration.";
				return false;
			}
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				error = "Raids can only be triggered on the host/server; they are shared world state.";
				return false;
			}
			if ((Object)(object)RandEventSystem.instance == (Object)null)
			{
				error = "No world is loaded.";
				return false;
			}
			events = RandEventSystem.instance;
			error = null;
			return true;
		}
	}
	public class Spawner
	{
		private readonly ModConfig _config;

		private readonly Random _random = new Random();

		public Spawner(ModConfig config)
		{
			_config = config;
		}

		public CommandResult SpawnMob(string mob, int amount, int level, string viewerName)
		{
			if (!TryGetContext(out var player, out var error))
			{
				return CommandResult.Fail(error);
			}
			if (!PrefabCatalog.Mobs.TryGetValue(mob, out var value))
			{
				return CommandResult.Fail("Unknown mob '" + mob + "'. Available mobs: " + string.Join(", ", PrefabCatalog.Mobs.Keys) + ".");
			}
			return SpawnCreatures(player, value, amount, level, varyLevel: true, viewerName);
		}

		public CommandResult SpawnEnemy(string enemy, int amount, int level, string viewerName)
		{
			if (!TryGetContext(out var player, out var error))
			{
				return CommandResult.Fail(error);
			}
			if (!PrefabCatalog.TryResolveEnemy(enemy, out var canonical))
			{
				return CommandResult.Fail("Unknown enemy '" + enemy + "'.");
			}
			return SpawnCreatures(player, new string[1] { canonical }, amount, level, varyLevel: false, viewerName);
		}

		public CommandResult SpawnItem(string item, int amount, ItemDeliveryMethod delivery)
		{
			if (!TryGetContext(out var player, out var error))
			{
				return CommandResult.Fail(error);
			}
			if (!PrefabCatalog.TryResolveItem(item, out var canonical))
			{
				return CommandResult.Fail("Unknown item '" + item + "'. Available items: " + string.Join(", ", PrefabCatalog.Items) + ".");
			}
			GameObject prefab = ZNetScene.instance.GetPrefab(canonical);
			if ((Object)(object)prefab == (Object)null)
			{
				return CommandResult.Fail("Item prefab '" + canonical + "' was not found in this world.");
			}
			if ((Object)(object)prefab.GetComponent<ItemDrop>() == (Object)null)
			{
				return CommandResult.Fail("'" + canonical + "' is not an item.");
			}
			if (delivery != ItemDeliveryMethod.Inventory)
			{
				return DropOnGround(player, prefab, canonical, amount);
			}
			return GiveToInventory(player, prefab, canonical, amount);
		}

		private CommandResult SpawnCreatures(Player player, string[] variantNames, int amount, int level, bool varyLevel, string viewerName)
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			List<GameObject> list = new List<GameObject>();
			List<string> list2 = new List<string>();
			foreach (string text in variantNames)
			{
				GameObject prefab = ZNetScene.instance.GetPrefab(text);
				if ((Object)(object)prefab != (Object)null)
				{
					list.Add(prefab);
				}
				else
				{
					list2.Add(text);
				}
			}
			if (list.Count == 0)
			{
				return CommandResult.Fail("No spawnable prefab found (" + string.Join(", ", list2) + ").");
			}
			for (int j = 0; j < amount; j++)
			{
				GameObject obj = list[_random.Next(list.Count)];
				int num = (varyLevel ? RollLevel(level) : level);
				GameObject val = Object.Instantiate<GameObject>(obj, FindSpawnPosition(player), Quaternion.identity);
				if (num > 1)
				{
					Character component = val.GetComponent<Character>();
					if ((Object)(object)component != (Object)null)
					{
						component.SetLevel(num);
					}
				}
				if (!string.IsNullOrEmpty(viewerName))
				{
					SetViewerName(val, viewerName);
				}
			}
			if (list2.Count > 0)
			{
				return CommandResult.Ok(string.Format("Spawned {0} creatures; skipped missing prefabs: {1}.", amount, string.Join(", ", list2)));
			}
			return CommandResult.Ok($"Spawned {amount} creatures.");
		}

		private static void SetViewerName(GameObject spawned, string viewerName)
		{
			ZNetView component = spawned.GetComponent<ZNetView>();
			Character component2 = spawned.GetComponent<Character>();
			if (!((Object)(object)component == (Object)null) && component.GetZDO() != null && !((Object)(object)component2 == (Object)null))
			{
				string hoverName = component2.GetHoverName();
				component.GetZDO().Set(ZDOVars.s_overrideHoverName, viewerName + "'s " + hoverName);
			}
		}

		private int RollLevel(int maxLevel)
		{
			if (maxLevel <= 1)
			{
				return 1;
			}
			int num = _random.Next(10);
			if (maxLevel == 2)
			{
				if (num >= 7)
				{
					return 2;
				}
				return 1;
			}
			if (num >= 5)
			{
				if (num >= 8)
				{
					return Math.Min(3, maxLevel);
				}
				return 2;
			}
			return 1;
		}

		private CommandResult GiveToInventory(Player player, GameObject prefab, string item, int amount)
		{
			Inventory inventory = ((Humanoid)player).GetInventory();
			int maxStack = GetMaxStack(prefab);
			int i;
			int num;
			for (i = 0; i < amount; i += num)
			{
				num = Mathf.Min(maxStack, amount - i);
				if (!inventory.CanAddItem(prefab, num) || !inventory.AddItem(prefab, num))
				{
					break;
				}
			}
			if (i == 0)
			{
				return CommandResult.Fail("Inventory is full; could not give any " + item + ".");
			}
			if (i < amount)
			{
				return CommandResult.Ok($"Gave {i}/{amount} {item}; inventory is full.");
			}
			return CommandResult.Ok($"Gave {i} {item}.");
		}

		private CommandResult DropOnGround(Player player, GameObject prefab, string item, int amount)
		{
			//IL_0019: 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)
			int maxStack = GetMaxStack(prefab);
			int i;
			int num;
			for (i = 0; i < amount; i += num)
			{
				num = Mathf.Min(maxStack, amount - i);
				ItemDrop component = Object.Instantiate<GameObject>(prefab, FindSpawnPosition(player), Quaternion.identity).GetComponent<ItemDrop>();
				if ((Object)(object)component != (Object)null)
				{
					component.SetStack(num);
				}
			}
			return CommandResult.Ok($"Dropped {i} {item} near the player.");
		}

		private Vector3 FindSpawnPosition(Player player)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: 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_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = ((Component)player).transform.position;
			float num = (float)(_random.NextDouble() * Math.PI * 2.0);
			float num2 = (float)_config.SpawnDistance.Value * (0.75f + (float)_random.NextDouble() * 0.5f);
			Vector3 val = position + new Vector3(Mathf.Cos(num), 0f, Mathf.Sin(num)) * num2;
			val.y = ZoneSystem.instance.GetGroundHeight(val);
			return val;
		}

		private static int GetMaxStack(GameObject prefab)
		{
			ItemDrop component = prefab.GetComponent<ItemDrop>();
			if ((Object)(object)component == (Object)null)
			{
				return 1;
			}
			int num = component.m_itemData?.m_shared?.m_maxStackSize ?? 1;
			if (num >= 1)
			{
				return num;
			}
			return 1;
		}

		private bool TryGetContext(out Player player, out string error)
		{
			player = null;
			if (!_config.SpawningEnabled.Value)
			{
				error = "Spawning is disabled in the configuration.";
				return false;
			}
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				error = "Spawning is only allowed on the host/server; this client cannot spawn world entities.";
				return false;
			}
			if ((Object)(object)ZNetScene.instance == (Object)null)
			{
				error = "No world is loaded.";
				return false;
			}
			player = Player.m_localPlayer;
			if ((Object)(object)player == (Object)null)
			{
				error = "No local player yet.";
				return false;
			}
			error = null;
			return true;
		}
	}
}
namespace ValheimTwitch.Portraits
{
	public class PortraitManager
	{
		private class Entry
		{
			public string Name;

			public string Url;
		}

		public class PortraitData
		{
			public string Name { get; set; }

			public string Url { get; set; }
		}

		private const int MaxImageBytes = 4194304;

		private const string HammerPrefabName = "Hammer";

		private static PortraitManager _instance;

		private readonly ModConfig _config;

		private readonly List<Entry> _roster = new List<Entry>();

		private readonly Dictionary<string, Texture2D> _texturesByUrl = new Dictionary<string, Texture2D>();

		private readonly Dictionary<string, List<Action<Texture2D>>> _pendingByUrl = new Dictionary<string, List<Action<Texture2D>>>();

		private readonly List<string> _downloadsInFlight = new List<string>();

		private FieldInfo _namedPrefabsField;

		private FieldInfo _knownRecipesField;

		private MethodInfo _updateAvailablePiecesMethod;

		private FieldInfo _noPlacementCostField;

		internal static PortraitManager Instance => _instance;

		private string StorePath => Path.Combine(Paths.ConfigPath, "CodeWithTD.ValheimTwitch.portraits.json");

		private FieldInfo NamedPrefabsField => _namedPrefabsField ?? (_namedPrefabsField = typeof(ZNetScene).GetField("m_namedPrefabs", BindingFlags.Instance | BindingFlags.NonPublic));

		private FieldInfo KnownRecipesField => _knownRecipesField ?? (_knownRecipesField = typeof(Player).GetField("m_knownRecipes", BindingFlags.Instance | BindingFlags.NonPublic));

		private MethodInfo UpdateAvailablePiecesMethod => _updateAvailablePiecesMethod ?? (_updateAvailablePiecesMethod = typeof(Player).GetMethod("UpdateAvailablePiecesList", BindingFlags.Instance | BindingFlags.NonPublic));

		private FieldInfo NoPlacementCostField => _noPlacementCostField ?? (_noPlacementCostField = typeof(Player).GetField("m_noPlacementCost", BindingFlags.Instance | BindingFlags.NonPublic));

		public PortraitManager(ModConfig config)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			_config = config;
			_instance = this;
			LoadFile();
			if (_config.PortraitsEnabled.Value)
			{
				new Harmony("CodeWithTD.ValheimTwitch.portraits").PatchAll(typeof(PortraitPatches));
			}
		}

		public CommandResult Register(string viewerName, string url)
		{
			if (!_config.PortraitsEnabled.Value)
			{
				return CommandResult.Fail("Portraits are disabled in the configuration.");
			}
			Entry entry = FindEntry(viewerName);
			if (entry != null && entry.Url == url)
			{
				RequestTexture(url, null);
				return CommandResult.Ok("'" + viewerName + "' is already in the portrait viewer list.");
			}
			if (entry == null)
			{
				if (_config.MaxPortraits.Value <= 0)
				{
					return CommandResult.Fail("[Portraits] MaxPortraits is set to 0; no viewers can be registered.");
				}
				while (_roster.Count >= _config.MaxPortraits.Value)
				{
					_roster.RemoveAt(0);
				}
				_roster.Add(new Entry
				{
					Name = viewerName,
					Url = url
				});
			}
			else
			{
				entry.Name = viewerName;
				entry.Url = url;
			}
			SaveFile();
			RequestTexture(url, null);
			return CommandResult.Ok($"'{viewerName}' added to the portrait viewer list ({_roster.Count}/{_config.MaxPortraits.Value}). " + "Place a 'VT Portrait' piece and press E on it to select the viewer.");
		}

		public CommandResult Remove(string viewerName)
		{
			if (!_config.PortraitsEnabled.Value)
			{
				return CommandResult.Fail("Portraits are disabled in the configuration.");
			}
			Entry entry = FindEntry(viewerName);
			if (entry == null)
			{
				List<string> list = new List<string>();
				foreach (Entry item in _roster)
				{
					list.Add(item.Name);
				}
				return CommandResult.Fail("No viewer '" + viewerName + "' in the portrait list. Registered viewers: " + string.Join(", ", list) + ".");
			}
			_roster.Remove(entry);
			SaveFile();
			return CommandResult.Ok("'" + viewerName + "' removed from the portrait viewer list. Portraits already showing them keep doing so until you reassign or remove them.");
		}

		internal List<PortraitData> GetRoster()
		{
			List<PortraitData> list = new List<PortraitData>();
			foreach (Entry item in _roster)
			{
				list.Add(new PortraitData
				{
					Name = item.Name,
					Url = item.Url
				});
			}
			return list;
		}

		internal void RequestTexture(string url, Action<Texture2D> callback)
		{
			if (string.IsNullOrEmpty(url))
			{
				callback?.Invoke(null);
				return;
			}
			if (_texturesByUrl.TryGetValue(url, out var value))
			{
				callback?.Invoke(value);
				return;
			}
			if (callback != null)
			{
				if (!_pendingByUrl.TryGetValue(url, out var value2))
				{
					value2 = new List<Action<Texture2D>>();
					_pendingByUrl[url] = value2;
				}
				value2.Add(callback);
			}
			StartDownload(url);
		}

		private void StartDownload(string url)
		{
			if (_downloadsInFlight.Contains(url))
			{
				return;
			}
			_downloadsInFlight.Add(url);
			ThreadPool.QueueUserWorkItem(delegate
			{
				try
				{
					using WebClient webClient = new WebClient();
					byte[] bytes = webClient.DownloadData(url);
					MainThreadDispatcher.Enqueue(delegate
					{
						OnDownloaded(url, bytes);
					});
				}
				catch (Exception ex)
				{
					Exception ex2 = ex;
					Exception e = ex2;
					MainThreadDispatcher.Enqueue(delegate
					{
						OnDownloadFailed(url, e.Message);
					});
				}
			});
		}

		private void OnDownloaded(string url, byte[] bytes)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			_downloadsInFlight.Remove(url);
			if (bytes == null || bytes.Length == 0 || bytes.Length > 4194304)
			{
				ValheimTwitchPlugin.Log.LogWarning((object)$"Portrait image from '{url}' rejected (empty or over {4194304} bytes).");
				Dispatch(url, null);
				return;
			}
			Texture2D val = new Texture2D(2, 2);
			if (!ImageConversion.LoadImage(val, bytes))
			{
				ValheimTwitchPlugin.Log.LogWarning((object)("Portrait image from '" + url + "' is not a valid PNG/JPEG; keeping the placeholder."));
				Object.Destroy((Object)(object)val);
				Dispatch(url, null);
			}
			else
			{
				_texturesByUrl[url] = val;
				ValheimTwitchPlugin.Log.LogInfo((object)$"[Portraits] Avatar downloaded from '{url}' ({((Texture)val).width}x{((Texture)val).height}).");
				Dispatch(url, val);
			}
		}

		private void OnDownloadFailed(string url, string message)
		{
			_downloadsInFlight.Remove(url);
			ValheimTwitchPlugin.Log.LogWarning((object)("[Portraits] Avatar download from '" + url + "' failed: " + message));
			Dispatch(url, null);
		}

		private void Dispatch(string url, Texture2D texture)
		{
			if (!_pendingByUrl.TryGetValue(url, out var value))
			{
				return;
			}
			_pendingByUrl.Remove(url);
			foreach (Action<Texture2D> item in value)
			{
				item(texture);
			}
		}

		internal static void OnZNetSceneAwakePrefix(ZNetScene scene)
		{
			if (_instance != null && _instance._config.PortraitsEnabled.Value)
			{
				_instance.RegisterPieceForSceneLoad(scene);
			}
		}

		private void RegisterPieceForSceneLoad(ZNetScene scene)
		{
			GameObject val = PortraitPrefab.EnsurePrefab(scene);
			if (!scene.m_prefabs.Contains(val))
			{
				scene.m_prefabs.Add(val);
			}
			PieceTable val2 = FindHammerTable(scene);
			if ((Object)(object)val2 != (Object)null && !val2.m_pieces.Contains(val))
			{
				val2.m_pieces.Add(val);
			}
			PortraitPrefab.ApplyMaterials(scene);
			ApplyBuildCost(scene, val);
			ValheimTwitchPlugin.Log.LogInfo((object)"[Portraits] 'VT Portrait' prefab registered for this world.");
		}

		private void ApplyBuildCost(ZNetScene scene, GameObject prefab)
		{
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Expected O, but got Unknown
			Piece component = prefab.GetComponent<Piece>();
			if ((Object)(object)component == (Object)null)
			{
				return;
			}
			List<Requirement> list = new List<Requirement>();
			string[] array = (_config.PortraitsCost.Value ?? "").Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length == 0)
				{
					continue;
				}
				string text2 = text;
				int result = 1;
				int num = text.LastIndexOf(':');
				if (num < 0)
				{
					num = text.LastIndexOf('=');
				}
				if (num >= 0)
				{
					text2 = text.Substring(0, num).Trim();
					if (!int.TryParse(text.Substring(num + 1).Trim(), out result))
					{
						result = -1;
					}
				}
				if (text2.Length != 0 && result > 0)
				{
					ItemDrop val = FindItemDrop(scene, text2);
					if ((Object)(object)val == (Object)null)
					{
						ValheimTwitchPlugin.Log.LogWarning((object)("[Portraits] Cost item '" + text2 + "' is not a known item prefab; skipped."));
						continue;
					}
					list.Add(new Requirement
					{
						m_resItem = val,
						m_amount = result,
						m_amountPerLevel = 0,
						m_recover = true
					});
				}
			}
			component.m_resources = list.ToArray();
			ValheimTwitchPlugin.Log.LogInfo((object)("[Portraits] VT Portrait build cost: " + DescribeCost(list) + "."));
		}

		private static ItemDrop FindItemDrop(ZNetScene scene, string name)
		{
			foreach (GameObject prefab in scene.m_prefabs)
			{
				if (((Object)prefab).name == name)
				{
					ItemDrop component = prefab.GetComponent<ItemDrop>();
					if ((Object)(object)component != (Object)null)
					{
						return component;
					}
				}
			}
			return null;
		}

		private static string DescribeCost(List<Requirement> requirements)
		{
			if (requirements.Count == 0)
			{
				return "free";
			}
			List<string> list = new List<string>();
			foreach (Requirement requirement in requirements)
			{
				list.Add(requirement.m_amount + "x " + ((Object)requirement.m_resItem).name);
			}
			return string.Join(", ", list);
		}

		internal static void OnUpdateKnownRecipesListPostfix(Player player)
		{
			if (_instance != null && _instance._config.PortraitsEnabled.Value)
			{
				_instance.EnsurePieceAvailable(player);
			}
		}

		private void EnsurePieceAvailable(Player player)
		{
			ZNetScene instance = ZNetScene.instance;
			if (!((Object)(object)instance == (Object)null))
			{
				GameObject val = PortraitPrefab.EnsurePrefab(instance);
				if (!instance.m_prefabs.Contains(val))
				{
					instance.m_prefabs.Add(val);
				}
				Dictionary<int, GameObject> dictionary = (Dictionary<int, GameObject>)NamedPrefabsField.GetValue(instance);
				if (dictionary != null)
				{
					dictionary[StringExtensionMethods.GetStableHashCode(((Object)val).name)] = val;
				}
				PieceTable val2 = FindHammerTable(instance);
				if ((Object)(object)val2 != (Object)null && !val2.m_pieces.Contains(val))
				{
					val2.m_pieces.Add(val);
				}
				HashSet<string> hashSet = (HashSet<string>)KnownRecipesField.GetValue(player);
				if (hashSet != null && hashSet.Add("VT Portrait"))
				{
					UpdateAvailablePiecesMethod?.Invoke(player, null);
					ValheimTwitchPlugin.Log.LogInfo((object)("[Portraits] 'VT Portrait' is now known and available in the hammer's furniture menu " + $"(hammer table found: {(Object)(object)val2 != (Object)null})."));
				}
			}
		}

		internal static bool OnPlacePiecePrefix(Player player, Piece piece, Vector3 pos, Quaternion rot)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: 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_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)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			if (_instance == null || (Object)(object)piece == (Object)null)
			{
				return true;
			}
			if ((Object)(object)((Component)piece).GetComponent<Portrait>() == (Object)null)
			{
				return true;
			}
			if (!_instance._config.PortraitsEnabled.Value)
			{
				ValheimTwitchPlugin.Log.LogWarning((object)"[Portraits] Placement skipped: portraits are disabled in the config.");
				return false;
			}
			GameObject val = Object.Instantiate<GameObject>(((Component)piece).gameObject, pos, rot);
			val.SetActive(true);
			Piece component = val.GetComponent<Piece>();
			component.SetCreator(player.GetPlayerID(), ((IUser)PlatformManager.DistributionPlatform.LocalUser).PlatformUserID);
			EffectList placeEffect = component.m_placeEffect;
			if (placeEffect != null)
			{
				placeEffect.Create(pos, rot, val.transform, 1f, -1, ((Character)player).GetZDOID());
			}
			_instance.ConsumeBuildCost(player, component);
			ZNetView component2 = val.GetComponent<ZNetView>();
			ValheimTwitchPlugin.Log.LogInfo((object)($"[Portraits] Placed a blank portrait at {val.transform.position:F1} " + $"(active={val.activeSelf}, networked={(Object)(object)component2 != (Object)null && component2.IsValid()}). Press E on it to pick a viewer."));
			return false;
		}

		private void ConsumeBuildCost(Player player, Piece placedPiece)
		{
			if (placedPiece.m_resources != null && placedPiece.m_resources.Length != 0 && !NoPlacementCost(player))
			{
				player.ConsumeResources(placedPiece.m_resources, 0, -1, 1);
			}
		}

		internal static void OnCreateObjectPostfix(ZDO zdo, GameObject result)
		{
			if (_instance == null || (Object)(object)result == (Object)null || result.activeSelf || (Object)(object)result.GetComponent<Portrait>() == (Object)null)
			{
				return;
			}
			ZNetView.m_useInitZDO = true;
			ZNetView.m_initZDO = zdo;
			try
			{
				result.SetActive(true);
			}
			finally
			{
				ZNetView.m_initZDO = null;
				ZNetView.m_useInitZDO = false;
			}
		}

		internal static void OnSetupPlacementGhostPostfix(Player player)
		{
			if (_instance == null)
			{
				return;
			}
			GameObject prefab = PortraitPrefab.Prefab;
			Portrait[] array = Resources.FindObjectsOfTypeAll<Portrait>();
			for (int i = 0; i < array.Length; i++)
			{
				GameObject gameObject = ((Component)array[i]).gameObject;
				if (!((Object)(object)gameObject == (Object)null) && !gameObject.activeSelf && (!((Object)(object)prefab != (Object)null) || !((Object)(object)gameObject == (Object)(object)prefab)))
				{
					ZNetView.m_forceDisableInit = true;
					try
					{
						gameObject.SetActive(true);
					}
					finally
					{
						ZNetView.m_forceDisableInit = false;
					}
					ValheimTwitchPlugin.Log.LogInfo((object)"[Portraits] Placement ghost activated.");
				}
			}
		}

		internal static void OnTakeInputPostfix(ref bool __result)
		{
			if (PortraitPicker.IsOpen)
			{
				__result = false;
			}
		}

		private static PieceTable FindHammerTable(ZNetScene scene)
		{
			foreach (GameObject prefab in scene.m_prefabs)
			{
				if (((Object)prefab).name == "Hammer")
				{
					return prefab.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_buildPieces;
				}
			}
			return null;
		}

		private void LoadFile()
		{
			try
			{
				if (!File.Exists(StorePath))
				{
					return;
				}
				List<PortraitData> list = JsonConvert.DeserializeObject<List<PortraitData>>(File.ReadAllText(StorePath));
				if (list == null)
				{
					return;
				}
				foreach (PortraitData item in list)
				{
					if (!string.IsNullOrEmpty(item?.Name) && !string.IsNullOrEmpty(item.Url))
					{
						_roster.Add(new Entry
						{
							Name = item.Name,
							Url = item.Url
						});
					}
				}
			}
			catch (Exception ex)
			{
				ValheimTwitchPlugin.Log.LogWarning((object)("Could not read the portrait list (" + StorePath + "): " + ex.Message));
			}
		}

		private void SaveFile()
		{
			try
			{
				List<PortraitData> list = new List<PortraitData>();
				foreach (Entry item in _roster)
				{
					list.Add(new PortraitData
					{
						Name = item.Name,
						Url = item.Url
					});
				}
				File.WriteAllText(StorePath, JsonConvert.SerializeObject((object)list, (Formatting)1));
			}
			catch (Exception ex)
			{
				ValheimTwitchPlugin.Log.LogWarning((object)("Could not save the portrait list (" + StorePath + "): " + ex.Message));
			}
		}

		private Entry FindEntry(string viewerName)
		{
			foreach (Entry item in _roster)
			{
				if (string.Equals(item.Name, viewerName, StringComparison.OrdinalIgnoreCase))
				{
					return item;
				}
			}
			return null;
		}

		private bool NoPlacementCost(Player player)
		{
			object value = NoPlacementCostField.GetValue(player);
			bool flag = default(bool);
			int num;
			if (value is bool)
			{
				flag = (bool)value;
				num = 1;
			}
			else
			{
				num = 0;
			}
			return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
		}
	}
	[HarmonyPatch]
	internal static class PortraitPatches
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		private static void ZNetSceneAwakePrefix(ZNetScene __instance)
		{
			PortraitManager.OnZNetSceneAwakePrefix(__instance);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Player), "PlacePiece")]
		private static bool PlacePiecePrefix(Player __instance, Piece piece, Vector3 pos, Quaternion rot)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return PortraitManager.OnPlacePiecePrefix(__instance, piece, pos, rot);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ZNetScene), "CreateObject")]
		private static void CreateObjectPostfix(ZDO zdo, GameObject __result)
		{
			PortraitManager.OnCreateObjectPostfix(zdo, __result);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Player), "SetupPlacementGhost")]
		private static void SetupPlacementGhostPostfix(Player __instance)
		{
			PortraitManager.OnSetupPlacementGhostPostfix(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Player), "TakeInput")]
		private static void TakeInputPostfix(ref bool __result)
		{
			PortraitManager.OnTakeInputPostfix(ref __result);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerController), "TakeInput")]
		private static void ControllerTakeInputPostfix(ref bool __result)
		{
			PortraitManager.OnTakeInputPostfix(ref __result);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Player), "UpdateKnownRecipesList")]
		private static void UpdateKnownRecipesListPostfix(Player __instance)
		{
			PortraitManager.OnUpdateKnownRecipesListPostfix(__instance);
		}
	}
	internal class PortraitPicker : MonoBehaviour
	{
		private const float CloseDistance = 12f;

		private const float PanelWidth = 500f;

		private const float PanelHeight = 520f;

		private const float RowHeight = 44f;

		private static PortraitPicker _instance;

		private Portrait _target;

		private GameObject _panel;

		private ScrollRect _scroll;

		private readonly List<GameObject> _rows = new List<GameObject>();

		internal static bool IsOpen
		{
			get
			{
				if ((Object)(object)_instance != (Object)null)
				{
					return (Object)(object)_instance._target != (Object)null;
				}
				return false;
			}
		}

		internal static PortraitPicker Instance
		{
			get
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Expected O, but got Unknown
				if ((Object)(object)_instance == (Object)null)
				{
					GameObject val = new GameObject("VTPortraitPicker");
					Object.DontDestroyOnLoad((Object)val);
					_instance = val.AddComponent<PortraitPicker>();
				}
				return _instance;
			}
		}

		internal void Open(Portrait target)
		{
			if (!GUIManager.IsHeadless())
			{
				_target = target;
				BuildIfNeeded();
				RebuildRows();
				_panel.SetActive(true);
				GUIManager.BlockInput(true);
				Cursor.visible = true;
				Cursor.lockState = (CursorLockMode)0;
			}
		}

		private void Close()
		{
			_target = null;
			if ((Object)(object)_panel != (Object)null)
			{
				_panel.SetActive(false);
			}
			GUIManager.BlockInput(false);
			Cursor.visible = false;
			Cursor.lockState = (CursorLockMode)1;
		}

		private void Update()
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_target == (Object)null)
			{
				return;
			}
			if ((Object)(object)_target == (Object)null || Input.GetKeyDown((KeyCode)27))
			{
				Close();
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || Vector3.Distance(((Component)localPlayer).transform.position, ((Component)_target).transform.position) > 12f)
			{
				Close();
			}
		}

		private void BuildIfNeeded()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: 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_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: 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_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: 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_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: 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)
			//IL_02f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0302: Unknown result type (might be due to invalid IL or missing references)
			//IL_0311: Unknown result type (might be due to invalid IL or missing references)
			//IL_0320: Unknown result type (might be due to invalid IL or missing references)
			//IL_033b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0345: Expected O, but got Unknown
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_036f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			//IL_0393: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f4: Expected O, but got Unknown
			//IL_040f: Unknown result type (might be due to invalid IL or missing references)
			//IL_041e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0423: Unknown result type (might be due to invalid IL or missing references)
			//IL_0430: Unknown result type (might be due to invalid IL or missing references)
			//IL_0436: Unknown result type (might be due to invalid IL or missing references)
			//IL_0461: Unknown result type (might be due to invalid IL or missing references)
			//IL_0470: Unknown result type (might be due to invalid IL or missing references)
			//IL_047f: Unknown result type (might be due to invalid IL or missing references)
			//IL_048e: Unknown result type (might be due to invalid IL or missing references)
			//IL_049d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_panel != (Object)null)
			{
				return;
			}
			GUIManager instance = GUIManager.Instance;
			Transform transform = GUIManager.CustomGUIFront.transform;
			_panel = instance.CreateWoodpanel(transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, 500f, 520f, false);
			((Object)_panel).name = "VTPortraitPickerPanel";
			_panel.AddComponent<CanvasGroup>();
			_panel.AddComponent<UIGroupHandler>().m_groupPriority = 10000;
			GameObject obj = instance.CreateText("VT Portrait", _panel.transform, new Vector2(0f, 0f), new Vector2(0f, 0f), Vector2.zero, instance.AveriaSerifBold, 30, instance.ValheimOrange, true, Color.black, 460f, 40f, false);
			obj.GetComponent<Text>().alignment = (TextAnchor)4;
			Place(obj, new Vector2(0f, 1f), new Vector2(1f, 1f), new Vector2(0.5f, 1f), new Vector2(20f, -70f), new Vector2(-20f, -30f));
			GameObject obj2 = instance.CreateText("Choose the viewer shown on this portrait", _panel.transform, new Vector2(0f, 0f), new Vector2(0f, 0f), Vector2.zero, instance.AveriaSerif, 16, Color.white, false, Color.black, 460f, 26f, false);
			obj2.GetComponent<Text>().alignment = (TextAnchor)4;
			Place(obj2, new Vector2(0f, 1f), new Vector2(1f, 1f), new Vector2(0.5f, 1f), new Vector2(20f, -100f), new Vector2(-20f, -74f));
			GameObject val = instance.CreateScrollView(_panel.transform, false, true, 10f, 6f, ColorBlock.defaultColorBlock, new Color(0f, 0f, 0f, 0.25f), 440f, 320f);
			Place(val, new Vector2(0f, 0f), new Vector2(1f, 1f), new Vector2(0.5f, 0.5f), new Vector2(30f, 92f), new Vector2(-30f, -112f));
			_scroll = val.GetComponentInChildren<ScrollRect>();
			GameObject obj3 = instance.CreateButton("Blank", _panel.transform, new Vector2(0f, 0f), new Vector2(0f, 0f), Vector2.zero, 120f, 46f);
			Place(obj3, new Vector2(1f, 0f), new Vector2(1f, 0f), new Vector2(1f, 0f), new Vector2(-270f, 30f), new Vector2(-150f, 76f));
			((UnityEvent)obj3.GetComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				if ((Object)(object)_target != (Object)null)
				{
					_target.AssignViewer("", "");
				}
				Close();
			});
			GameObject obj4 = instance.CreateButton("Close", _panel.transform, new Vector2(0f, 0f), new Vector2(0f, 0f), Vector2.zero, 120f, 46f);
			Place(obj4, new Vector2(1f, 0f), new Vector2(1f, 0f), new Vector2(1f, 0f), new Vector2(-140f, 30f), new Vector2(-20f, 76f));
			((UnityEvent)obj4.GetComponent<Button>().onClick).AddListener(new UnityAction(Close));
			GameObject obj5 = instance.CreateText("[Esc] Close", _panel.transform, new Vector2(0f, 0f), new Vector2(0f, 0f), Vector2.zero, instance.AveriaSerif, 14, Color.white, false, Color.black, 200f, 24f, false);
			obj5.GetComponent<Text>().alignment = (TextAnchor)3;
			Place(obj5, new Vector2(0f, 0f), new Vector2(0f, 0f), new Vector2(0f, 0f), new Vector2(24f, 24f), new Vector2(224f, 48f));
		}

		private static void Place(GameObject go, Vector2 anchorMin, Vector2 anchorMax, Vector2 pivot, Vector2 offsetMin, Vector2 offsetMax)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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)
			RectTransform component = go.GetComponent<RectTransform>();
			component.anchorMin = anchorMin;
			component.anchorMax = anchorMax;
			component.pivot = pivot;
			component.offsetMin = offsetMin;
			component.offsetMax = offsetMax;
			((Transform)component).localScale = Vector3.one;
		}

		private void RebuildRows()
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Expected O, but got Unknown
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c2: 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_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: 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_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Expected O, but got Unknown
			foreach (GameObject row in _rows)
			{
				Object.Destroy((Object)(object)row);
			}
			_rows.Clear();
			GUIManager instance = GUIManager.Instance;
			RectTransform content = _scroll.content;
			List<PortraitManager.PortraitData> list = PortraitManager.Instance?.GetRoster() ?? new List<PortraitManager.PortraitData>();
			VerticalLayoutGroup obj = ((Component)content).GetComponent<VerticalLayoutGroup>() ?? ((Component)content).gameObject.AddComponent<VerticalLayoutGroup>();
			((LayoutGroup)obj).childAlignment = (TextAnchor)1;
			((HorizontalOrVerticalLayoutGroup)obj).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj).childControlHeight = true;
			((HorizontalOrVerticalLayoutGroup)obj).childForceExpandWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj).childForceExpandHeight = false;
			((HorizontalOrVerticalLayoutGroup)obj).spacing = 6f;
			((LayoutGroup)obj).padding = new RectOffset(8, 8, 6, 6);
			ContentSizeFitter obj2 = ((Component)content).GetComponent<ContentSizeFitter>() ?? ((Component)content).gameObject.AddComponent<ContentSizeFitter>();
			obj2.verticalFit = (FitMode)2;
			obj2.horizontalFit = (FitMode)0;
			foreach (PortraitManager.PortraitData item in list)
			{
				string name = item.Name;
				string url = item.Url;
				string text = (((Object)(object)_target != (Object)null && name == _target.ViewerName) ? (name + "  (shown)") : name);
				GameObject val = instance.CreateButton(text, (Transform)(object)content, new Vector2(0f, 1f), new Vector2(1f, 1f), Vector2.zero, 410f, 38f);
				((Object)val).name = "VTPortraitRow_" + name;
				val.SetActive(true);
				LayoutElement obj3 = val.GetComponent<LayoutElement>() ?? val.AddComponent<LayoutElement>();
				obj3.minHeight = 38f;
				obj3.preferredHeight = 38f;
				((UnityEvent)val.GetComponent<Button>().onClick).AddListener((UnityAction)delegate
				{
					if ((Object)(object)_target != (Object)null)
					{
						_target.AssignViewer(name, url);
					}
					Close();
				});
				_rows.Add(val);
			}
			if (list.Count == 0)
			{
				GameObject gameObject = instance.CreateText("No viewers registered yet.\nSend a viewer_portrait command from Streamer.bot.", (Transform)(object)content, new Vector2(0f, 1f), new Vector2(1f, 1f), Vector2.zero, instance.AveriaSerif, 16, Color.white, false, Color.black, 380f, 60f, false).gameObject;
				_rows.Add(gameObject);
			}
			LayoutRebuilder.ForceRebuildLayoutImmediate(content);
			_scroll.verticalNormalizedPosition = 1f;
			ManualLogSource log = ValheimTwitchPlugin.Log;
			object arg = list.Count;
			Rect rect = content.rect;
			log.LogInfo((object)$"[Portraits] Picker list: {arg} viewer row(s), content height {((Rect)(ref rect)).height:F0}.");
		}
	}
	public class Portrait : MonoBehaviour, Hoverable, Interactable
	{
		public string ViewerName;

		public string Url;

		internal static readonly List<Portrait> Instances = new List<Portrait>();

		private ZNetView _nview;

		private float _nextZdoPoll;

		public bool Interact(Humanoid user, bool hold, bool alt)
		{
			if (hold || alt)
			{
				return false;
			}
			PortraitPicker.Instance.Open(this);
			return true;
		}

		public bool UseItem(Humanoid user, ItemData item)
		{
			return false;
		}

		public string GetHoverName()
		{
			return "VT Portrait";
		}

		public string GetHoverText()
		{
			string text = (string.IsNullOrEmpty(ViewerName) ? "no viewer selected" : ViewerName);
			return "VT Portrait\n" + text + "\n[<color=yellow><b>E</b></color>] Select viewer";
		}

		public float GetHoverOffset()
		{
			return 0f;
		}

		public void AssignViewer(string viewerName, string url)
		{
			if ((Object)(object)_nview == (Object)null)
			{
				_nview = ((Component)this).GetComponent<ZNetView>();
			}
			if (!((Object)(object)_nview == (Object)null) && _nview.IsValid())
			{
				_nview.ClaimOwnership();
				ZDO zDO = _nview.GetZDO();
				zDO.Set("HasFields", true);
				zDO.Set("HasFieldsPortrait", true);
				zDO.Set("Portrait.ViewerName", viewerName ?? "");
				zDO.Set("Portrait.Url", url ?? "");
				ViewerName = viewerName ?? "";
				Url = url ?? "";
				RefreshVisual();
			}
		}

		internal void RefreshVisual()
		{
			if (string.IsNullOrEmpty(Url))
			{
				ApplyTexture(null);
			}
			else
			{
				PortraitManager.Instance?.RequestTexture(Url, ApplyTexture);
			}
		}

		private void ApplyTexture(Texture2D texture)
		{
			Transform val = ((Component)this).transform.Find("image");
			MeshRenderer val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<MeshRenderer>() : null);
			if (!((Object)(object)val2 == (Object)null))
			{
				((Renderer)val2).material.mainTexture = (Texture)(object)(((Object)(object)texture != (Object)null) ? texture : PortraitPrefab.PlaceholderTexture());
			}
		}

		private void OnEnable()
		{
			Instances.Add(this);
		}

		private void OnDisable()
		{
			Instances.Remove(this);
		}

		private void Start()
		{
			_nview = ((Component)this).GetComponent<ZNetView>();
			RefreshVisual();
		}

		private void Update()
		{
			if (!(Time.time < _nextZdoPoll))
			{
				_nextZdoPoll = Time.time + 1f;
				PollZdo();
			}
		}

		private void PollZdo()
		{
			if ((Object)(object)_nview == (Object)null)
			{
				_nview = ((Component)this).GetComponent<ZNetView>();
			}
			ZNetView nview = _nview;
			ZDO val = ((nview != null) ? nview.GetZDO() : null);
			if (val != null)
			{
				string text = val.GetString("Portrait.ViewerName", "");
				string text2 = val.GetString("Portrait.Url", "");
				if (text != ViewerName || text2 != Url)
				{
					ViewerName = text;
					Url = text2;
					RefreshVisual();
				}
			}
		}
	}
	internal static class PortraitPrefab
	{
		public const string PrefabName = "VT_Portrait";

		internal const float PieceScale = 0.5f;

		internal const float PictureFill = 0.8f;

		private static GameObject _prefab;

		private static Texture2D _placeholder;

		private static Texture2D _tileTexture;

		private static Sprite _icon;

		internal static GameObject Prefab => _prefab;

		public static GameObject EnsurePrefab(ZNetScene scene)
		{
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Expected O, but got Unknown
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: 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_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: 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_01c4: 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_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Expected O, but got Unknown
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_prefab != (Object)null)
			{
				return _prefab;
			}
			GameObject val = FindWoodWallTemplate(scene);
			if ((Object)(object)val == (Object)null)
			{
				ValheimTwitchPlugin.Log.LogWarning((object)"[Portraits] No wood wall prefab found; building a plain fallback tile.");
				_prefab = CreateFallbackPrefab();
				return _prefab;
			}
			ZNetView.m_forceDisableInit = true;
			GameObject val2;
			try
			{
				val2 = Object.Instantiate<GameObject>(val);
			}
			finally
			{
				ZNetView.m_forceDisableInit = false;
			}
			((Object)val2).name = "VT_Portrait";
			Piece[] componentsInChildren = val2.GetComponentsInChildren<Piece>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Object.Destroy((Object)(object)componentsInChildren[i]);
			}
			WearNTear[] componentsInChildren2 = val2.GetComponentsInChildren<WearNTear>(true);
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				Object.Destroy((Object)(object)componentsInChildren2[i]);
			}
			foreach (Transform item in val2.transform)
			{
				Transform val3 = item;
				val3.localScale = new Vector3(val3.localScale.x, val3.localScale.y, val3.localScale.z * 0.5f);
			}
			Bounds val4 = MeasureBounds(val2.transform);
			GameObject obj = GameObject.CreatePrimitive((PrimitiveType)5);
			((Object)obj).name = "image";
			Object.Destroy((Object)(object)obj.GetComponent<Collider>());
			obj.transform.SetParent(val2.transform, false);
			obj.transform.localPosition = new Vector3(((Bounds)(ref val4)).center.x, ((Bounds)(ref val4)).center.y, ((Bounds)(ref val4)).min.z - 0.01f);
			obj.transform.localScale = new Vector3(((Bounds)(ref val4)).size.x * 0.8f, ((Bounds)(ref val4)).size.y * 0.8f, 1f);
			val2.transform.localScale = Vector3.one * 0.5f;
			Sprite val5 = val.GetComponent<Piece>()?.m_icon;
			Piece obj2 = val2.AddComponent<Piece>();
			obj2.m_name = "VT Portrait";
			obj2.m_description = "Twitch viewer portrait (ValheimTwitch). Place it, then press E on it to pick the viewer.";
			obj2.m_category = (PieceCategory)4;
			obj2.m_icon = (((Object)(object)val5 != (Object)null) ? val5 : IconSprite());
			obj2.m_placeEffect = new EffectList();
			obj2.m_canRotate = true;
			ZNetView obj3 = val2.AddComponent<ZNetView>();
			obj3.m_type = (ObjectType)0;
			obj3.m_persistent = true;
			Portrait portrait = val2.AddComponent<Portrait>();
			portrait.ViewerName = "";
			portrait.Url = "";
			val2.SetActive(false);
			SetLayer(val2);
			Object.DontDestroyOnLoad((Object)(object)val2);
			_prefab = val2;
			ValheimTwitchPlugin.Log.LogInfo((object)("[Portraits] Portrait piece cloned from '" + ((Object)val).name + "'."));
			return val2;
		}

		private static Bounds MeasureBounds(Transform root)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: 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_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: 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_00b9: 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_00c0: 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_00c3: 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_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(float.MaxValue, float.MaxValue, float.MaxValue);
			Vector3 val2 = default(Vector3);
			((Vector3)(ref val2))..ctor(float.MinValue, float.MinValue, float.MinValue);
			MeshRenderer[] componentsInChildren = ((Component)root).GetComponentsInChildren<MeshRenderer>(true);
			Vector3 val3 = default(Vector3);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Bounds bounds = ((Renderer)componentsInChildren[i]).bounds;
				for (int j = 0; j < 8; j++)
				{
					((Vector3)(ref val3))..ctor(((j & 1) == 0) ? ((Bounds)(ref bounds)).min.x : ((Bounds)(ref bounds)).max.x, ((j & 2) == 0) ? ((Bounds)(ref bounds)).min.y : ((Bounds)(ref bounds)).max.y, ((j & 4) == 0) ? ((Bounds)(ref bounds)).min.z : ((Bounds)(ref bounds)).max.z);
					Vector3 val4 = root.InverseTransformPoint(val3);
					val = Vector3.Min(val, val4);
					val2 = Vector3.Max(val2, val4);
				}
			}
			Bounds result = default(Bounds);
			((Bounds)(ref result)).SetMinMax(val, val2);
			ValheimTwitchPlugin.Log.LogInfo((object)$"[Portraits] Wall bounds (local): centre {((Bounds)(ref result)).center:F2}, size {((Bounds)(ref result)).size:F2}.");
			return result;
		}

		private static GameObject FindWoodWallTemplate(ZNetScene scene)
		{
			if ((Object)(object)scene == (Object)null)
			{
				return null;
			}
			string[] array = new string[4] { "wood_wall_1x1", "wood_wall_half", "wood_wall_1", "wood_wall" };
			foreach (string text in array)
			{
				GameObject prefab = scene.GetPrefab(text);
				if ((Object)(object)prefab != (Object)null)
				{
					return prefab;
				}
			}
			foreach (GameObject prefab2 in scene.m_prefabs)
			{
				if ((Object)(object)prefab2 != (Object)null && ((Object)prefab2).name.Contains("wood_wall"))
				{
					return prefab2;
				}
			}
			return null;
		}

		private static GameObject CreateFallbackPrefab()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("VT_Portrait");
			val.AddComponent<BoxCollider>().size = new Vector3(1f, 1f, 0.06f);
			GameObject obj = GameObject.CreatePrimitive((PrimitiveType)5);
			((Object)obj).name = "image";
			Object.Destroy((Object)(object)obj.GetComponent<Collider>());
			obj.transform.SetParent(val.transform, false);
			obj.transform.localScale = new Vector3(0.9f, 0.9f, 1f);
			Piece obj2 = val.AddComponent<Piece>();
			obj2.m_name = "VT Portrait";
			obj2.m_description = "Twitch viewer portrait (ValheimTwitch). Place it, then press E on it to pick the viewer.";
			obj2.m_category = (PieceCategory)4;
			obj2.m_icon = IconSprite();
			obj2.m_placeEffect = new EffectList();
			obj2.m_canRotate = true;
			ZNetView obj3 = val.AddComponent<ZNetView>();
			obj3.m_type = (ObjectType)0;
			obj3.m_persistent = true;
			val.AddComponent<Portrait>();
			val.SetActive(false);
			SetLayer(val);
			Object.DontDestroyOnLoad((Object)(object)val);
			return val;
		}

		internal static void ApplyMaterials(ZNetScene scene)
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Expected O, but got Unknown
			if ((Object)(object)_prefab == (Object)null)
			{
				return;
			}
			Transform val = _prefab.transform.Find("image");
			MeshRenderer val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<MeshRenderer>() : null);
			if ((Object)(object)val2 == (Object)null)
			{
				return;
			}
			GameObject val3 = FindWoodWallTemplate(scene);
			Material val4 = null;
			if ((Object)(object)val3 != (Object)null)
			{
				MeshRenderer[] componentsInChildren = val3.GetComponentsInChildren<MeshRenderer>(true);
				foreach (MeshRenderer val5 in componentsInChildren)
				{
					if ((Object)(object)((Renderer)val5).sharedMaterial != (Object)null && ((Renderer)val5).sharedMaterial.HasProperty("_MainTex"))
					{
						val4 = ((Renderer)val5).sharedMaterial;
						break;
					}
				}
			}
			if ((Object)(object)val4 == (Object)null)
			{
				ValheimTwitchPlugin.Log.LogWarning((object)"[Portraits] No wood wall material found; the picture may not render correctly.");
				return;
			}
			Material val6 = new Material(val4);
			ResetTiling(val6);
			val6.mainTexture = (Texture)(object)PlaceholderTexture();
			((Renderer)val2).sharedMaterial = val6;
			ValheimTwitchPlugin.Log.LogInfo((object)("[Portraits] Picture material cloned from the wood wall ('" + ((Object)val4).name + "', shader '" + ((Object)val4.shader).name + "')."));
		}

		private static void ResetTiling(Material material)
		{
			//IL_0006: 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_0047: Unknown result type (might be due to invalid IL or missing references)
			material.SetTextureScale("_MainTex", Vector2.one);
			material.SetTextureOffset("_MainTex", Vector2.zero);
			if (material.HasProperty("_MainTexSt"))
			{
				material.SetVector("_MainTexSt", new Vector4(1f, 1f, 0f, 0f));
			}
		}

		internal static Texture2D PlaceholderTexture()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			//IL_0026: 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_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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_placeholder == (Object)null)
			{
				_placeholder = new Texture2D(2, 2);
				_placeholder.SetPixels((Color[])(object)new Color[4]
				{
					Color.grey,
					Color.grey,
					Color.grey,
					Color.grey
				});
				_placeholder.Apply();
			}
			return _placeholder;
		}

		internal static Texture2D TileTexture()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			//IL_0077: 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_007c: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_tileTexture == (Object)null)
			{
				Texture2D val = new Texture2D(64, 64);
				Color[] array = (Color[])(object)new Color[4096];
				for (int i = 0; i < 64; i++)
				{
					for (int j = 0; j < 64; j++)
					{
						bool flag = j < 6 || j >= 58 || i < 6 || i >= 58;
						array[i * 64 + j] = (flag ? new Color(0.42f, 0.3f, 0.17f) : new Color(0.62f, 0.62f, 0.58f));
					}
				}
				val.SetPixels(array);
				val.Apply();
				_tileTexture = val;
			}
			return _tileTexture;
		}

		private static Sprite IconSprite()
		{
			//IL_002c: 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 ((Object)(object)_icon == (Object)null)
			{
				Texture2D val = TileTexture();
				_icon = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), (float)((Texture)val).width);
			}
			return _icon;
		}

		private static void SetLayer(GameObject go)
		{
			int num = LayerMask.NameToLayer("piece");
			if (num >= 0)
			{
				go.layer = num;
			}
		}
	}
}
namespace ValheimTwitch.Networking
{
	public static class MainThreadDispatcher
	{
		private static readonly ConcurrentQueue<Action> Actions = new ConcurrentQueue<Action>();

		private static ManualLogSource _log;

		public static void Init(ManualLogSource log)
		{
			_log = log;
		}

		public static void Enqueue(Action action)
		{
			if (action != null)
			{
				Actions.Enqueue(action);
			}
		}

		public static void InvokePending()
		{
			Action result;
			while (Actions.TryDequeue(out result))
			{
				try
				{
					result();
				}
				catch (Exception arg)
				{
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogError((object)$"MainThreadDispatcher: swallowed exception in queued action: {arg}");
					}
				}
			}
		}

		public static void Clear()
		{
			Action result;
			while (Actions.TryDequeue(out result))
			{
			}
		}
	}
	public class StreamerBotClient
	{
		private enum ClientState
		{
			Disconnected,
			Connecting,
			Connected,
			WaitingReconnect,
			Closed
		}

		private readonly ModConfig _config;

		private readonly Queue<string> _sendQueue = new Queue<string>();

		private readonly object _sendLock = new object();

		private readonly Random _idRandom = new Random();

		private WebSocket _ws;

		private ClientState _state;

		private bool _closing;

		private bool _helloSeen;

		private bool _authenticated;

		private bool _subscribeSent;

		private bool _subscribed;

		private bool _authFailed;

		private string _authRequestId;

		private string _subscribeRequestId;

		private float _connectedAt;

		private float _reconnectAt;

		public bool IsConnected => _state == ClientState.Connected;

		public bool IsAuthenticated => _authenticated;

		public bool IsSubscribed => _subscribed;

		public event Action<StreamerBotEvent> EventReceived;

		public bool DoAction(string actionName, JObject args)
		{
			//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_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: 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_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(actionName))
			{
				return false;
			}
			if (_state != ClientState.Connected || !_subscribeSent)
			{
				return false;
			}
			QueueSend(((JToken)new JObject
			{
				["request"] = JToken.op_Implicit("DoAction"),
				["id"] = JToken.op_Implicit(NextId()),
				["action"] = (JToken)new JObject { ["name"] = JToken.op_Implicit(actionName) },
				["args"] = (JToken)(((object)args) ?? ((object)new JObject()))
			}).ToString((Formatting)0, Array.Empty<JsonConverter>()));
			return true;
		}

		public StreamerBotClient(ModConfig config)
		{
			_config = config;
		}

		public void Connect()
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			if (_state == ClientState.Connecting || _state == ClientState.Connected)
			{
				return;
			}
			_closing = false;
			_helloSeen = false;
			_authenticated = false;
			_subscribeSent = false;
			_subscribed = false;
			_authFailed = false;
			_authRequestId = null;
			_subscribeRequestId = null;
			string text = $"ws://{_config.WebSocketHost.Value}:{_config.WebSocketPort.Value}/";
			_ws = new WebSocket(text, Array.Empty<string>());
			_ws.OnOpen += delegate
			{
				MainThreadDispatcher.Enqueue(OnOpen);
			};
			_ws.OnMessage += delegate(object sender, MessageEventArgs args)
			{
				MainThreadDispatcher.Enqueue(delegate
				{
					OnMessage(args.IsText ? args.Data : Encoding.UTF8.GetString(args.RawData));
				});
			};
			_ws.OnClose += delegate(object sender, CloseEventArgs args)
			{
				MainThreadDispatcher.Enqueue(delegate
				{
					OnClosed(args.Code, args.Reason);
				});
			};
			_ws.OnError += delegate(object sender, ErrorEventArgs args)
			{
				MainThreadDispatcher.Enqueue(delegate
				{
					OnError(args.Message);
				});
			};
			_state = ClientState.Connecting;
			LogInfo($"Connecting to Streamer.bot at {_config.WebSocketHost.Value}:{_config.WebSocketPort.Value} ...");
			_ws.ConnectAsync();
		}

		public void Close()
		{
			if (_ws == null || _state == ClientState.Closed)
			{
				_state = ClientState.Closed;
				return;
			}
			_closing = true;
			_state = ClientState.Closed;
			try
			{
				_ws.CloseAsync((CloseStatusCode)1000, "ValheimTwitch shutdown");
			}
			catch (Exception ex)
			{
				LogWarn("Error while closing the WebSocket: " + ex.Message);
			}
			lock (_sendLock)
			{
				_sendQueue.Clear();
			}
			LogInfo("Disconnected from Streamer.bot (graceful shutdown).");
		}

		public void Tick()
		{
			DrainSendQueue();
			if (_state == ClientState.WaitingReconnect && Time.realtimeSinceStartup >= _reconnectAt)
			{
				Connect();
			}
			else if (_state == ClientState.Connected && !_helloSeen && !_subscribeSent && Time.realtimeSinceStartup - _connectedAt > 3f)
			{
				LogInfo("No Hello message received; assuming a legacy Streamer.bot server.");
				QueueSubscribe();
			}
		}

		private void OnOpen()
		{
			_state = ClientState.Connected;
			_connectedAt = Time.realtimeSinceStartup;
			LogInfo("WebSocket connection opened; waiting for Hello message...");
		}

		private void OnMessage(string raw)
		{
			if (_config.WebSocketDebugLogging.Value)
			{
				LogDebug("<- " + raw);
			}
			if (!StreamerBotEventParser.TryParse(raw, out var message))
			{
				LogWarn("Received a malformed or unrecognised message from Streamer.bot; ignoring it.");
			}
			else if (message.IsHello)
			{
				HandleHello(message.Hello);
			}
			else if (message.Response != null)
			{
				HandleResponse(message.Response);
			}
			else if (message.Event != null)
			{
				this.EventReceived?.Invoke(message.Event);
			}
		}

		private void HandleHello(StreamerBotHello hello)
		{
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: 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)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			_helloSeen = true;
			LogInfo("Connected to Streamer.bot instance '" + (hello.InstanceName ?? "unknown") + "' (version " + (hello.Version ?? "unknown") + ").");
			if (hello.Salt != null && hello.Challenge != null)
			{
				if (string.IsNullOrEmpty(_config.WebSocketPassword.Value))
				{
					LogWarn("Streamer.bot requires WebSocket authentication but no password is configured. Set [WebSocket] Password in BepInEx/config/CodeWithTD.ValheimTwitch.cfg.");
					QueueSubscribe();
					return;
				}
				_authRequestId = NextId();
				QueueSend(((JToken)new JObject
				{
					["request"] = JToken.op_Implicit("Authenticate"),
					["id"] = JToken.op_Implicit(_authRequestId),
					["authentication"] = JToken.op_Implicit(ComputeAuthentication(_config.WebSocketPassword.Value, hello.Salt, hello.Challenge))
				}).ToString((Formatting)0, Array.Empty<JsonConverter>()));
			}
			else
			{
				QueueSubscribe();
			}
		}

		private void HandleResponse(StreamerBotResponse response)
		{
			bool flag = string.Equals(response.Status, "ok", StringComparison.OrdinalIgnoreCase);
			if (response.Id == _authRequestId)
			{
				if (flag)
				{
					_authenticated = true;
					LogInfo("Authenticated with Streamer.bot.");
					QueueSubscribe();
				}
				else
				{
					_authFailed = true;
					LogError("Streamer.bot WebSocket authentication failed. Check [WebSocket] Password in BepInEx/config/CodeWithTD.ValheimTwitch.cfg.");
					Close();
				}
			}
			else if (response.Id == _subscribeRequestId)
			{
				if (flag)
				{
					_subscribed = true;
					LogInfo("Subscribed to Streamer.bot events (Twitch + General.Custom).");
				}
				else
				{
					LogError($"Subscribe request rejected by Streamer.bot: {response.Raw}");
				}
			}
			else if (!flag)
			{
				LogWarn($"Streamer.bot reported an error for request '{response.Id}': {response.Raw}");
			}
		}

		private void OnClosed(ushort code, string reason)
		{
			if (_closing || _authFailed)
			{
				_state = ClientState.Closed;
				return;
			}
			LogWarn($"WebSocket connection to Streamer.bot closed (code {code}" + (string.IsNullOrEmpty(reason) ? ")." : (": " + reason + ").")));
			if (_config.WebSocketAutoReconnect.Value)
			{
				_state = ClientState.WaitingReconnect;
				_reconnectAt = Time.realtimeSinceStartup + (float)_config.WebSocketReconnectDelay.Value;
				LogInfo($"Reconnecting in {_config.WebSocketReconnectDelay.Value} seconds...");
			}
			else
			{
				_state = ClientState.Closed;
			}
		}

		private void OnError(string message)
		{
			LogWarn("WebSocket error: " + message);
		}

		private void QueueSubscribe()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: 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_004d: 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_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			//IL_006d: 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_0082: Expected O, but got Unknown
			//IL_0087: Expected O, but got Unknown
			if (!_subscribeSent)
			{
				_subscribeSent = true;
				_subscribeRequestId = NextId();
				QueueSend(((JToken)new JObject
				{
					["request"] = JToken.op_Implicit("Subscribe"),
					["id"] = JToken.op_Implicit(_subscribeRequestId),
					["events"] = (JToken)new JObject
					{
						["Twitch"] = (JToken)new JArray((object)StreamerBotEventParser.SubscribedTwitchEvents),
						["General"] = (JToken)new JArray((object)"Custom")
					}
				}).ToString((Formatting)0, Array.Empty<JsonConverter>()));
			}
		}

		private void QueueSend(string json)
		{
			lock (_sendLock)
			{
				_sendQueue.Enqueue(json);
			}
		}

		private void DrainSendQueue()
		{
			lock (_sendLock)
			{
				while (_sendQueue.Count > 0)
				{
					string text = _sendQueue.Dequeue();
					if (_config.WebSocketDebugLogging.Value)
					{
						LogDebug($"-> (outgoing request, {text.Length} bytes)");
					}
					try
					{
						WebSocket ws = _ws;
						if (ws != null)
						{
							ws.Send(text);
						}
					}
					catch (Exception ex)
					{
						LogWarn("Failed to send WebSocket message: " + ex.Message);
					}
				}
			}
		}

		private string NextId()
		{
			return "vt-" + _idRandom.Next(100000, 999999);
		}

		private static string ComputeAuthentication(string password, string salt, string challenge)
		{
			using SHA256 sHA = new SHA256Managed();
			string text = Convert.ToBase64String(sHA.ComputeHash(Encoding.UTF8.GetBytes(password + salt)));
			return Convert.ToBase64String(sHA.ComputeHash(Encoding.UTF8.GetBytes(text + challenge)));
		}

		private void LogInfo(string message)
		{
			ValheimTwitchPlugin.Log.LogInfo((object)("[StreamerBot] " + message));
		}

		private void LogWarn(string message)
		{
			ValheimTwitchPlugin.Log.LogWarning((object)("[StreamerBot] " + message));
		}

		private void LogError(string message)
		{
			ValheimTwitchPlugin.Log.LogError((object)("[StreamerBot] " + message));
		}

		private void LogDebug(string message)
		{
			ValheimTwitchPlugin.Log.LogDebug((object)("[StreamerBot] " + message));
		}
	}
	public sealed class StreamerBotEvent
	{
		public string Source;

		public string Type;

		public JObject Data;

		public override string ToString()
		{
			return (Source ?? "Unknown") + "." + Type;
		}
	}
	public sealed class StreamerBotHello
	{
		public string InstanceName;

		public string Version;

		public string Salt;

		public string Challenge;
	}
	public sealed class StreamerBotResponse
	{
		public string Status;

		public string Id;

		public JObject Raw;
	}
	public sealed class ParsedStreamerBotMessage
	{
		public bool IsHello;

		public StreamerBotHello Hello;

		public StreamerBotResponse Response;

		public StreamerBotEvent Event;
	}
	public static class StreamerBotEventParser
	{
		public static readonly HashSet<string> SubscribedTwitchEvents = new HashSet<string> { "Follow", "Cheer", "Sub", "ReSub", "GiftSub", "GiftBomb", "Raid", "RewardRedemption" };

		public static bool TryParse(string raw, out ParsedStreamerBotMessage message)
		{
			message = null;
			if (string.IsNullOrEmpty(raw))
			{
				return false;
			}
			JObject obj;
			try
			{
				obj = JObject.Parse(raw);
			}
			catch
			{
				return false;
			}
			ParsedStreamerBotMessage parsedStreamerBotMessage = new ParsedStreamerBotMessage();
			if (TryParseHello(obj, out var hello))
			{
				parsedStreamerBotMessage.IsHello = true;
				parsedStreamerBotMessage.Hello = hello;
				message = parsedStreamerBotMessage;
				return true;
			}
			if (TryParseResponse(obj, out var response))
			{
				parsedStreamerBotMessage.Response = response;
				message = parsedStreamerBotMessage;
				return true;
			}
			if (TryParseEvent(obj, out var evt))
			{
				parsedStreamerBotMessage.Event = evt;
				message = parsedStreamerBotMessage;
				return true;
			}
			return false;
		}

		private static bool TryParseHello(JObject obj, out StreamerBotHello hello)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Invalid comparison between Unknown and I4
			hello = null;
			JToken val = obj["request"];
			if (val == null || (int)val.Type != 8 || Extensions.Value<string>((IEnumerable<JToken>)val) != "Hello")
			{
				return false;
			}
			JToken obj2 = obj["info"];
			JObject val2 = (JObject)(object)((obj2 is JObject) ? obj2 : null);
			JToken obj3 = obj["authentication"];
			JObject val3 = (JObject)(object)((obj3 is JObject) ? obj3 : null);
			hello = new StreamerBotHello
			{
				InstanceName = ((val2 != null) ? ((string)val2["name"]) : null),
				Version = ((val2 != null) ? ((string)val2["version"]) : null),
				Salt = ((val3 != null) ? ((string)val3["salt"]) : null),
				Challenge = ((val3 != null) ? ((string)val3["challenge"]) : null)
			};
			return true;
		}

		private static bool TryParseResponse(JObject obj, out StreamerBotResponse response)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Invalid comparison between Unknown and I4
			response = null;
			JToken val = obj["status"];
			if (val == null || (int)val.Type != 8)
			{
				return false;
			}
			response = new StreamerBotResponse
			{
				Status = Extensions.Value<string>((IEnumerable<JToken>)val),
				Id = (string)obj["id"],
				Raw = obj
			};
			return true;
		}

		private static bool TryParseEvent(JObject obj, out StreamerBotEvent evt)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Invalid comparison between Unknown and I4
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Invalid comparison between Unknown and I4
			evt = null;
			JToken val = obj["event"];
			if (val == null)
			{
				return false;
			}
			string text = null;
			string text2 = null;
			if ((int)val.Type == 1)
			{
				text = (string)val[(object)"source"];
				text2 = (string)val[(object)"type"];
			}
			else if ((int)val.Type == 8)
			{
				text2 = Extensions.Value<string>((IEnumerable<JToken>)val);
			}
			if (string.IsNullOrEmpty(text2))
			{
				return false;
			}
			if (string.IsNullOrEmpty(text) && SubscribedTwitchEvents.Contains(text2))
			{
				text = "Twitch";
			}
			evt = new StreamerBotEvent
			{
				Source = text,
				Type = text2,
				Data = (JObject)/*isinst with value type is only supported in some contexts*/
			};
			return true;
		}
	}
	public static class TwitchEventFormatter
	{
		public static bool TryFormatNotification(StreamerBotEvent evt, out string title, out string message)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			title = null;
			message = null;
			if (evt == null || string.IsNullOrEmpty(evt.Type))
			{
				return false;
			}
			JObject d = (JObject)(((object)evt.Data) ?? ((object)new JObject()));
			switch (evt.Type)
			{
			case "Raid":
				title = "RAID INCOMING!";
				message = Name(d) + " has raided with " + Viewers(d) + "!";
				return true;
			case "Follow":
				title = "New Follower!";
				message = Name(d) + " followed the channel!";
				return true;
			case "Sub":
				title = "New Subscriber!";
				message = Name(d) + " subscribed!";
				return true;
			case "ReSub":
				title = "Resubscription!";
				message = Name(d) + " resubscribed" + ForMonths(d) + "!";
				return true;
			case "GiftSub":
				title = "Gifted Sub!";
				message = Name(d) + " gifted a sub to " + Recipient(d) + "!";
				return true;
			case "GiftBomb":
				title = "Sub Bomb!";
				message = Name(d) + " gifted " + Amount(d, "gifts", "5") + " subs to the community!";
				return true;
			case "Cheer":
				title = "Cheer!";
				message = Name(d) + " cheered " + Amount(d, "bits", "0") + " bits!";
				return true;
			case "RewardRedemption":
				title = "Redemption!";
				message = Name(d) + " redeemed '" + Reward(d) + "'!";
				return true;
			default:
				return false;
			}
		}

		private static string Name(JObject d)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Invalid comparison between Unknown and I4
			JToken val = d["user"] ?? d["userName"] ?? d["fromUser"];
			JObject val2 = (JObject)(object)((val is JObject) ? val : null);
			if (val2 != null)
			{
				string text = (string)(val2["name"] ?? val2["login"]);
				if (!string.IsNullOrEmpty(text))
				{
					return text;
				}
			}
			else
			{
				JValue val3 = (JValue)(object)((val is JValue) ? val : null);
				if (val3 != null && (int)((JToken)val3).Type == 8)
				{
					return (string)(JToken)(object)val3;
				}
			}
			return "Someone";
		}

		private static string Recipient(JObject d)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Invalid comparison between Unknown and I4
			JToken val = d["recipient"] ?? d["recipientUser"];
			JObject val2 = (JObject)(object)((val is JObject) ? val : null);
			if (val2 != null)
			{
				string text = (string)(val2["name"] ?? val2["login"]);
				if (!string.IsNullOrEmpty(text))
				{
					return text;
				}
			}
			else
			{
				JValue val3 = (JValue)(object)((val is JValue) ? val : null);
				if (val3 != null && (int)((JToken)val3).Type == 8)
				{
					return (string)(JToken)(object)val3;
				}
			}
			return "someone";
		}

		private static string Viewers(JObject d)
		{
			int num = Int(d, "viewers");
			return string.Format("{0} {1}", num, (num == 1) ? "viewer" : "viewers");
		}

		private static string Amount(JObject d, string primary, string fallback)
		{
			int result = Int(d, primary);
			if (result <= 0)
			{
				int.TryParse(fallback, out result);
			}
			return result.ToString();
		}

		private static string ForMonths(JObject d)
		{
			int num = Int(d, "months");
			if (num > 1)
			{
				return $" for {num} months";
			}
			int num2 = Int(d, "cumulativeMonths");
			if (num2 > 1)
			{
				return $" for {num2} months";
			}
			return "";
		}

		private static string Reward(JObject d)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Invalid comparison between Unknown and I4
			JToken obj = d["rewardTitle"];
			JValue val = (JValue)(object)((obj is JValue) ? obj : null);
			if (val != null && (int)((JToken)val).Type == 8)
			{
				return (string)(JToken)(object)val;
			}
			JToken obj2 = d["reward"];
			JObject val2 = (JObject)(object)((obj2 is JObject) ? obj2 : null);
			if (val2 != null)
			{
				string text = (string)(val2["title"] ?? val2["name"]);
				if (!string.IsNullOrEmpty(text))
				{
					return text;
				}
			}
			return "a channel point reward";
		}

		private static int Int(JObject d, string key)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Invalid comparison between Unknown and I4
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Invalid comparison between Unknown and I4
			JToken obj = d[key];
			JValue val = (JValue)(object)((obj is JValue) ? obj : null);
			if (val != null && ((int)((JToken)val).Type == 6 || (int)((JToken)val).Type == 7))
			{
				return (int)(JToken)(object)val;
			}
			return 0;
		}
	}
}
namespace ValheimTwitch.Configuration
{
	public enum ItemDeliveryMethod
	{
		Inventory,
		Ground
	}
	public class ModConfig
	{
		private const string SecWebSocket = "WebSocket";

		private const string SecNotifications = "Notifications";

		private const string SecSpawning = "Spawning";

		private const string SecRaids = "Raids";

		private const string SecRequests = "Requests";

		private const string SecPortraits = "Portraits";

		private const string SecDebug = "Debug";

		public ConfigEntry<bool> WebSocketEnabled { get; private set; }

		public ConfigEntry<string> WebSocketHost { get; private set; }

		public ConfigEntry<int> WebSocketPort { get; private set; }

		public ConfigEntry<string> WebSocketPassword { get; private set; }

		public ConfigEntry<bool> WebSocketAutoReconnect { get; private set; }

		public ConfigEntry<int> WebSocketReconnectDelay { get; private set; }

		public ConfigEntry<bool> WebSocketDebugLogging { get; private set; }

		public ConfigEntry<bool> NotificationsEnabled { get; private set; }

		public ConfigEntry<bool> SpawningEnabled { get; private set; }

		public ConfigEntry<int> MaxSpawnsPerCommand { get; private set; }

		public ConfigEntry<int> MaxItemsPerCommand { get; private set; }

		public ConfigEntry<int> SpawnDistance { get; private set; }

		public ConfigEntry<int> MaxLevel { get; private set; }

		public ConfigEntry<ItemDeliveryMethod> ItemDelivery { get; private set; }

		public ConfigEntry<bool> RaidsEnabled { get; private set; }

		public ConfigEntry<bool> RequestsEnabled { get; private set; }

		public ConfigEntry<string> RequestActionName { get; private set; }

		public ConfigEntry<bool> PortraitsEnabled { get; private set; }

		public ConfigEntry<int> MaxPortraits { get; private set; }

		public ConfigEntry<string> PortraitsCost { get; private set; }

		public ConfigEntry<bool> DebugEnabled { get; private set; }

		public bool DebugLogging
		{
			get
			{
				if (!DebugEnabled.Value)
				{
					return WebSocketDebugLogging.Value;
				}
				return true;
			}
		}

		public ModConfig(ConfigFile file)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: 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_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Expected O, but got Unknown
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Expected O, but got Unknown
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Expected O, but got Unknown
			BindWebSocket(file);
			NotificationsEnabled = file.Bind<bool>("Notifications", "Enabled", true, "Show on-screen notifications inside Valheim (local player only).");
			SpawningEnabled = file.Bind<bool>("Spawning", "Enabled", true, "Allow spawning commands (mob_spawn, enemy_spawn, item_spawn). Only ever executed with host/server authority.");
			MaxSpawnsPerCommand = file.Bind<int>("Spawning", "MaxSpawnsPerCommand", 10, new ConfigDescription("Upper limit of creatures a single command may spawn.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>()));
			MaxItemsPerCommand = file.Bind<int>("Spawning", "MaxItemsPerCommand", 100, new ConfigDescription("Upper limit of items a single command may give or drop.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 1000), Array.Empty<object>()));
			SpawnDistance = file.Bind<int>("Spawning", "SpawnDistance", 10, new ConfigDescription("Distance in meters from the player where entities and items are placed.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 50), Array.Empty<object>()));
			MaxLevel = file.Bind<int>("Spawning", "MaxLevel", 3, new ConfigDescription("Upper limit for the level of spawned enemies. Level 1 = normal, 2 = one star, 3 = two stars (vanilla maximum).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 8), Array.Empty<object>()));
			ItemDelivery = file.Bind<ItemDeliveryMethod>("Spawning", "ItemDelivery", ItemDeliveryMethod.Inventory, "Default item_spawn delivery when the payload does not specify one (Inventory or Ground).");
			RaidsEnabled = file.Bind<bool>("Raids", "Enabled", true, "Allow triggering native Valheim raid events (raid_start / raid_stop commands). Only ever executed with host/server authority; raids are shared world state, so every player sees them.");
			RequestsEnabled = file.Bind<bool>("Requests", "Enabled", true, "Enable the in-game /request chat command, which forwards item requests to Streamer.bot.");
			RequestActionName = file.Bind<string>("Requests", "ActionName", "ValheimItemRequest", "Name of the Streamer.bot action to run when a player uses /request. The action receives the item name, a full stack amount and the player name as arguments (%item%, %amount%, %player%).");
			PortraitsEnabled = file.Bind<bool>("Portraits", "Enabled", false, "Twitch viewer portraits as buildable pieces (viewer_portrait command). One blank 'VT Portrait' piece appears in the hammer's furniture menu; place it, press E on it and pick a registered viewer. The choice is stored on the piece and persists with the world.");
			MaxPortraits = file.Bind<int>("Portraits", "MaxPortraits", 10, new ConfigDescription("Maximum number of viewers kept in the portrait picker list (oldest is dropped when exceeded).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 50), Array.Empty<object>()));
			PortraitsCost = file.Bind<string>("Portraits", "Cost", "Wood:2, LeatherScraps:2, Raspberry:1, Mushroom:1, Blueberries:1", "Building cost of the VT Portrait piece: 'ItemPrefabName:Amount' pairs, comma sepa

BepInEx/plugins/ValheimTwitch/websocket-sharp.dll

Decompiled 21 hours ago
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.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.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;
using WebSocketSharp.Server;

[assembly: AssemblyProduct("websocket-sharp.dll")]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("sta.blockhead")]
[assembly: AssemblyTrademark("")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyTitle("websocket-sharp")]
[assembly: AssemblyDescription("A C# implementation of the WebSocket protocol client and server")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyVersion("1.0.2.59611")]
namespace WebSocketSharp
{
	public static class Ext
	{
		private const string _tspecials = "()<>@,;:\\\"/[]?={} \t";

		private static readonly byte[] _last;

		private static readonly int _retry;

		private static byte[] compress(this byte[] data)
		{
			if (data.LongLength == 0)
			{
				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 == 0)
			{
				return memoryStream;
			}
			stream.Position = 0L;
			using DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress, leaveOpen: true);
			CopyTo(stream, 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 == 0)
			{
				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 == 0)
			{
				return memoryStream;
			}
			stream.Position = 0L;
			using DeflateStream source = new DeflateStream(stream, CompressionMode.Decompress, leaveOpen: true);
			CopyTo(source, 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 string CheckIfAvailable(this ServerState state, bool ready, bool start, bool shutting)
		{
			return ((!ready && (state == ServerState.Ready || state == ServerState.Stop)) || (!start && state == ServerState.Start) || (!shutting && state == ServerState.ShuttingDown)) ? ("This operation isn't available in: " + state.ToString().ToLower()) : null;
		}

		internal static string CheckIfAvailable(this WebSocketState state, bool connecting, bool open, bool closing, bool closed)
		{
			return ((!connecting && state == WebSocketState.Connecting) || (!open && state == WebSocketState.Open) || (!closing && state == WebSocketState.Closing) || (!closed && state == WebSocketState.Closed)) ? ("This operation isn't available in: " + state.ToString().ToLower()) : null;
		}

		internal static string CheckIfValidProtocols(this string[] protocols)
		{
			return protocols.Contains((string protocol) => protocol == null || protocol.Length == 0 || !protocol.IsToken()) ? "Contains an invalid value." : (protocols.ContainsTwice() ? "Contains a value twice." : null);
		}

		internal static string CheckIfValidServicePath(this string path)
		{
			return (path == null || path.Length == 0) ? "'path' is null or empty." : ((path[0] != '/') ? "'path' isn't an absolute path." : ((path.IndexOfAny(new char[2] { '?', '#' }) > -1) ? "'path' includes either or both query and fragment components." : null));
		}

		internal static string CheckIfValidSessionID(this string id)
		{
			return (id == null || id.Length == 0) ? "'id' is null or empty." : null;
		}

		internal static string CheckIfValidWaitTime(this TimeSpan time)
		{
			return (time <= TimeSpan.Zero) ? "A wait time is zero or less." : null;
		}

		internal static bool CheckWaitTime(this TimeSpan time, out string message)
		{
			message = null;
			if (time <= TimeSpan.Zero)
			{
				message = "A wait time is zero or less.";
				return false;
			}
			return true;
		}

		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)
		{
			return (method == CompressionMethod.Deflate) ? data.compress() : data;
		}

		internal static Stream Compress(this Stream stream, CompressionMethod method)
		{
			return (method == CompressionMethod.Deflate) ? stream.compress() : stream;
		}

		internal static byte[] CompressToArray(this Stream stream, CompressionMethod method)
		{
			return (method == CompressionMethod.Deflate) ? stream.compressToArray() : stream.ToByteArray();
		}

		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;
			Func<int, bool> contains = null;
			contains = delegate(int idx)
			{
				if (idx < len - 1)
				{
					for (int i = idx + 1; i < len; i++)
					{
						if (values[i] == values[idx])
						{
							return true;
						}
					}
					return contains(++idx);
				}
				return false;
			};
			return contains(0);
		}

		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)
		{
			return (method == CompressionMethod.Deflate) ? data.decompress() : data;
		}

		internal static Stream Decompress(this Stream stream, CompressionMethod method)
		{
			return (method == CompressionMethod.Deflate) ? stream.decompress() : stream;
		}

		internal static byte[] DecompressToArray(this Stream stream, CompressionMethod method)
		{
			return (method == CompressionMethod.Deflate) ? stream.decompressToArray() : stream.ToByteArray();
		}

		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] { '?', '#' });
			return (num > 0) ? originalString.Substring(0, num) : originalString;
		}

		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);
			return (num > 0) ? nameAndValue.Substring(0, num).Trim() : null;
		}

		internal static string GetValue(this string nameAndValue, char separator)
		{
			int num = nameAndValue.IndexOf(separator);
			return (num > -1 && num < nameAndValue.Length - 1) ? nameAndValue.Substring(num + 1).Trim() : null;
		}

		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();
			return unquote ? text.Unquote() : text;
		}

		internal static TcpListenerWebSocketContext GetWebSocketContext(this TcpClient tcpClient, string protocol, bool secure, ServerSslConfiguration sslConfig, Logger logger)
		{
			return new TcpListenerWebSocketContext(tcpClient, protocol, secure, sslConfig, logger);
		}

		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)
		{
			return opcode > 7 && opcode < 16;
		}

		internal static bool IsControl(this Opcode opcode)
		{
			return (int)opcode >= 8;
		}

		internal static bool IsData(this byte opcode)
		{
			return opcode == 1 || opcode == 2;
		}

		internal static bool IsData(this Opcode opcode)
		{
			return opcode == Opcode.Text || opcode == Opcode.Binary;
		}

		internal static bool IsPortNumber(this int value)
		{
			return value > 0 && value < 65536;
		}

		internal static bool IsReserved(this ushort code)
		{
			return code == 1004 || code == 1005 || code == 1006 || code == 1015;
		}

		internal static bool IsReserved(this CloseStatusCode code)
		{
			return code == CloseStatusCode.Undefined || code == CloseStatusCode.NoStatus || code == CloseStatusCode.Abnormal || code == CloseStatusCode.TlsHandshakeFailure;
		}

		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 < ' ' && !Contains("\r\n\t", c))
				{
					return false;
				}
				switch (c)
				{
				case '\u007f':
					return false;
				case '\n':
					if (++i < length)
					{
						c = value[i];
						if (!Contains(" \t", c))
						{
							return false;
						}
					}
					break;
				}
			}
			return true;
		}

		internal static bool IsToken(this string value)
		{
			foreach (char c in value)
			{
				if (c < ' ' || c >= '\u007f' || 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)
					{
						break;
					}
					num += num2;
					length -= num2;
				}
			}
			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)
					{
						break;
					}
					memoryStream.Write(buffer, 0, num);
					length -= num;
				}
			}
			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)
						{
							retry++;
							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;
				}
			}
			return (num > 0) ? value.Substring(num) : value;
		}

		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;
			CopyTo(stream, 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 hostnameOrAddress)
		{
			if (IPAddress.TryParse(hostnameOrAddress, out IPAddress address))
			{
				return address;
			}
			try
			{
				return Dns.GetHostAddresses(hostnameOrAddress)[0];
			}
			catch
			{
				return null;
			}
		}

		internal static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
		{
			return new List<TSource>(source);
		}

		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 TrimEndSlash(this string value)
		{
			value = value.TrimEnd(new char[1] { '/' });
			return (value.Length > 0) ? value : "/";
		}

		internal static bool TryCreateWebSocketUri(this string uriString, out Uri result, out string message)
		{
			result = null;
			Uri uri = uriString.ToUri();
			if (uri == null)
			{
				message = "An invalid URI string: " + uriString;
				return false;
			}
			if (!uri.IsAbsoluteUri)
			{
				message = "Not an absolute URI: " + uriString;
				return false;
			}
			string scheme = uri.Scheme;
			if (!(scheme == "ws") && !(scheme == "wss"))
			{
				message = "The scheme part isn't 'ws' or 'wss': " + uriString;
				return false;
			}
			if (uri.Fragment.Length > 0)
			{
				message = "Includes the fragment component: " + uriString;
				return false;
			}
			int port = uri.Port;
			if (port == 0)
			{
				message = "The port part is zero: " + uriString;
				return false;
			}
			result = ((port != -1) ? uri : new Uri(string.Format("{0}://{1}:{2}{3}", scheme, uri.Host, (scheme == "ws") ? 80 : 443, uri.PathAndQuery)));
			message = string.Empty;
			return true;
		}

		internal static string Unquote(this string value)
		{
			int num = value.IndexOf('"');
			if (num < 0)
			{
				return value;
			}
			int num2 = value.LastIndexOf('"');
			int num3 = num2 - num - 1;
			return (num3 < 0) ? value : ((num3 == 0) ? string.Empty : value.Substring(num + 1, num3).Replace("\\\"", "\""));
		}

		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 source = new MemoryStream(bytes);
			CopyTo(source, 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)
		{
			return chars == null || chars.Length == 0 || (value != null && value.Length != 0 && value.IndexOfAny(chars) > -1);
		}

		public static bool Contains(this NameValueCollection collection, string name)
		{
			return collection != null && collection.Count > 0 && 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] { ',' });
			foreach (string text2 in array)
			{
				if (text2.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");
			return (headers != null && headers.Contains(name)) ? WebSocketSharp.Net.CookieCollection.Parse(headers[name], response) : new WebSocketSharp.Net.CookieCollection();
		}

		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)
		{
			return value > 999 && value < 5000;
		}

		public static bool IsEnclosedIn(this string value, char c)
		{
			return value != null && value.Length > 1 && value[0] == c && value[value.Length - 1] == c;
		}

		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;
				}
			}
			string hostName = Dns.GetHostName();
			IPAddress[] hostAddresses = Dns.GetHostAddresses(hostName);
			IPAddress[] array = hostAddresses;
			foreach (IPAddress obj in array)
			{
				if (address.Equals(obj))
				{
					return true;
				}
			}
			return false;
		}

		public static bool IsNullOrEmpty(this string value)
		{
			return value == null || value.Length == 0;
		}

		public static bool IsPredefinedScheme(this string value)
		{
			if (value == null || value.Length < 2)
			{
				return false;
			}
			char c = value[0];
			if (c == 'h')
			{
				return value == "http" || value == "https";
			}
			if (c == 'w')
			{
				return value == "ws" || value == "wss";
			}
			if (c == 'f')
			{
				return value == "file" || value == "ftp";
			}
			if (c == 'n')
			{
				c = value[1];
				return (c != 'e') ? (value == "nntp") : (value == "news" || value == "net.pipe" || value == "net.tcp");
			}
			return (c == 'g' && value == "gopher") || (c == 'm' && value == "mailto");
		}

		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");
			}
			return request.Headers.Contains("Upgrade", protocol) && request.Headers.Contains("Connection", "Upgrade");
		}

		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 longLength;
			if (array == null || (longLength = array.LongLength) == 0)
			{
				return new T[0];
			}
			if (startIndex < 0 || length <= 0 || startIndex + length > longLength)
			{
				return new T[0];
			}
			if (startIndex == 0 && length == longLength)
			{
				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);
			return ((object)typeFromHandle == typeof(bool)) ? ((T)(object)BitConverter.ToBoolean(value, 0)) : (((object)typeFromHandle == typeof(char)) ? ((T)(object)BitConverter.ToChar(value, 0)) : (((object)typeFromHandle == typeof(double)) ? ((T)(object)BitConverter.ToDouble(value, 0)) : (((object)typeFromHandle == typeof(short)) ? ((T)(object)BitConverter.ToInt16(value, 0)) : (((object)typeFromHandle == typeof(int)) ? ((T)(object)BitConverter.ToInt32(value, 0)) : (((object)typeFromHandle == typeof(long)) ? ((T)(object)BitConverter.ToInt64(value, 0)) : (((object)typeFromHandle == typeof(float)) ? ((T)(object)BitConverter.ToSingle(value, 0)) : (((object)typeFromHandle == typeof(ushort)) ? ((T)(object)BitConverter.ToUInt16(value, 0)) : (((object)typeFromHandle == typeof(uint)) ? ((T)(object)BitConverter.ToUInt32(value, 0)) : (((object)typeFromHandle == typeof(ulong)) ? ((T)(object)BitConverter.ToUInt64(value, 0)) : default(T))))))))));
		}

		public static byte[] ToByteArray<T>(this T value, ByteOrder order) where T : struct
		{
			Type typeFromHandle = typeof(T);
			byte[] array = (((object)typeFromHandle == typeof(bool)) ? BitConverter.GetBytes((bool)(object)value) : (((object)typeFromHandle == typeof(byte)) ? new byte[1] { (byte)(object)value } : (((object)typeFromHandle == typeof(char)) ? BitConverter.GetBytes((char)(object)value) : (((object)typeFromHandle == typeof(double)) ? BitConverter.GetBytes((double)(object)value) : (((object)typeFromHandle == typeof(short)) ? BitConverter.GetBytes((short)(object)value) : (((object)typeFromHandle == typeof(int)) ? BitConverter.GetBytes((int)(object)value) : (((object)typeFromHandle == typeof(long)) ? BitConverter.GetBytes((long)(object)value) : (((object)typeFromHandle == typeof(float)) ? BitConverter.GetBytes((float)(object)value) : (((object)typeFromHandle == typeof(ushort)) ? BitConverter.GetBytes((ushort)(object)value) : (((object)typeFromHandle == typeof(uint)) ? BitConverter.GetBytes((uint)(object)value) : (((object)typeFromHandle == typeof(ulong)) ? BitConverter.GetBytes((ulong)(object)value) : WebSocket.EmptyBytes)))))))))));
			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");
			}
			return (source.Length > 1 && !sourceOrder.IsHostOrder()) ? source.Reverse() : source;
		}

		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 uriString)
		{
			Uri.TryCreate(uriString, uriString.MaybeUri() ? UriKind.Absolute : UriKind.Relative, out Uri result);
			return result;
		}

		public static string UrlDecode(this string value)
		{
			return (value != null && value.Length > 0) ? HttpUtility.UrlDecode(value) : value;
		}

		public static string UrlEncode(this string value)
		{
			return (value != null && value.Length > 0) ? HttpUtility.UrlEncode(value) : 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 longLength = content.LongLength;
			if (longLength == 0)
			{
				response.Close();
				return;
			}
			response.ContentLength64 = longLength;
			Stream outputStream = response.OutputStream;
			if (longLength <= int.MaxValue)
			{
				outputStream.Write(content, 0, (int)longLength);
			}
			else
			{
				outputStream.WriteBytes(content, 1024);
			}
			outputStream.Close();
		}

		static Ext()
		{
			byte[] last = new byte[1];
			_last = last;
			_retry = 5;
		}
	}
	public class MessageEventArgs : EventArgs
	{
		private string _data;

		private bool _dataSet;

		private Opcode _opcode;

		private byte[] _rawData;

		public string Data
		{
			get
			{
				if (!_dataSet)
				{
					_data = ((_opcode != Opcode.Binary) ? _rawData.UTF8Decode() : BitConverter.ToString(_rawData));
					_dataSet = true;
				}
				return _data;
			}
		}

		public bool IsBinary => _opcode == Opcode.Binary;

		public bool IsPing => _opcode == Opcode.Ping;

		public bool IsText => _opcode == Opcode.Text;

		public byte[] RawData => _rawData;

		[Obsolete("This property will be removed. Use any of the Is properties instead.")]
		public Opcode Type => _opcode;

		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;
		}
	}
	public class CloseEventArgs : EventArgs
	{
		private bool _clean;

		private ushort _code;

		private PayloadData _payloadData;

		private string _reason;

		internal PayloadData PayloadData => _payloadData ?? (_payloadData = new PayloadData(_code.Append(_reason)));

		public ushort Code => _code;

		public string Reason => _reason ?? string.Empty;

		public bool WasClean
		{
			get
			{
				return _clean;
			}
			internal set
			{
				_clean = value;
			}
		}

		internal CloseEventArgs()
		{
			_code = 1005;
			_payloadData = PayloadData.Empty;
		}

		internal CloseEventArgs(ushort code)
		{
			_code = code;
		}

		internal CloseEventArgs(CloseStatusCode code)
			: this((ushort)code)
		{
		}

		internal CloseEventArgs(PayloadData payloadData)
		{
			_payloadData = payloadData;
			byte[] applicationData = payloadData.ApplicationData;
			int num = applicationData.Length;
			_code = (ushort)((num > 1) ? applicationData.SubArray(0, 2).ToUInt16(ByteOrder.Big) : 1005);
			_reason = ((num > 2) ? applicationData.SubArray(2, num - 2).UTF8Decode() : string.Empty);
		}

		internal CloseEventArgs(ushort code, string reason)
		{
			_code = code;
			_reason = reason;
		}

		internal CloseEventArgs(CloseStatusCode code, string reason)
			: this((ushort)code, reason)
		{
		}
	}
	public enum ByteOrder
	{
		Little,
		Big
	}
	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 class WebSocket : IDisposable
	{
		private const string _guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

		private const string _version = "13";

		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 AutoResetEvent _exitReceiving;

		private string _extensions;

		private bool _extensionsRequested;

		private object _forConn;

		private object _forMessageEventQueue;

		private object _forSend;

		private MemoryStream _fragmentsBuffer;

		private bool _fragmentsCompressed;

		private Opcode _fragmentsOpcode;

		private Func<WebSocketContext, string> _handshakeRequestChecker;

		private bool _ignoreExtensions;

		private bool _inContinuation;

		private volatile bool _inMessage;

		private volatile Logger _logger;

		private Action<MessageEventArgs> _message;

		private Queue<MessageEventArgs> _messageEventQueue;

		private uint _nonceCount;

		private string _origin;

		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 AutoResetEvent _receivePong;

		private bool _secure;

		private ClientSslConfiguration _sslConfig;

		private Stream _stream;

		private TcpClient _tcpClient;

		private Uri _uri;

		private TimeSpan _waitTime;

		internal static readonly byte[] EmptyBytes;

		internal static readonly 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 => _readyState == WebSocketState.Open || _readyState == WebSocketState.Closing;

		public CompressionMethod Compression
		{
			get
			{
				return _compression;
			}
			set
			{
				lock (_forConn)
				{
					if (!checkIfAvailable(client: true, server: false, connecting: true, open: false, closing: false, closed: true, out var text))
					{
						_logger.Error(text);
						error("An error has occurred in setting the compression.", null);
					}
					else
					{
						_compression = value;
					}
				}
			}
		}

		public IEnumerable<WebSocketSharp.Net.Cookie> Cookies
		{
			get
			{
				object syncRoot;
				object obj = (syncRoot = _cookies.SyncRoot);
				Monitor.Enter(syncRoot);
				try
				{
					foreach (WebSocketSharp.Net.Cookie cookie in _cookies)
					{
						yield return cookie;
					}
				}
				finally
				{
					Monitor.Exit(obj);
				}
			}
		}

		public WebSocketSharp.Net.NetworkCredential Credentials => _credentials;

		public bool EmitOnPing
		{
			get
			{
				return _emitOnPing;
			}
			set
			{
				_emitOnPing = value;
			}
		}

		public bool EnableRedirection
		{
			get
			{
				return _enableRedirection;
			}
			set
			{
				lock (_forConn)
				{
					if (!checkIfAvailable(client: true, server: false, connecting: true, open: false, closing: false, closed: true, out var text))
					{
						_logger.Error(text);
						error("An error has occurred in setting the enable redirection.", null);
					}
					else
					{
						_enableRedirection = value;
					}
				}
			}
		}

		public string Extensions => _extensions ?? string.Empty;

		public bool IsAlive => Ping();

		public bool IsSecure => _secure;

		public Logger Log
		{
			get
			{
				return _logger;
			}
			internal set
			{
				_logger = value;
			}
		}

		public string Origin
		{
			get
			{
				return _origin;
			}
			set
			{
				lock (_forConn)
				{
					Uri result;
					if (!checkIfAvailable(client: true, server: false, connecting: true, open: false, closing: false, closed: true, out var text))
					{
						_logger.Error(text);
						error("An error has occurred in setting the origin.", null);
					}
					else if (value.IsNullOrEmpty())
					{
						_origin = value;
					}
					else if (!Uri.TryCreate(value, UriKind.Absolute, out result) || result.Segments.Length > 1)
					{
						_logger.Error("The syntax of an origin must be '<scheme>://<host>[:<port>]'.");
						error("An error has occurred in setting the origin.", null);
					}
					else
					{
						_origin = value.TrimEnd(new char[1] { '/' });
					}
				}
			}
		}

		public string Protocol
		{
			get
			{
				return _protocol ?? string.Empty;
			}
			internal set
			{
				_protocol = value;
			}
		}

		public WebSocketState ReadyState => _readyState;

		public ClientSslConfiguration SslConfiguration
		{
			get
			{
				return _client ? (_sslConfig ?? (_sslConfig = new ClientSslConfiguration(_uri.DnsSafeHost))) : null;
			}
			set
			{
				lock (_forConn)
				{
					if (!checkIfAvailable(client: true, server: false, connecting: true, open: false, closing: false, closed: true, out var text))
					{
						_logger.Error(text);
						error("An error has occurred in setting the ssl configuration.", null);
					}
					else
					{
						_sslConfig = value;
					}
				}
			}
		}

		public Uri Url => _client ? _uri : _context.RequestUri;

		public TimeSpan WaitTime
		{
			get
			{
				return _waitTime;
			}
			set
			{
				lock (_forConn)
				{
					if (!checkIfAvailable(client: true, server: true, connecting: true, open: false, closing: false, closed: true, out var text) || !value.CheckWaitTime(out text))
					{
						_logger.Error(text);
						error("An error has occurred in setting the wait time.", null);
					}
					else
					{
						_waitTime = value;
					}
				}
			}
		}

		public event EventHandler<CloseEventArgs> OnClose;

		public event EventHandler<ErrorEventArgs> OnError;

		public event EventHandler<MessageEventArgs> OnMessage;

		public event EventHandler OnOpen;

		static WebSocket()
		{
			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)
			{
				text = protocols.CheckIfValidProtocols();
				if (text != null)
				{
					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 (_forConn)
			{
				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 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 isn't available in: connecting";
				return false;
			}
			if (!open && _readyState == WebSocketState.Open)
			{
				message = "This operation isn't available in: open";
				return false;
			}
			if (!closing && _readyState == WebSocketState.Closing)
			{
				message = "This operation isn't available in: closing";
				return false;
			}
			if (!closed && _readyState == WebSocketState.Closed)
			{
				message = "This operation isn't 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 isn't available in: client";
				return false;
			}
			if (!server && !_client)
			{
				message = "This operation isn't available in: server";
				return false;
			}
			return checkIfAvailable(connecting, open, closing, closed, out message);
		}

		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 isn't 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(CloseEventArgs e, bool send, bool receive, bool received)
		{
			lock (_forConn)
			{
				if (_readyState == WebSocketState.Closing)
				{
					_logger.Info("The closing is already in progress.");
					return;
				}
				if (_readyState == WebSocketState.Closed)
				{
					_logger.Info("The connection has been closed.");
					return;
				}
				send = send && _readyState == WebSocketState.Open;
				receive = receive && send;
				_readyState = WebSocketState.Closing;
			}
			_logger.Trace("Begin closing the connection.");
			byte[] frameAsBytes = (send ? WebSocketFrame.CreateCloseFrame(e.PayloadData, _client).ToArray() : null);
			e.WasClean = closeHandshake(frameAsBytes, receive, received);
			releaseResources();
			_logger.Trace("End closing the connection.");
			_readyState = WebSocketState.Closed;
			try
			{
				this.OnClose.Emit(this, e);
			}
			catch (Exception ex)
			{
				_logger.Error(ex.ToString());
				error("An exception has occurred during the OnClose event.", ex);
			}
		}

		private void closeAsync(CloseEventArgs e, bool send, bool receive, bool received)
		{
			Action<CloseEventArgs, bool, bool, bool> closer = close;
			closer.BeginInvoke(e, 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);
			received = received || (receive && flag && _exitReceiving != null && _exitReceiving.WaitOne(_waitTime));
			bool flag2 = flag && received;
			_logger.Debug($"Was clean?: {flag2}\n  sent: {flag}\n  received: {received}");
			return flag2;
		}

		private bool connect()
		{
			lock (_forConn)
			{
				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;
				}
				try
				{
					_readyState = WebSocketState.Connecting;
					if (!doHandshake())
					{
						return false;
					}
					_readyState = WebSocketState.Open;
				}
				catch (Exception ex)
				{
					_logger.Fatal(ex.ToString());
					fatal("An exception has occurred while connecting.", ex);
					return false;
				}
				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;
			return _handshakeRequestChecker == null || (message = _handshakeRequestChecker(context)) == null;
		}

		private MessageEventArgs dequeueFromMessageEventQueue()
		{
			lock (_forMessageEventQueue)
			{
				return (_messageEventQueue.Count > 0) ? _messageEventQueue.Dequeue() : null;
			}
		}

		private bool doHandshake()
		{
			setClientStream();
			HttpResponse httpResponse = sendHandshakeRequest();
			if (!checkHandshakeResponse(httpResponse, out var text))
			{
				_logger.Fatal(text);
				fatal("An error has occurred while connecting.", CloseStatusCode.ProtocolError);
				return false;
			}
			if (_protocolsRequested)
			{
				_protocol = httpResponse.Headers["Sec-WebSocket-Protocol"];
			}
			if (_extensionsRequested)
			{
				processSecWebSocketExtensionsServerHeader(httpResponse.Headers["Sec-WebSocket-Extensions"]);
			}
			processCookies(httpResponse.Cookies);
			return true;
		}

		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, code);
		}

		private void fatal(string message, CloseStatusCode code)
		{
			close(new CloseEventArgs(code, message), !code.IsReserved(), receive: false, received: false);
		}

		private void init()
		{
			_compression = CompressionMethod.None;
			_cookies = new WebSocketSharp.Net.CookieCollection();
			_forConn = new object();
			_forSend = 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 exception has occurred during an OnMessage event.", ex);
				}
				lock (_forMessageEventQueue)
				{
					if (_messageEventQueue.Count == 0 || _readyState != WebSocketState.Open)
					{
						_inMessage = false;
						break;
					}
					e = _messageEventQueue.Dequeue();
				}
				bool flag = true;
			}
		}

		private void messages(MessageEventArgs e)
		{
			try
			{
				this.OnMessage.Emit(this, e);
			}
			catch (Exception ex)
			{
				_logger.Error(ex.ToString());
				error("An exception 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 exception 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 processCloseFrame(WebSocketFrame frame)
		{
			PayloadData payloadData = frame.PayloadData;
			close(new CloseEventArgs(payloadData), !payloadData.IncludesReservedCloseStatusCode, 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)
		{
			if (send(new WebSocketFrame(Opcode.Pong, frame.PayloadData, _client).ToArray()))
			{
				_logger.Trace("Returned a pong.");
			}
			if (_emitOnPing)
			{
				enqueueToMessageEventQueue(new MessageEventArgs(frame));
			}
			return true;
		}

		private bool processPongFrame(WebSocketFrame frame)
		{
			_receivePong.Set();
			_logger.Trace("Received a pong.");
			return true;
		}

		private bool processReceivedFrame(WebSocketFrame frame)
		{
			if (!checkReceivedFrame(frame, out var text))
			{
				throw new WebSocketException(CloseStatusCode.ProtocolError, text);
			}
			frame.Unmask();
			return frame.IsFragment ? processFragmentFrame(frame) : (frame.IsData ? processDataFrame(frame) : (frame.IsPing ? processPingFrame(frame) : (frame.IsPong ? processPongFrame(frame) : (frame.IsClose ? processCloseFrame(frame) : processUnsupportedFrame(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 (_receivePong != null)
			{
				_receivePong.Close();
				_receivePong = null;
			}
			if (_exitReceiving != null)
			{
				_exitReceiving.Close();
				_exitReceiving = 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(byte[] frameAsBytes)
		{
			lock (_forConn)
			{
				if (_readyState != WebSocketState.Open)
				{
					_logger.Error("The sending has been interrupted.");
					return false;
				}
				return sendBytes(frameAsBytes);
			}
		}

		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("The sending has been interrupted.", null);
					}
				}
				catch (Exception ex)
				{
					_logger.Error(ex.ToString());
					error("An exception has occurred while sending data.", 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 == 0)
			{
				return send(Fin.Final, opcode, EmptyBytes, compressed);
			}
			long num = length / FragmentLength;
			int num2 = (int)(length % FragmentLength);
			byte[] array = null;
			if (num == 0)
			{
				array = new byte[num2];
				return stream.Read(array, 0, num2) == num2 && send(Fin.Final, opcode, array, compressed);
			}
			array = new byte[FragmentLength];
			if (num == 1 && num2 == 0)
			{
				return stream.Read(array, 0, FragmentLength) == FragmentLength && send(Fin.Final, opcode, array, compressed);
			}
			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))
				{
					return false;
				}
			}
			if (num2 == 0)
			{
				num2 = FragmentLength;
			}
			else
			{
				array = new byte[num2];
			}
			return stream.Read(array, 0, num2) == num2 && send(Fin.Final, Opcode.Cont, array, compressed);
		}

		private bool send(Fin fin, Opcode opcode, byte[] data, bool compressed)
		{
			lock (_forConn)
			{
				if (_readyState != WebSocketState.Open)
				{
					_logger.Error("The sending has been interrupted.");
					return false;
				}
				return sendBytes(new WebSocketFrame(fin, opcode, data, compressed, _client).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 exception has occurred during a send callback.", ex);
				}
			}, null);
		}

		private bool sendBytes(byte[] bytes)
		{
			try
			{
				_stream.Write(bytes, 0, bytes.Length);
				return true;
			}
			catch (Exception ex)
			{
				_logger.Error(ex.ToString());
				return false;
			}
		}

		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();
			}
			_exitReceiving = new AutoResetEvent(initialState: false);
			_receivePong = new AutoResetEvent(initialState: false);
			Action receive = null;
			receive = delegate
			{
				WebSocketFrame.ReadFrameAsync(_stream, unmask: false, delegate(WebSocketFrame frame)
				{
					if (!processReceivedFrame(frame) || _readyState == WebSocketState.Closed)
					{
						_exitReceiving?.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)
		{
			return value != null && value == CreateResponseKey(_base64Key);
		}

		private bool validateSecWebSocketExtensionsClientHeader(string value)
		{
			return value == null || value.Length > 0;
		}

		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)
		{
			return value != null && value.Length > 0;
		}

		private bool validateSecWebSocketProtocolClientHeader(string value)
		{
			return value == null || value.Length > 0;
		}

		private bool validateSecWebSocketProtocolServerHeader(string value)
		{
			if (value == null)
			{
				return !_protocolsRequested;
			}
			if (value.Length == 0)
			{
				return false;
			}
			return _protocolsRequested && _protocols.Contains((string p) => p == value);
		}

		private bool validateSecWebSocketVersionClientHeader(string value)
		{
			return value != null && value == "13";
		}

		private bool validateSecWebSocketVersionServerHeader(string value)
		{
			return value == null || value == "13";
		}

		internal static string CheckCloseParameters(ushort code, string reason, bool client)
		{
			return (!code.IsCloseStatusCode()) ? "An invalid close status code." : ((code != 1005) ? ((code == 1010 && !client) ? "MandatoryExtension cannot be used by a server." : ((code == 1011 && client) ? "ServerError cannot be used by a client." : ((!reason.IsNullOrEmpty() && reason.UTF8Encode().Length > 123) ? "A reason has greater than the allowable max size." : null))) : ((!reason.IsNullOrEmpty()) ? "NoStatus cannot have a reason." : null));
		}

		internal static string CheckCloseParameters(CloseStatusCode code, string reason, bool client)
		{
			return (code != CloseStatusCode.NoStatus) ? ((code == CloseStatusCode.MandatoryExtension && !client) ? "MandatoryExtension cannot be used by a server." : ((code == CloseStatusCode.ServerError && client) ? "ServerError cannot be used by a client." : ((!reason.IsNullOrEmpty() && reason.UTF8Encode().Length > 123) ? "A reason has greater than the allowable max size." : null))) : ((!reason.IsNullOrEmpty()) ? "NoStatus cannot have a reason." : null);
		}

		internal static string CheckPingParameter(string message, out byte[] bytes)
		{
			bytes = message.UTF8Encode();
			return (bytes.Length > 125) ? "A message has greater than the allowable max size." : null;
		}

		internal static string CheckSendParameter(byte[] data)
		{
			return (data == null) ? "'data' is null." : null;
		}

		internal static string CheckSendParameter(FileInfo file)
		{
			return (file == null) ? "'file' is null." : null;
		}

		internal static string CheckSendParameter(string data)
		{
			return (data == null) ? "'data' is null." : null;
		}

		internal static string CheckSendParameters(Stream stream, int length)
		{
			return (stream == null) ? "'stream' is null." : ((!stream.CanRead) ? "'stream' cannot be read." : ((length < 1) ? "'length' is less than 1." : null));
		}

		internal void Close(HttpResponse response)
		{
			_readyState = WebSocketState.Closing;
			sendHttpResponse(response);
			releaseServerResources();
			_readyState = WebSocketState.Closed;
		}

		internal void Close(WebSocketSharp.Net.HttpStatusCode code)
		{
			Close(createHandshakeFailureResponse(code));
		}

		internal void Close(CloseEventArgs e, byte[] frameAsBytes, bool receive)
		{
			lock (_forConn)
			{
				if (_readyState == WebSocketState.Closing)
				{
					_logger.Info("The closing is already in progress.");
					return;
				}
				if (_readyState == WebSocketState.Closed)
				{
					_logger.Info("The connection has been closed.");
					return;
				}
				_readyState = WebSocketState.Closing;
			}
			e.WasClean = closeHandshake(frameAsBytes, receive, received: false);
			releaseServerResources();
			releaseCommonResources();
			_readyState = WebSocketState.Closed;
			try
			{
				this.OnClose.Emit(this, e);
			}
			catch (Exception ex)
			{
				_logger.Error(ex.ToString());
			}
		}

		internal static string CreateBase64Key()
		{
			byte[] array = new byte[16];
			RandomNumber.GetBytes(array);
			return Convert.ToBase64String(array);
		}

		internal static string CreateResponseKey(string base64Key)
		{
			StringBuilder stringBuilder = new StringBuilder(base64Key, 64);
			stringBuilder.Append("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
			SHA1 sHA = new SHA1CryptoServiceProvider();
			byte[] inArray = sHA.ComputeHash(stringBuilder.ToString().UTF8Encode());
			return Convert.ToBase64String(inArray);
		}

		internal void InternalAccept()
		{
			try
			{
				if (!acceptHandshake())
				{
					return;
				}
				_readyState = WebSocketState.Open;
			}
			catch (Exception ex)
			{
				_logger.Fatal(ex.ToString());
				fatal("An exception has occurred while accepting.", ex);
				return;
			}
			open();
		}

		internal bool Ping(byte[] frameAsBytes, TimeSpan timeout)
		{
			if (_readyState != WebSocketState.Open)
			{
				return false;
			}
			if (!send(frameAsBytes))
			{
				return false;
			}
			return _receivePong?.WaitOne(timeout) ?? false;
		}

		internal void Send(Opcode opcode, byte[] data, Dictionary<CompressionMethod, byte[]> cache)
		{
			lock (_forSend)
			{
				lock (_forConn)
				{
					if (_readyState != WebSocketState.Open)
					{
						_logger.Error("The sending has been interrupted.");
						return;
					}
					try
					{
						if (!cache.TryGetValue(_compression, out var value))
						{
							value = new WebSocketFrame(Fin.Final, opcode, data.Compress(_compression), _compression != CompressionMethod.None, mask: false).ToArray();
							cache.Add(_compression, value);
						}
						sendBytes(value);
					}
					catch (Exception ex)
					{
						_logger.Error(ex.ToString());
					}
				}
			}
		}

		internal void Send(Opcode opcode, Stream stream, Dictionary<CompressionMethod, Stream> cache)
		{
			lock (_forSend)
			{
				try
				{
					if (!cache.TryGetValue(_compression, out var value))
					{
						value = stream.Compress(_compression);
						cache.Add(_compression, value);
					}
					else
					{
						value.Position = 0L;
					}
					send(opcode, value, _compression != CompressionMethod.None);
				}
				catch (Exception ex)
				{
					_logger.Error(ex.ToString());
				}
			}
		}

		public void Accept()
		{
			if (!checkIfAvailable(client: false, server: true, connecting: true, open: false, closing: false, closed: false, out var text))
			{
				_logger.Error(text);
				error("An error has occurred in accepting.", null);
			}
			else if (accept())
			{
				open();
			}
		}

		public void AcceptAsync()
		{
			if (!checkIfAvailable(client: false, server: true, connecting: true, open: false, closing: false, closed: false, out var text))
			{
				_logger.Error(text);
				error("An error has occurred in accepting.", null);
				return;
			}
			Func<bool> acceptor = accept;
			acceptor.BeginInvoke(delegate(IAsyncResult ar)
			{
				if (acceptor.EndInvoke(ar))
				{
					open();
				}
			}, null);
		}

		public void Close()
		{
			if (!checkIfAvailable(connecting: true, open: true, closing: false, closed: false, out var text))
			{
				_logger.Error(text);
				error("An error has occurred in closing the connection.", null);
			}
			else
			{
				close(new CloseEventArgs(), send: true, receive: true, received: false);
			}
		}

		public void Close(ushort code)
		{
			string text = _readyState.CheckIfAvailable(connecting: true, open: true, closing: false, closed: false) ?? CheckCloseParameters(code, null, _client);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in closing the connection.", null);
			}
			else if (code == 1005)
			{
				close(new CloseEventArgs(), send: true, receive: true, received: false);
			}
			else
			{
				bool receive = !code.IsReserved();
				close(new CloseEventArgs(code), receive, receive, received: false);
			}
		}

		public void Close(CloseStatusCode code)
		{
			string text = _readyState.CheckIfAvailable(connecting: true, open: true, closing: false, closed: false) ?? CheckCloseParameters(code, null, _client);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in closing the connection.", null);
			}
			else if (code == CloseStatusCode.NoStatus)
			{
				close(new CloseEventArgs(), send: true, receive: true, received: false);
			}
			else
			{
				bool receive = !code.IsReserved();
				close(new CloseEventArgs(code), receive, receive, received: false);
			}
		}

		public void Close(ushort code, string reason)
		{
			string text = _readyState.CheckIfAvailable(connecting: true, open: true, closing: false, closed: false) ?? CheckCloseParameters(code, reason, _client);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in closing the connection.", null);
			}
			else if (code == 1005)
			{
				close(new CloseEventArgs(), send: true, receive: true, received: false);
			}
			else
			{
				bool receive = !code.IsReserved();
				close(new CloseEventArgs(code, reason), receive, receive, received: false);
			}
		}

		public void Close(CloseStatusCode code, string reason)
		{
			string text = _readyState.CheckIfAvailable(connecting: true, open: true, closing: false, closed: false) ?? CheckCloseParameters(code, reason, _client);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in closing the connection.", null);
			}
			else if (code == CloseStatusCode.NoStatus)
			{
				close(new CloseEventArgs(), send: true, receive: true, received: false);
			}
			else
			{
				bool receive = !code.IsReserved();
				close(new CloseEventArgs(code, reason), receive, receive, received: false);
			}
		}

		public void CloseAsync()
		{
			if (!checkIfAvailable(connecting: true, open: true, closing: false, closed: false, out var text))
			{
				_logger.Error(text);
				error("An error has occurred in closing the connection.", null);
			}
			else
			{
				closeAsync(new CloseEventArgs(), send: true, receive: true, received: false);
			}
		}

		public void CloseAsync(ushort code)
		{
			string text = _readyState.CheckIfAvailable(connecting: true, open: true, closing: false, closed: false) ?? CheckCloseParameters(code, null, _client);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in closing the connection.", null);
			}
			else if (code == 1005)
			{
				closeAsync(new CloseEventArgs(), send: true, receive: true, received: false);
			}
			else
			{
				bool receive = !code.IsReserved();
				closeAsync(new CloseEventArgs(code), receive, receive, received: false);
			}
		}

		public void CloseAsync(CloseStatusCode code)
		{
			string text = _readyState.CheckIfAvailable(connecting: true, open: true, closing: false, closed: false) ?? CheckCloseParameters(code, null, _client);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in closing the connection.", null);
			}
			else if (code == CloseStatusCode.NoStatus)
			{
				closeAsync(new CloseEventArgs(), send: true, receive: true, received: false);
			}
			else
			{
				bool receive = !code.IsReserved();
				closeAsync(new CloseEventArgs(code), receive, receive, received: false);
			}
		}

		public void CloseAsync(ushort code, string reason)
		{
			string text = _readyState.CheckIfAvailable(connecting: true, open: true, closing: false, closed: false) ?? CheckCloseParameters(code, reason, _client);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in closing the connection.", null);
			}
			else if (code == 1005)
			{
				closeAsync(new CloseEventArgs(), send: true, receive: true, received: false);
			}
			else
			{
				bool receive = !code.IsReserved();
				closeAsync(new CloseEventArgs(code, reason), receive, receive, received: false);
			}
		}

		public void CloseAsync(CloseStatusCode code, string reason)
		{
			string text = _readyState.CheckIfAvailable(connecting: true, open: true, closing: false, closed: false) ?? CheckCloseParameters(code, reason, _client);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in closing the connection.", null);
			}
			else if (code == CloseStatusCode.NoStatus)
			{
				closeAsync(new CloseEventArgs(), send: true, receive: true, received: false);
			}
			else
			{
				bool receive = !code.IsReserved();
				closeAsync(new CloseEventArgs(code, reason), receive, receive, received: false);
			}
		}

		public void Connect()
		{
			if (!checkIfAvailable(client: true, server: false, connecting: true, open: false, closing: false, closed: true, out var text))
			{
				_logger.Error(text);
				error("An error has occurred in connecting.", null);
			}
			else if (connect())
			{
				open();
			}
		}

		public void ConnectAsync()
		{
			if (!checkIfAvailable(client: true, server: false, connecting: true, open: false, closing: false, closed: true, out var text))
			{
				_logger.Error(text);
				error("An error has occurred in connecting.", null);
				return;
			}
			Func<bool> connector = connect;
			connector.BeginInvoke(delegate(IAsyncResult ar)
			{
				if (connector.EndInvoke(ar))
				{
					open();
				}
			}, null);
		}

		public bool Ping()
		{
			byte[] frameAsBytes = (_client ? WebSocketFrame.CreatePingFrame(mask: true).ToArray() : WebSocketFrame.EmptyPingBytes);
			return Ping(frameAsBytes, _waitTime);
		}

		public bool Ping(string message)
		{
			if (message == null || message.Length == 0)
			{
				return Ping();
			}
			byte[] bytes;
			string text = CheckPingParameter(message, out bytes);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in sending a ping.", null);
				return false;
			}
			return Ping(WebSocketFrame.CreatePingFrame(bytes, _client).ToArray(), _waitTime);
		}

		public void Send(byte[] data)
		{
			string text = _readyState.CheckIfAvailable(connecting: false, open: true, closing: false, closed: false) ?? CheckSendParameter(data);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in sending data.", null);
			}
			else
			{
				send(Opcode.Binary, new MemoryStream(data));
			}
		}

		public void Send(FileInfo file)
		{
			string text = _readyState.CheckIfAvailable(connecting: false, open: true, closing: false, closed: false) ?? CheckSendParameter(file);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in sending data.", null);
			}
			else
			{
				send(Opcode.Binary, file.OpenRead());
			}
		}

		public void Send(string data)
		{
			string text = _readyState.CheckIfAvailable(connecting: false, open: true, closing: false, closed: false) ?? CheckSendParameter(data);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in sending data.", null);
			}
			else
			{
				send(Opcode.Text, new MemoryStream(data.UTF8Encode()));
			}
		}

		public void SendAsync(byte[] data, Action<bool> completed)
		{
			string text = _readyState.CheckIfAvailable(connecting: false, open: true, closing: false, closed: false) ?? CheckSendParameter(data);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in sending data.", null);
			}
			else
			{
				sendAsync(Opcode.Binary, new MemoryStream(data), completed);
			}
		}

		public void SendAsync(FileInfo file, Action<bool> completed)
		{
			string text = _readyState.CheckIfAvailable(connecting: false, open: true, closing: false, closed: false) ?? CheckSendParameter(file);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in sending data.", null);
			}
			else
			{
				sendAsync(Opcode.Binary, file.OpenRead(), completed);
			}
		}

		public void SendAsync(string data, Action<bool> completed)
		{
			string text = _readyState.CheckIfAvailable(connecting: false, open: true, closing: false, closed: false) ?? CheckSendParameter(data);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in sending data.", null);
			}
			else
			{
				sendAsync(Opcode.Text, new MemoryStream(data.UTF8Encode()), completed);
			}
		}

		public void SendAsync(Stream stream, int length, Action<bool> completed)
		{
			string text = _readyState.CheckIfAvailable(connecting: false, open: true, closing: false, closed: false) ?? CheckSendParameters(stream, length);
			if (text != null)
			{
				_logger.Error(text);
				error("An error has occurred in sending data.", null);
				return;
			}
			stream.ReadBytesAsync(length, delegate(byte[] data)
			{
				int num = data.Length;
				if (num == 0)
				{
					_logger.Error("The data cannot be read from 'stream'.");
					error("An error has occurred in sending data.", null);
				}
				else
				{
					if (num < length)
					{
						_logger.Warn($"The length of the data is less than 'length':\n  expected: {length}\n  actual: {num}");
					}
					bool obj = send(Opcode.Binary, new MemoryStream(data));
					if (completed != null)
					{
						completed(obj);
					}
				}
			}, delegate(Exception ex)
			{
				_logger.Error(ex.ToString());
				error("An exception has occurred while sending data.", ex);
			});
		}

		public void SetCookie(WebSocketSharp.Net.Cookie cookie)
		{
			if (!checkIfAvailable(client: true, server: false, connecting: true, open: false, closing: false, closed: true, out var text))
			{
				_logger.Error(text);
				error("An error has occurred in setting a cookie.", null);
				return;
			}
			lock (_forConn)
			{
				if (!checkIfAvailable(connecting: true, open: false, closing: false, closed: true, out text))
				{
					_logger.Error(text);
					error("An error has occurred in setting a cookie.", null);
					return;
				}
				if (cookie == null)
				{
					_logger.Error("'cookie' is null.");
					error("An error has occurred in setting a cookie.", null);
					return;
				}
				lock (_cookies.SyncRoot)
				{
					_cookies.SetOrRemove(cookie);
				}
			}
		}

		public void SetCredentials(string username, string password, bool preAuth)
		{
			if (!checkIfAvailable(client: true, server: false, connecting: true, open: false, closing: false, closed: true, out var text))
			{
				_logger.Error(text);
				error("An error has occurred in setting the credentials.", null);
				return;
			}
			lock (_forConn)
			{
				if (!checkIfAvailable(connecting: true, open: false, closing: false, closed: true, out text))
				{
					_logger.Error(text);
					error("An error has occurred in setting the credentials.", null);
				}
				else if (username.IsNullOrEmpty())
				{
					_logger.Warn("The credentials are set back to the default.");
					_credentials = null;
					_preAuth = false;
				}
				else if (Ext.Contains(username, ':') || !username.IsText())
				{
					_logger.Error("'username' contains an invalid character.");
					error("An error has occurred in setting the credentials.", null);
				}
				else if (!password.IsNullOrEmpty() && !password.IsText())
				{
					_logger.Error("'password' contains an invalid character.");
					error("An error has occurred in setting the credentials.", null);
				}
				else
				{
					_credentials = new WebSocketSharp.Net.NetworkCredential(username, password, _uri.PathAndQuery);
					_preAuth = preAuth;
				}
			}
		}

		public void SetProxy(string url, string username, string password)
		{
			if (!checkIfAvailable(client: true, server: false, connecting: true, open: false, closing: false, closed: true, out var text))
			{
				_logger.Error(text);
				error("An error has occurred in setting the proxy.", null);
				return;
			}
			lock (_forConn)
			{
				Uri result;
				if (!checkIfAvailable(connecting: true, open: false, closing: false, closed: true, out text))
				{
					_logger.Error(text);
					error("An error has occurred in setting the proxy.", null);
				}
				else if (url.IsNullOrEmpty())
				{
					_logger.Warn("The proxy url and credentials are set back to the default.");
					_proxyUri = null;
					_proxyCredentials = null;
				}
				else if (!Uri.TryCreate(url, UriKind.Absolute, out result) || result.Scheme != "http" || result.Segments.Length > 1)
				{
					_logger.Error("The syntax of a proxy url must be 'http://<host>[:<port>]'.");
					error("An error has occurred in setting the proxy.", null);
				}
				else if (username.IsNullOrEmpty())
				{
					_logger.Warn("The proxy credentials are set back to the default.");
					_proxyUri = result;
					_proxyCredentials = null;
				}
				else if (Ext.Contains(username, ':') || !username.IsText())
				{
					_logger.Error("'username' contains an invalid character.");
					error("An error has occurred in setting the proxy.", null);
				}
				else if (!password.IsNullOrEmpty() && !password.IsText())
				{
					_logger.Error("'password' contains an invalid character.");
					error("An error has occurred in setting the proxy.", null);
				}
				else
				{
					_proxyUri = result;
					_proxyCredentials = new WebSocketSharp.Net.NetworkCredential(username, password, $"{_uri.DnsSafeHost}:{_uri.Port}");
				}
			}
		}

		void IDisposable.Dispose()
		{
			close(new CloseEventArgs(CloseStatusCode.Away), send: true, receive: true, received: false);
		}
	}
}
namespace WebSocketSharp.Server
{
	public class WebSocketServer
	{
		private IPAddress _address;

		private WebSocketSharp.Net.AuthenticationSchemes _authSchemes;

		private static readonly string _defaultRealm;

		private bool _dnsStyle;

		private string _hostname;

		private TcpListener _listener;

		private Logger _logger;

		private int _port;

		private string _realm;

		private Thread _receiveThread;

		private bool _reuseAddress;

		private bool _secure;

		private WebSocketServiceManager _services;

		private ServerSslConfiguration _sslConfig;

		private volatile ServerState _state;

		private object _sync;

		private Func<IIdentity, WebSocketSharp.Net.NetworkCredential> _userCredFinder;

		public IPAddress Address => _address;

		public WebSocketSharp.Net.AuthenticationSchemes AuthenticationSchemes
		{
			get
			{
				return _authSchemes;
			}
			set
			{
				string text = _state.CheckIfAvailable(ready: true, start: false, shutting: false);
				if (text != null)
				{
					_logger.Error(text);
				}
				else
				{
					_authSchemes = value;
				}
			}
		}

		public bool IsListening => _state == ServerState.Start;

		public bool IsSecure => _secure;

		public bool KeepClean
		{
			get
			{
				return _services.KeepClean;
			}
			set
			{
				string text = _state.CheckIfAvailable(ready: true, start: false, shutting: false);
				if (text != null)
				{
					_logger.Error(text);
				}
				else
				{
					_services.KeepClean = value;
				}
			}
		}

		public Logger Log => _logger;

		public int Port => _port;

		public string Realm
		{
			get
			{
				return _realm;
			}
			set
			{
				string text = _state.CheckIfAvailable(ready: true, start: false, shutting: false);
				if (text != null)
				{
					_logger.Error(text);
				}
				else
				{
					_realm = value;
				}
			}
		}

		public bool ReuseAddress
		{
			get
			{
				return _reuseAddress;
			}
			set
			{
				string text = _state.CheckIfAvailable(ready: true, start: false, shutting: false);
				if (text != null)
				{
					_logger.Error(text);
				}
				else
				{
					_reuseAddress = value;
				}
			}
		}

		public ServerSslConfiguration SslConfiguration
		{
			get
			{
				return _sslConfig ?? (_sslConfig = new ServerSslConfiguration(null));
			}
			set
			{
				string text = _state.CheckIfAvailable(ready: true, start: false, shutting: false);
				if (text != null)
				{
					_logger.Error(text);
				}
				else
				{
					_sslConfig = value;
				}
			}
		}

		public Func<IIdentity, WebSocketSharp.Net.NetworkCredential> UserCredentialsFinder
		{
			get
			{
				return _userCredFinder;
			}
			set
			{
				string text = _state.CheckIfAvailable(ready: true, start: false, shutting: false);
				if (text != null)
				{
					_logger.Error(text);
				}
				else
				{
					_userCredFinder = value;
				}
			}
		}

		public TimeSpan WaitTime
		{
			get
			{
				return _services.WaitTime;
			}
			set
			{
				string text = _state.CheckIfAvailable(ready: true, start: false, shutting: false) ?? value.CheckIfValidWaitTime();
				if (text != null)
				{
					_logger.Error(text);
				}
				else
				{
					_services.WaitTime = value;
				}
			}
		}

		public WebSocketServiceManager WebSocketServices => _services;

		static WebSocketServer()
		{
			_defaultRealm = "SECRET AREA";
		}

		public WebSocketServer()
		{
			init(null, IPAddress.Any, 80, secure: false);
		}

		public WebSocketServer(int port)
			: this(port, port == 443)
		{
		}

		public WebSocketServer(string url)
		{
			if (url == null)
			{
				throw new ArgumentNullException("url");
			}
			if (url.Length == 0)
			{
				throw new ArgumentException("An empty string.", "url");
			}
			if (!tryCreateUri(url, out var result, out var message))
			{
				throw new ArgumentException(message, "url");
			}
			string dnsSafeHost = result.DnsSafeHost;
			IPAddress address = dnsSafeHost.ToIPAddress();
			if (!address.IsLocal())
			{
				throw new ArgumentException("The host part isn't a local host name: " + url, "url");
			}
			init(dnsSafeHost, address, result.Port, result.Scheme == "wss");
		}

		public WebSocketServer(int port, bool secure)
		{
			if (!port.IsPortNumber())
			{
				throw new ArgumentOutOfRangeException("port", "Not between 1 and 65535 inclusive: " + port);
			}
			init(null, IPAddress.Any, port, secure);
		}

		public WebSocketServer(IPAddress address, int port)
			: this(address, port, port == 443)
		{
		}

		public WebSocketServer(IPAddress address, int port, bool secure)
		{
			if (address == null)
			{
				throw new ArgumentNullException("address");
			}
			if (!address.IsLocal())
			{
				throw new ArgumentException("Not a local IP address: " + address, "address");
			}
			if (!port.IsPortNumber())
			{
				throw new ArgumentOutOfRangeException("port", "Not between 1 and 65535 inclusive: " + port);
			}
			init(null, address, port, secure);
		}

		private void abort()
		{
			lock (_sync)
			{
				if (!IsListening)
				{
					return;
				}
				_state = ServerState.ShuttingDown;
			}
			_listener.Stop();
			_services.Stop(new CloseEventArgs(CloseStatusCode.ServerError), send: true, receive: false);
			_state = ServerState.Stop;
		}

		private string checkIfCertificateExists()
		{
			return (_secure && (_sslConfig == null || _sslConfig.ServerCertificate == null)) ? "The secure connection requires a server certificate." : null;
		}

		private string getRealm()
		{
			string realm = _realm;
			return (realm != null && realm.Length > 0) ? realm : _defaultRealm;
		}

		private void init(string hostname, IPAddress address, int port, bool secure)
		{
			_hostname = hostname ?? address.ToString();
			_address = address;
			_port = port;
			_secure = se