Decompiled source of Project Arrhythmia Multiplayer v1.4.2

patchers/PAMultiplayer.Preloader/DiscordRPC.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using DiscordRPC.Converters;
using DiscordRPC.Events;
using DiscordRPC.Exceptions;
using DiscordRPC.Helper;
using DiscordRPC.IO;
using DiscordRPC.Logging;
using DiscordRPC.Message;
using DiscordRPC.RPC;
using DiscordRPC.RPC.Commands;
using DiscordRPC.RPC.Payload;
using DiscordRPC.Registry;
using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Discord RPC")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Discord RPC")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("819d20d6-8d88-45c1-a4d2-aa21f10abd19")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace DiscordRPC
{
	public class Configuration
	{
		[JsonProperty("api_endpoint")]
		public string ApiEndpoint { get; set; }

		[JsonProperty("cdn_host")]
		public string CdnHost { get; set; }

		[JsonProperty("environment")]
		public string Environment { get; set; }
	}
	public sealed class DiscordRpcClient : IDisposable
	{
		private ILogger _logger;

		private RpcConnection connection;

		private bool _shutdownOnly = true;

		private object _sync = new object();

		public bool HasRegisteredUriScheme { get; private set; }

		public string ApplicationID { get; private set; }

		public string SteamID { get; private set; }

		public int ProcessID { get; private set; }

		public int MaxQueueSize { get; private set; }

		public bool IsDisposed { get; private set; }

		public ILogger Logger
		{
			get
			{
				return _logger;
			}
			set
			{
				_logger = value;
				if (connection != null)
				{
					connection.Logger = value;
				}
			}
		}

		public bool AutoEvents { get; private set; }

		public bool SkipIdenticalPresence { get; set; }

		public int TargetPipe { get; private set; }

		public RichPresence CurrentPresence { get; private set; }

		public EventType Subscription { get; private set; }

		public User CurrentUser { get; private set; }

		public Configuration Configuration { get; private set; }

		public bool IsInitialized { get; private set; }

		public bool ShutdownOnly
		{
			get
			{
				return _shutdownOnly;
			}
			set
			{
				_shutdownOnly = value;
				if (connection != null)
				{
					connection.ShutdownOnly = value;
				}
			}
		}

		public event OnReadyEvent OnReady;

		public event OnCloseEvent OnClose;

		public event OnErrorEvent OnError;

		public event OnPresenceUpdateEvent OnPresenceUpdate;

		public event OnSubscribeEvent OnSubscribe;

		public event OnUnsubscribeEvent OnUnsubscribe;

		public event OnJoinEvent OnJoin;

		[Obsolete("Spectating is no longer supported by Discord.")]
		public event OnSpectateEvent OnSpectate;

		public event OnJoinRequestedEvent OnJoinRequested;

		public event OnConnectionEstablishedEvent OnConnectionEstablished;

		public event OnConnectionFailedEvent OnConnectionFailed;

		public event OnRpcMessageEvent OnRpcMessage;

		public DiscordRpcClient(string applicationID)
			: this(applicationID, -1, null, autoEvents: true, null)
		{
		}

		public DiscordRpcClient(string applicationID, int pipe = -1, ILogger logger = null, bool autoEvents = true, INamedPipeClient client = null)
		{
			if (string.IsNullOrEmpty(applicationID))
			{
				throw new ArgumentNullException("applicationID");
			}
			ApplicationID = applicationID.Trim();
			TargetPipe = pipe;
			ProcessID = Process.GetCurrentProcess().Id;
			HasRegisteredUriScheme = false;
			AutoEvents = autoEvents;
			SkipIdenticalPresence = true;
			_logger = logger ?? new NullLogger();
			connection = new RpcConnection(ApplicationID, ProcessID, TargetPipe, client ?? new ManagedNamedPipeClient(), (!autoEvents) ? 128u : 0u)
			{
				ShutdownOnly = _shutdownOnly,
				Logger = _logger
			};
			connection.OnRpcMessage += delegate(object sender, IMessage msg)
			{
				if (this.OnRpcMessage != null)
				{
					this.OnRpcMessage(this, msg);
				}
				if (AutoEvents)
				{
					ProcessMessage(msg);
				}
			};
		}

		public IMessage[] Invoke()
		{
			if (AutoEvents)
			{
				Logger.Error("Cannot Invoke client when AutomaticallyInvokeEvents has been set.");
				return new IMessage[0];
			}
			IMessage[] array = connection.DequeueMessages();
			foreach (IMessage message in array)
			{
				ProcessMessage(message);
			}
			return array;
		}

		private void ProcessMessage(IMessage message)
		{
			if (message == null)
			{
				return;
			}
			switch (message.Type)
			{
			case MessageType.PresenceUpdate:
				lock (_sync)
				{
					if (message is PresenceMessage presenceMessage)
					{
						if (presenceMessage.Presence == null)
						{
							CurrentPresence = null;
						}
						else if (CurrentPresence == null)
						{
							CurrentPresence = new RichPresence().Merge(presenceMessage.Presence);
						}
						else
						{
							CurrentPresence.Merge(presenceMessage.Presence);
						}
						presenceMessage.Presence = CurrentPresence;
					}
				}
				if (this.OnPresenceUpdate != null)
				{
					this.OnPresenceUpdate(this, message as PresenceMessage);
				}
				break;
			case MessageType.Ready:
				if (message is ReadyMessage readyMessage)
				{
					lock (_sync)
					{
						Configuration = readyMessage.Configuration;
						CurrentUser = readyMessage.User;
					}
					SynchronizeState();
				}
				if (this.OnReady != null)
				{
					this.OnReady(this, message as ReadyMessage);
				}
				break;
			case MessageType.Close:
				if (this.OnClose != null)
				{
					this.OnClose(this, message as CloseMessage);
				}
				break;
			case MessageType.Error:
				if (this.OnError != null)
				{
					this.OnError(this, message as ErrorMessage);
				}
				break;
			case MessageType.JoinRequest:
				if (Configuration != null && message is JoinRequestMessage joinRequestMessage)
				{
					joinRequestMessage.User.SetConfiguration(Configuration);
				}
				if (this.OnJoinRequested != null)
				{
					this.OnJoinRequested(this, message as JoinRequestMessage);
				}
				break;
			case MessageType.Subscribe:
				lock (_sync)
				{
					SubscribeMessage subscribeMessage = message as SubscribeMessage;
					Subscription |= subscribeMessage.Event;
				}
				if (this.OnSubscribe != null)
				{
					this.OnSubscribe(this, message as SubscribeMessage);
				}
				break;
			case MessageType.Unsubscribe:
				lock (_sync)
				{
					UnsubscribeMessage unsubscribeMessage = message as UnsubscribeMessage;
					Subscription &= ~unsubscribeMessage.Event;
				}
				if (this.OnUnsubscribe != null)
				{
					this.OnUnsubscribe(this, message as UnsubscribeMessage);
				}
				break;
			case MessageType.Join:
				if (this.OnJoin != null)
				{
					this.OnJoin(this, message as JoinMessage);
				}
				break;
			case MessageType.Spectate:
				if (this.OnSpectate != null)
				{
					this.OnSpectate(this, message as SpectateMessage);
				}
				break;
			case MessageType.ConnectionEstablished:
				if (this.OnConnectionEstablished != null)
				{
					this.OnConnectionEstablished(this, message as ConnectionEstablishedMessage);
				}
				break;
			case MessageType.ConnectionFailed:
				if (this.OnConnectionFailed != null)
				{
					this.OnConnectionFailed(this, message as ConnectionFailedMessage);
				}
				break;
			default:
				Logger.Error("Message was queued with no appropriate handle! {0}", message.Type);
				break;
			}
		}

		public void Respond(JoinRequestMessage request, bool acceptRequest)
		{
			Respond(request.User.ID, acceptRequest);
		}

		public void Respond(User user, bool acceptRequest)
		{
			Respond(user.ID, acceptRequest);
		}

		public void Respond(ulong userID, bool acceptRequest)
		{
			if (IsDisposed)
			{
				throw new ObjectDisposedException("Discord IPC Client");
			}
			if (connection == null)
			{
				throw new ObjectDisposedException("Connection", "Cannot initialize as the connection has been deinitialized");
			}
			if (!IsInitialized)
			{
				throw new UninitializedException();
			}
			connection.EnqueueCommand(new RespondCommand
			{
				Accept = acceptRequest,
				UserID = userID.ToString()
			});
		}

		public void SetPresence(RichPresence presence)
		{
			if (IsDisposed)
			{
				throw new ObjectDisposedException("Discord IPC Client");
			}
			if (connection == null)
			{
				throw new ObjectDisposedException("Connection", "Cannot initialize as the connection has been deinitialized");
			}
			if (!IsInitialized)
			{
				Logger.Warning("The client is not yet initialized, storing the presence as a state instead.");
			}
			if (presence == null)
			{
				if (!SkipIdenticalPresence || CurrentPresence != null)
				{
					connection.EnqueueCommand(new PresenceCommand
					{
						PID = ProcessID,
						Presence = null
					});
				}
			}
			else
			{
				if (presence.HasSecrets() && !HasRegisteredUriScheme)
				{
					throw new BadPresenceException("Cannot send a presence with secrets as this object has not registered a URI scheme. Please enable the uri scheme registration in the DiscordRpcClient constructor.");
				}
				if (presence.HasParty() && presence.Party.Max < presence.Party.Size)
				{
					throw new BadPresenceException("Presence maximum party size cannot be smaller than the current size.");
				}
				if (presence.HasSecrets() && !presence.HasParty())
				{
					Logger.Warning("The presence has set the secrets but no buttons will show as there is no party available.");
				}
				if (!SkipIdenticalPresence || !presence.Matches(CurrentPresence))
				{
					connection.EnqueueCommand(new PresenceCommand
					{
						PID = ProcessID,
						Presence = presence.Clone()
					});
				}
			}
			lock (_sync)
			{
				CurrentPresence = presence?.Clone();
			}
		}

		public RichPresence Update(Action<RichPresence> func)
		{
			if (!IsInitialized)
			{
				throw new UninitializedException();
			}
			RichPresence richPresence;
			lock (_sync)
			{
				richPresence = ((CurrentPresence == null) ? new RichPresence() : CurrentPresence.Clone());
			}
			func(richPresence);
			SetPresence(richPresence);
			return richPresence;
		}

		public RichPresence UpdateType(ActivityType type)
		{
			return Update(delegate(RichPresence p)
			{
				p.Type = type;
			});
		}

		public RichPresence UpdateStatusDisplayType(StatusDisplayType type)
		{
			return Update(delegate(RichPresence p)
			{
				p.StatusDisplay = type;
			});
		}

		public RichPresence UpdateButtons(Button[] buttons = null)
		{
			return Update(delegate(RichPresence p)
			{
				p.Buttons = buttons;
			});
		}

		public RichPresence SetButton(Button button, int index = 0)
		{
			return Update(delegate(RichPresence p)
			{
				p.Buttons[index] = button;
			});
		}

		public RichPresence UpdateDetails(string details)
		{
			return Update(delegate(RichPresence p)
			{
				p.Details = details;
			});
		}

		public RichPresence UpdateState(string state)
		{
			return Update(delegate(RichPresence p)
			{
				p.State = state;
			});
		}

		public RichPresence UpdateName(string name)
		{
			return Update(delegate(RichPresence p)
			{
				p.Name = name;
			});
		}

		public RichPresence UpdateParty(Party party)
		{
			return Update(delegate(RichPresence p)
			{
				p.Party = party;
			});
		}

		public RichPresence UpdatePartySize(int size)
		{
			return Update(delegate(RichPresence p)
			{
				if (p.Party == null)
				{
					throw new BadPresenceException("Cannot set the size of the party if the party does not exist");
				}
				p.Party.Size = size;
			});
		}

		public RichPresence UpdatePartySize(int size, int max)
		{
			return Update(delegate(RichPresence p)
			{
				if (p.Party == null)
				{
					throw new BadPresenceException("Cannot set the size of the party if the party does not exist");
				}
				p.Party.Size = size;
				p.Party.Max = max;
			});
		}

		public RichPresence UpdateLargeAsset(string key = null, string tooltip = null)
		{
			return Update(delegate(RichPresence p)
			{
				if (p.Assets == null)
				{
					p.Assets = new Assets();
				}
				p.Assets.LargeImageKey = key ?? p.Assets.LargeImageKey;
				p.Assets.LargeImageText = tooltip ?? p.Assets.LargeImageText;
			});
		}

		public RichPresence UpdateSmallAsset(string key = null, string tooltip = null)
		{
			return Update(delegate(RichPresence p)
			{
				if (p.Assets == null)
				{
					p.Assets = new Assets();
				}
				p.Assets.SmallImageKey = key ?? p.Assets.SmallImageKey;
				p.Assets.SmallImageText = tooltip ?? p.Assets.SmallImageText;
			});
		}

		public RichPresence UpdateSecrets(Secrets secrets)
		{
			return Update(delegate(RichPresence p)
			{
				p.Secrets = secrets;
			});
		}

		public RichPresence UpdateStartTime()
		{
			return UpdateStartTime(DateTime.UtcNow);
		}

		public RichPresence UpdateStartTime(DateTime time)
		{
			return Update(delegate(RichPresence p)
			{
				if (p.Timestamps == null)
				{
					p.Timestamps = new Timestamps();
				}
				p.Timestamps.Start = time;
			});
		}

		public RichPresence UpdateEndTime()
		{
			return UpdateEndTime(DateTime.UtcNow);
		}

		public RichPresence UpdateEndTime(DateTime time)
		{
			return Update(delegate(RichPresence p)
			{
				if (p.Timestamps == null)
				{
					p.Timestamps = new Timestamps();
				}
				p.Timestamps.End = time;
			});
		}

		public RichPresence UpdateClearTime()
		{
			return Update(delegate(RichPresence p)
			{
				p.Timestamps = null;
			});
		}

		public void ClearPresence()
		{
			if (IsDisposed)
			{
				throw new ObjectDisposedException("Discord IPC Client");
			}
			if (!IsInitialized)
			{
				throw new UninitializedException();
			}
			if (connection == null)
			{
				throw new ObjectDisposedException("Connection", "Cannot initialize as the connection has been deinitialized");
			}
			SetPresence(null);
		}

		public bool RegisterUriScheme(string steamAppID = null, string executable = null)
		{
			SchemeInfo schemeInfo = default(SchemeInfo);
			schemeInfo.ApplicationID = ApplicationID;
			schemeInfo.SteamAppID = steamAppID;
			schemeInfo.ExecutablePath = executable ?? Process.GetCurrentProcess().MainModule.FileName;
			SchemeInfo info = schemeInfo;
			return HasRegisteredUriScheme = UriScheme.Register(info, _logger);
		}

		public void Subscribe(EventType type)
		{
			SetSubscription(Subscription | type);
		}

		public void Unsubscribe(EventType type)
		{
			SetSubscription(Subscription & ~type);
		}

		public void SetSubscription(EventType type)
		{
			if (IsInitialized)
			{
				SubscribeToTypes(Subscription & ~type, isUnsubscribe: true);
				SubscribeToTypes(~Subscription & type, isUnsubscribe: false);
			}
			else
			{
				Logger.Warning("Client has not yet initialized, but events are being subscribed too. Storing them as state instead.");
			}
			lock (_sync)
			{
				Subscription = type;
			}
		}

		private void SubscribeToTypes(EventType type, bool isUnsubscribe)
		{
			if (type != 0)
			{
				if (IsDisposed)
				{
					throw new ObjectDisposedException("Discord IPC Client");
				}
				if (!IsInitialized)
				{
					throw new UninitializedException();
				}
				if (connection == null)
				{
					throw new ObjectDisposedException("Connection", "Cannot initialize as the connection has been deinitialized");
				}
				if (!HasRegisteredUriScheme)
				{
					throw new InvalidConfigurationException("Cannot subscribe/unsubscribe to an event as this application has not registered a URI Scheme. Call RegisterUriScheme().");
				}
				if ((type & EventType.Spectate) == EventType.Spectate)
				{
					connection.EnqueueCommand(new SubscribeCommand
					{
						Event = ServerEvent.ActivitySpectate,
						IsUnsubscribe = isUnsubscribe
					});
				}
				if ((type & EventType.Join) == EventType.Join)
				{
					connection.EnqueueCommand(new SubscribeCommand
					{
						Event = ServerEvent.ActivityJoin,
						IsUnsubscribe = isUnsubscribe
					});
				}
				if ((type & EventType.JoinRequest) == EventType.JoinRequest)
				{
					connection.EnqueueCommand(new SubscribeCommand
					{
						Event = ServerEvent.ActivityJoinRequest,
						IsUnsubscribe = isUnsubscribe
					});
				}
			}
		}

		public void SynchronizeState()
		{
			if (!IsInitialized)
			{
				throw new UninitializedException();
			}
			SetPresence(CurrentPresence);
			if (HasRegisteredUriScheme)
			{
				SubscribeToTypes(Subscription, isUnsubscribe: false);
			}
		}

		public bool Initialize()
		{
			if (IsDisposed)
			{
				throw new ObjectDisposedException("Discord IPC Client");
			}
			if (IsInitialized)
			{
				throw new UninitializedException("Cannot initialize a client that is already initialized");
			}
			if (connection == null)
			{
				throw new ObjectDisposedException("Connection", "Cannot initialize as the connection has been deinitialized");
			}
			return IsInitialized = connection.AttemptConnection();
		}

		public void Deinitialize()
		{
			if (!IsInitialized)
			{
				throw new UninitializedException("Cannot deinitialize a client that has not been initalized.");
			}
			connection.Close();
			IsInitialized = false;
		}

		public void Dispose()
		{
			if (!IsDisposed)
			{
				if (IsInitialized)
				{
					Deinitialize();
				}
				IsDisposed = true;
			}
		}
	}
	public enum ActivityType
	{
		Playing = 0,
		Listening = 2,
		Watching = 3,
		Competing = 5
	}
	[Serializable]
	public class Assets
	{
		private const string EXTERNAL_KEY_PREFIX = "mp:external";

		private string _largeimagekey;

		private string _largeimagetext;

		private string _largeimageurl;

		private string _smallimagekey;

		private string _smallimagetext;

		private string _smallimageurl;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string LargeImageKey
		{
			get
			{
				return _largeimagekey;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _largeimagekey, useBytes: false, 256))
				{
					throw new StringOutOfRangeException(256);
				}
				LargeImageID = null;
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string LargeImageText
		{
			get
			{
				return _largeimagetext;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _largeimagetext, useBytes: false, 128))
				{
					throw new StringOutOfRangeException(128);
				}
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string LargeImageUrl
		{
			get
			{
				return _largeimageurl;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _largeimageurl, useBytes: false, 256))
				{
					throw new StringOutOfRangeException(256);
				}
				if (!BaseRichPresence.ValidateUrl(_largeimageurl))
				{
					throw new ArgumentException("Url must be a valid URI");
				}
			}
		}

		[JsonIgnore]
		public string LargeImageID { get; private set; }

		[JsonIgnore]
		public bool IsLargeImageKeyExternal { get; private set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string SmallImageKey
		{
			get
			{
				return _smallimagekey;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _smallimagekey, useBytes: false, 256))
				{
					throw new StringOutOfRangeException(256);
				}
				SmallImageID = null;
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string SmallImageText
		{
			get
			{
				return _smallimagetext;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _smallimagetext, useBytes: false, 128))
				{
					throw new StringOutOfRangeException(128);
				}
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string SmallImageUrl
		{
			get
			{
				return _smallimageurl;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _smallimageurl, useBytes: false, 256))
				{
					throw new StringOutOfRangeException(256);
				}
				if (!BaseRichPresence.ValidateUrl(_smallimageurl))
				{
					throw new ArgumentException("Url must be a valid URI");
				}
			}
		}

		[JsonIgnore]
		public string SmallImageID { get; private set; }

		[JsonIgnore]
		public bool IsSmallImageKeyExternal { get; private set; }

		internal void Merge(Assets other)
		{
			if (other == null)
			{
				_smallimagetext = null;
				_smallimageurl = null;
				_largeimagetext = null;
				_largeimageurl = null;
				_largeimagekey = null;
				_smallimagekey = null;
				LargeImageID = null;
				SmallImageID = null;
				IsLargeImageKeyExternal = false;
				IsSmallImageKeyExternal = false;
				return;
			}
			_smallimagetext = other._smallimagetext;
			_smallimageurl = other._smallimageurl;
			_largeimagetext = other._largeimagetext;
			_largeimageurl = other._largeimageurl;
			string text = other._largeimagekey ?? "";
			ulong result;
			if (text.StartsWith("mp:external"))
			{
				IsLargeImageKeyExternal = true;
				LargeImageID = text;
			}
			else if (ulong.TryParse(text, out result))
			{
				IsLargeImageKeyExternal = false;
				LargeImageID = text;
			}
			else
			{
				IsLargeImageKeyExternal = false;
				LargeImageID = null;
				_largeimagekey = text;
			}
			string text2 = other._smallimagekey ?? "";
			if (text2.StartsWith("mp:external"))
			{
				IsSmallImageKeyExternal = true;
				SmallImageID = text2;
			}
			else if (ulong.TryParse(text2, out result))
			{
				IsSmallImageKeyExternal = false;
				SmallImageID = text2;
			}
			else
			{
				IsSmallImageKeyExternal = false;
				SmallImageID = null;
				_smallimagekey = text2;
			}
		}
	}
	public class Button
	{
		private string _label;

		private string _url;

		[JsonProperty("label")]
		public string Label
		{
			get
			{
				return _label;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _label, useBytes: true, 31, Encoding.UTF8))
				{
					throw new StringOutOfRangeException(31);
				}
			}
		}

		[JsonProperty("url")]
		public string Url
		{
			get
			{
				return _url;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _url, useBytes: false, 512))
				{
					throw new StringOutOfRangeException(512);
				}
				if (!BaseRichPresence.ValidateUrl(_url))
				{
					throw new ArgumentException("Url must be a valid URI");
				}
			}
		}
	}
	[Serializable]
	public class Party
	{
		public enum PrivacySetting
		{
			Private,
			Public
		}

		private string _partyid;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string ID
		{
			get
			{
				return _partyid;
			}
			set
			{
				_partyid = value.GetNullOrString();
			}
		}

		[JsonIgnore]
		public int Size { get; set; }

		[JsonIgnore]
		public int Max { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public PrivacySetting Privacy { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		private int[] _size
		{
			get
			{
				int num = Math.Max(1, Size);
				return new int[2]
				{
					num,
					Math.Max(num, Max)
				};
			}
			set
			{
				if (value.Length != 2)
				{
					Size = 0;
					Max = 0;
				}
				else
				{
					Size = value[0];
					Max = value[1];
				}
			}
		}
	}
	[Serializable]
	[JsonObject(/*Could not decode attribute arguments.*/)]
	public class BaseRichPresence
	{
		protected internal string _state;

		protected internal string _stateUrl;

		protected internal string _name;

		protected internal string _details;

		protected internal string _detailsUrl;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string State
		{
			get
			{
				return _state;
			}
			set
			{
				if (!ValidateString(value, out _state, useBytes: false, 128))
				{
					throw new StringOutOfRangeException("State", 0, 128);
				}
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string StateUrl
		{
			get
			{
				return _stateUrl;
			}
			set
			{
				if (!ValidateString(value, out _stateUrl, useBytes: false, 256))
				{
					throw new StringOutOfRangeException(256);
				}
				if (!ValidateUrl(_stateUrl))
				{
					throw new ArgumentException("Url must be a valid URI");
				}
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string Name
		{
			get
			{
				return _name;
			}
			set
			{
				if (!ValidateString(value, out _name, useBytes: false, 256))
				{
					throw new StringOutOfRangeException(256);
				}
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string Details
		{
			get
			{
				return _details;
			}
			set
			{
				if (!ValidateString(value, out _details, useBytes: false, 128))
				{
					throw new StringOutOfRangeException(128);
				}
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string DetailsUrl
		{
			get
			{
				return _detailsUrl;
			}
			set
			{
				if (!ValidateString(value, out _detailsUrl, useBytes: false, 256))
				{
					throw new StringOutOfRangeException(256);
				}
				if (!ValidateUrl(_detailsUrl))
				{
					throw new ArgumentException("Url must be a valid URI");
				}
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Timestamps Timestamps { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Assets Assets { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Party Party { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Secrets Secrets { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public ActivityType Type { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public StatusDisplayType StatusDisplay { get; set; }

		public bool HasTimestamps()
		{
			if (Timestamps != null)
			{
				if (!Timestamps.Start.HasValue)
				{
					return Timestamps.End.HasValue;
				}
				return true;
			}
			return false;
		}

		public bool HasAssets()
		{
			return Assets != null;
		}

		public bool HasParty()
		{
			if (Party != null)
			{
				return Party.ID != null;
			}
			return false;
		}

		public bool HasSecrets()
		{
			if (Secrets != null)
			{
				if (Secrets.Join == null)
				{
					return Secrets.SpectateSecret != null;
				}
				return true;
			}
			return false;
		}

		internal static bool ValidateString(string str, out string result, bool useBytes, int length, Encoding encoding = null)
		{
			result = str;
			if (str == null)
			{
				return true;
			}
			string text = str.Trim();
			if ((useBytes && !text.WithinLength(length, encoding)) || text.Length > length)
			{
				return false;
			}
			result = text.GetNullOrString();
			return true;
		}

		internal static bool ValidateUrl(string url)
		{
			if (string.IsNullOrEmpty(url))
			{
				return true;
			}
			if (!Uri.TryCreate(url, UriKind.Absolute, out Uri _))
			{
				return false;
			}
			return true;
		}

		public static implicit operator bool(BaseRichPresence presence)
		{
			return presence != null;
		}

		internal virtual bool Matches(RichPresence other)
		{
			if (other == null)
			{
				return false;
			}
			if (State != other.State || StateUrl != other.StateUrl || Details != other.Details || Name != other.Name || DetailsUrl != other.DetailsUrl || Type != other.Type)
			{
				return false;
			}
			if (Timestamps != null)
			{
				if (other.Timestamps == null || other.Timestamps.StartUnixMilliseconds != Timestamps.StartUnixMilliseconds || other.Timestamps.EndUnixMilliseconds != Timestamps.EndUnixMilliseconds)
				{
					return false;
				}
			}
			else if (other.Timestamps != null)
			{
				return false;
			}
			if (Secrets != null)
			{
				if (other.Secrets == null || other.Secrets.Join != Secrets.Join || other.Secrets.SpectateSecret != Secrets.SpectateSecret)
				{
					return false;
				}
			}
			else if (other.Secrets != null)
			{
				return false;
			}
			if (Party != null)
			{
				if (other.Party == null || other.Party.ID != Party.ID || other.Party.Max != Party.Max || other.Party.Size != Party.Size || other.Party.Privacy != Party.Privacy)
				{
					return false;
				}
			}
			else if (other.Party != null)
			{
				return false;
			}
			if (Assets != null)
			{
				if (other.Assets == null || other.Assets.LargeImageKey != Assets.LargeImageKey || other.Assets.LargeImageText != Assets.LargeImageText || other.Assets.LargeImageUrl != Assets.LargeImageUrl || other.Assets.SmallImageKey != Assets.SmallImageKey || other.Assets.SmallImageText != Assets.SmallImageText || other.Assets.SmallImageUrl != Assets.SmallImageUrl)
				{
					return false;
				}
			}
			else if (other.Assets != null)
			{
				return false;
			}
			return true;
		}

		public RichPresence ToRichPresence()
		{
			RichPresence richPresence = new RichPresence();
			richPresence.State = State;
			richPresence.Name = Name;
			richPresence.StateUrl = StateUrl;
			richPresence.Details = Details;
			richPresence.DetailsUrl = DetailsUrl;
			richPresence.Type = Type;
			richPresence.StatusDisplay = StatusDisplay;
			richPresence.Party = ((!HasParty()) ? Party : null);
			richPresence.Secrets = ((!HasSecrets()) ? Secrets : null);
			if (HasAssets())
			{
				richPresence.Assets = new Assets
				{
					SmallImageKey = Assets.SmallImageKey,
					SmallImageText = Assets.SmallImageText,
					SmallImageUrl = Assets.SmallImageUrl,
					LargeImageKey = Assets.LargeImageKey,
					LargeImageText = Assets.LargeImageText,
					LargeImageUrl = Assets.LargeImageUrl
				};
			}
			if (HasTimestamps())
			{
				richPresence.Timestamps = new Timestamps();
				if (Timestamps.Start.HasValue)
				{
					richPresence.Timestamps.Start = Timestamps.Start;
				}
				if (Timestamps.End.HasValue)
				{
					richPresence.Timestamps.End = Timestamps.End;
				}
			}
			return richPresence;
		}
	}
	public sealed class RichPresence : BaseRichPresence
	{
		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Button[] Buttons { get; set; }

		public bool HasButtons()
		{
			if (Buttons != null)
			{
				return Buttons.Length != 0;
			}
			return false;
		}

		public RichPresence WithState(string state)
		{
			base.State = state;
			return this;
		}

		public RichPresence WithStateUrl(string stateUrl)
		{
			base.StateUrl = stateUrl;
			return this;
		}

		public RichPresence WithName(string name)
		{
			base.Name = name;
			return this;
		}

		public RichPresence WithDetails(string details)
		{
			base.Details = details;
			return this;
		}

		public RichPresence WithDetailsUrl(string detailsUrl)
		{
			base.DetailsUrl = detailsUrl;
			return this;
		}

		public RichPresence WithType(ActivityType type)
		{
			base.Type = type;
			return this;
		}

		public RichPresence WithStatusDisplay(StatusDisplayType statusDisplay)
		{
			base.StatusDisplay = statusDisplay;
			return this;
		}

		public RichPresence WithTimestamps(Timestamps timestamps)
		{
			base.Timestamps = timestamps;
			return this;
		}

		public RichPresence WithAssets(Assets assets)
		{
			base.Assets = assets;
			return this;
		}

		public RichPresence WithParty(Party party)
		{
			base.Party = party;
			return this;
		}

		public RichPresence WithSecrets(Secrets secrets)
		{
			base.Secrets = secrets;
			return this;
		}

		public RichPresence WithButtons(Button topButton, Button bottomButton = null)
		{
			if (topButton != null && bottomButton != null)
			{
				Buttons = new Button[2] { topButton, bottomButton };
			}
			else if (topButton == null && bottomButton == null)
			{
				Buttons = null;
			}
			else
			{
				Buttons = new Button[1] { topButton ?? bottomButton };
			}
			return this;
		}

		public RichPresence Clone()
		{
			return new RichPresence
			{
				State = ((_state != null) ? (_state.Clone() as string) : null),
				Name = ((_name != null) ? (_name.Clone() as string) : null),
				StateUrl = ((_stateUrl != null) ? (_stateUrl.Clone() as string) : null),
				Details = ((_details != null) ? (_details.Clone() as string) : null),
				DetailsUrl = ((_detailsUrl != null) ? (_detailsUrl.Clone() as string) : null),
				Type = base.Type,
				StatusDisplay = base.StatusDisplay,
				Buttons = ((!HasButtons()) ? null : (Buttons.Clone() as Button[])),
				Secrets = ((!HasSecrets()) ? null : new Secrets
				{
					Join = ((base.Secrets.Join != null) ? (base.Secrets.Join.Clone() as string) : null),
					SpectateSecret = ((base.Secrets.SpectateSecret != null) ? (base.Secrets.SpectateSecret.Clone() as string) : null)
				}),
				Timestamps = ((!HasTimestamps()) ? null : new Timestamps
				{
					Start = base.Timestamps.Start,
					End = base.Timestamps.End
				}),
				Assets = ((!HasAssets()) ? null : new Assets
				{
					LargeImageKey = ((base.Assets.LargeImageKey != null) ? (base.Assets.LargeImageKey.Clone() as string) : null),
					LargeImageText = ((base.Assets.LargeImageText != null) ? (base.Assets.LargeImageText.Clone() as string) : null),
					LargeImageUrl = ((base.Assets.LargeImageUrl != null) ? (base.Assets.LargeImageUrl.Clone() as string) : null),
					SmallImageKey = ((base.Assets.SmallImageKey != null) ? (base.Assets.SmallImageKey.Clone() as string) : null),
					SmallImageText = ((base.Assets.SmallImageText != null) ? (base.Assets.SmallImageText.Clone() as string) : null),
					SmallImageUrl = ((base.Assets.SmallImageUrl != null) ? (base.Assets.SmallImageUrl.Clone() as string) : null)
				}),
				Party = ((!HasParty()) ? null : new Party
				{
					ID = base.Party.ID,
					Size = base.Party.Size,
					Max = base.Party.Max,
					Privacy = base.Party.Privacy
				})
			};
		}

		internal RichPresence Merge(BaseRichPresence presence)
		{
			_state = presence.State;
			_name = presence.Name;
			_stateUrl = presence.StateUrl;
			_details = presence.Details;
			_detailsUrl = presence.DetailsUrl;
			base.Type = presence.Type;
			base.StatusDisplay = presence.StatusDisplay;
			base.Party = presence.Party;
			base.Timestamps = presence.Timestamps;
			base.Secrets = presence.Secrets;
			if (presence.HasAssets())
			{
				if (!HasAssets())
				{
					base.Assets = presence.Assets;
				}
				else
				{
					base.Assets.Merge(presence.Assets);
				}
			}
			else
			{
				base.Assets = null;
			}
			return this;
		}

		internal override bool Matches(RichPresence other)
		{
			if (!base.Matches(other))
			{
				return false;
			}
			if ((Buttons == null) ^ (other.Buttons == null))
			{
				return false;
			}
			if (Buttons != null)
			{
				if (Buttons.Length != other.Buttons.Length)
				{
					return false;
				}
				for (int i = 0; i < Buttons.Length; i++)
				{
					Button button = Buttons[i];
					Button button2 = other.Buttons[i];
					if (button.Label != button2.Label || button.Url != button2.Url)
					{
						return false;
					}
				}
			}
			return true;
		}

		public static implicit operator bool(RichPresence presesnce)
		{
			return presesnce != null;
		}
	}
	internal sealed class RichPresenceResponse : BaseRichPresence
	{
		[JsonProperty("application_id")]
		public string ClientID { get; private set; }

		[JsonProperty("name")]
		public new string Name { get; private set; }
	}
	[Serializable]
	public class Secrets
	{
		[Obsolete("This feature has been deprecated my Mason in issue #152 on the offical library. Was originally used as a Notify Me feature, it has been replaced with Join / Spectate.", true)]
		[JsonIgnore]
		public string MatchSecret;

		private string _joinSecret;

		public const int SecretLength = 128;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string Join
		{
			get
			{
				return _joinSecret;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _joinSecret, useBytes: false, 128))
				{
					throw new StringOutOfRangeException(128);
				}
			}
		}

		[Obsolete("Property name is redundant and replaced with Join.")]
		[JsonIgnore]
		public string JoinSecret
		{
			get
			{
				return Join;
			}
			set
			{
				Join = value;
			}
		}

		[Obsolete("Spectating is no longer supported by Discord.")]
		[JsonIgnore]
		public string SpectateSecret { get; set; }

		public static Encoding Encoding => Encoding.UTF8;

		public static string CreateSecret(Random random, int length = 128)
		{
			if (length < 1 || length > 128)
			{
				throw new ArgumentOutOfRangeException("length", "Secret length must be between 1 and 128 characters.");
			}
			byte[] array = new byte[length];
			random.NextBytes(array);
			return Encoding.GetString(array);
		}

		public static string CreateFriendlySecret(Random random, int length = 128)
		{
			if (length < 1 || length > 128)
			{
				throw new ArgumentOutOfRangeException("length", "Secret length must be between 1 and 128 characters.");
			}
			string text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < length; i++)
			{
				stringBuilder.Append(text[random.Next(text.Length)]);
			}
			return stringBuilder.ToString();
		}
	}
	public enum StatusDisplayType
	{
		Name,
		State,
		Details
	}
	[Serializable]
	public class Timestamps
	{
		public static Timestamps Now => new Timestamps(DateTime.UtcNow);

		[JsonIgnore]
		public DateTime? Start { get; set; }

		[JsonIgnore]
		public DateTime? End { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public ulong? StartUnixMilliseconds
		{
			get
			{
				if (!Start.HasValue)
				{
					return null;
				}
				return ToUnixMilliseconds(Start.Value);
			}
			set
			{
				Start = (value.HasValue ? new DateTime?(FromUnixMilliseconds(value.Value)) : null);
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public ulong? EndUnixMilliseconds
		{
			get
			{
				if (!End.HasValue)
				{
					return null;
				}
				return ToUnixMilliseconds(End.Value);
			}
			set
			{
				End = (value.HasValue ? new DateTime?(FromUnixMilliseconds(value.Value)) : null);
			}
		}

		public static Timestamps FromTimeSpan(double seconds)
		{
			return FromTimeSpan(TimeSpan.FromSeconds(seconds));
		}

		public static Timestamps FromTimeSpan(TimeSpan timespan)
		{
			return new Timestamps
			{
				Start = DateTime.UtcNow,
				End = DateTime.UtcNow + timespan
			};
		}

		public Timestamps()
		{
			Start = null;
			End = null;
		}

		public Timestamps(DateTime start)
		{
			Start = start;
			End = null;
		}

		public Timestamps(DateTime start, DateTime end)
		{
			Start = start;
			End = end;
		}

		public static DateTime FromUnixMilliseconds(ulong unixTime)
		{
			return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Convert.ToDouble(unixTime));
		}

		public static ulong ToUnixMilliseconds(DateTime date)
		{
			DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
			return Convert.ToUInt64((date - dateTime).TotalMilliseconds);
		}
	}
	public class User
	{
		public enum AvatarFormat
		{
			PNG,
			JPEG,
			WebP,
			GIF
		}

		public enum AvatarSize
		{
			x16 = 0x10,
			x32 = 0x20,
			x64 = 0x40,
			x128 = 0x80,
			x256 = 0x100,
			x512 = 0x200,
			x1024 = 0x400,
			x2048 = 0x800
		}

		public struct AvatarDecorationData
		{
			[JsonProperty("asset")]
			public string Asset { get; private set; }

			[JsonProperty("skuId")]
			public string SKU { get; private set; }
		}

		[Flags]
		public enum Flag
		{
			None = 0,
			Employee = 1,
			Partner = 2,
			HypeSquad = 4,
			BugHunter = 8,
			HouseBravery = 0x40,
			HouseBrilliance = 0x80,
			HouseBalance = 0x100,
			EarlySupporter = 0x200,
			TeamUser = 0x400,
			BugHunterLevel2 = 0x4000,
			VerifiedBot = 0x10000,
			VerifiedDeveloper = 0x20000,
			CertifiedModerator = 0x40000,
			BotHttpInteractions = 0x80000,
			ActiveDeveloper = 0x400000
		}

		public enum PremiumType
		{
			None,
			NitroClassic,
			Nitro,
			NitroBasic
		}

		[JsonProperty("id")]
		public ulong ID { get; private set; }

		[JsonProperty("username")]
		public string Username { get; private set; }

		[JsonProperty("discriminator")]
		[Obsolete("Discord no longer uses discriminators.")]
		public int Discriminator { get; private set; }

		[JsonProperty("global_name")]
		public string DisplayName { get; private set; }

		[JsonProperty("avatar")]
		public string Avatar { get; private set; }

		public bool IsAvatarAnimated
		{
			get
			{
				if (Avatar != null)
				{
					return Avatar.StartsWith("a_");
				}
				return false;
			}
		}

		[JsonProperty("avatar_decoration_data")]
		public AvatarDecorationData? AvatarDecoration { get; private set; }

		[JsonProperty("bot")]
		public bool Bot { get; private set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Flag Flags { get; private set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public PremiumType Premium { get; private set; }

		public string CdnEndpoint { get; private set; }

		internal User()
		{
			CdnEndpoint = "cdn.discordapp.com";
		}

		internal void SetConfiguration(Configuration configuration)
		{
			CdnEndpoint = configuration.CdnHost;
		}

		public string GetAvatarURL()
		{
			return GetAvatarURL(AvatarFormat.PNG, AvatarSize.x128);
		}

		public string GetAvatarURL(AvatarFormat format)
		{
			return GetAvatarURL(format, AvatarSize.x128);
		}

		public string GetAvatarURL(AvatarFormat format, AvatarSize size)
		{
			string text = $"/avatars/{ID}/{Avatar}";
			if (string.IsNullOrEmpty(Avatar))
			{
				if (format != 0)
				{
					throw new BadImageFormatException("The user has no avatar and the requested format " + format.ToString() + " is not supported. (Only supports PNG).");
				}
				int num = (int)((ID >> 22) % 6);
				if (Discriminator > 0)
				{
					num = Discriminator % 5;
				}
				text = $"/embed/avatars/{num}";
			}
			return $"https://{CdnEndpoint}{text}{GetAvatarExtension(format)}?size={(int)size}&animated=true";
		}

		public string GetAvatarDecorationURL()
		{
			return GetAvatarDecorationURL(AvatarFormat.PNG);
		}

		public string GetAvatarDecorationURL(AvatarFormat format)
		{
			if (!AvatarDecoration.HasValue)
			{
				return null;
			}
			string arg = "/avatar-decoration-presets/" + AvatarDecoration.Value.Asset;
			return $"https://{CdnEndpoint}{arg}{GetAvatarExtension(format)}";
		}

		public string GetAvatarExtension(AvatarFormat format)
		{
			return "." + format.ToString().ToLowerInvariant();
		}

		public override string ToString()
		{
			if (!string.IsNullOrEmpty(DisplayName))
			{
				return DisplayName;
			}
			if (Discriminator != 0)
			{
				return Username + "#" + Discriminator.ToString("D4");
			}
			return Username;
		}
	}
	[Flags]
	public enum EventType
	{
		None = 0,
		[Obsolete("Spectating is no longer supported by Discord.")]
		Spectate = 1,
		Join = 2,
		JoinRequest = 4
	}
}
namespace DiscordRPC.RPC
{
	internal class RpcConnection : IDisposable
	{
		public static readonly int VERSION = 1;

		public static readonly int POLL_RATE = 1000;

		private static readonly bool CLEAR_ON_SHUTDOWN = true;

		private static readonly bool LOCK_STEP = false;

		private ILogger _logger;

		private RpcState _state;

		private readonly object l_states = new object();

		private Configuration _configuration;

		private readonly object l_config = new object();

		private volatile bool aborting;

		private volatile bool shutdown;

		private string applicationID;

		private int processID;

		private long nonce;

		private Thread thread;

		private INamedPipeClient namedPipe;

		private int targetPipe;

		private readonly object l_rtqueue = new object();

		private readonly uint _maxRtQueueSize;

		private Queue<ICommand> _rtqueue;

		private readonly object l_rxqueue = new object();

		private readonly uint _maxRxQueueSize;

		private Queue<IMessage> _rxqueue;

		private AutoResetEvent queueUpdatedEvent = new AutoResetEvent(initialState: false);

		private BackoffDelay delay;

		public ILogger Logger
		{
			get
			{
				return _logger;
			}
			set
			{
				_logger = value;
				if (namedPipe != null)
				{
					namedPipe.Logger = value;
				}
			}
		}

		public RpcState State
		{
			get
			{
				lock (l_states)
				{
					return _state;
				}
			}
		}

		public Configuration Configuration
		{
			get
			{
				Configuration configuration = null;
				lock (l_config)
				{
					return _configuration;
				}
			}
		}

		public bool IsRunning => thread != null;

		public bool ShutdownOnly { get; set; }

		public event OnRpcMessageEvent OnRpcMessage;

		public RpcConnection(string applicationID, int processID, int targetPipe, INamedPipeClient client, uint maxRxQueueSize = 128u, uint maxRtQueueSize = 512u)
		{
			this.applicationID = applicationID;
			this.processID = processID;
			this.targetPipe = targetPipe;
			namedPipe = client;
			ShutdownOnly = true;
			Logger = new ConsoleLogger();
			delay = new BackoffDelay(500, 60000);
			_maxRtQueueSize = maxRtQueueSize;
			_rtqueue = new Queue<ICommand>((int)(_maxRtQueueSize + 1));
			_maxRxQueueSize = maxRxQueueSize;
			_rxqueue = new Queue<IMessage>((int)(_maxRxQueueSize + 1));
			nonce = 0L;
		}

		private long GetNextNonce()
		{
			nonce++;
			return nonce;
		}

		internal void EnqueueCommand(ICommand command)
		{
			Logger.Trace("Enqueue Command: {0}", command.GetType().FullName);
			if (aborting || shutdown)
			{
				return;
			}
			lock (l_rtqueue)
			{
				if (_rtqueue.Count == _maxRtQueueSize)
				{
					Logger.Error("Too many enqueued commands, dropping oldest one. Maybe you are pushing new presences to fast?");
					_rtqueue.Dequeue();
				}
				_rtqueue.Enqueue(command);
			}
		}

		private void EnqueueMessage(IMessage message)
		{
			try
			{
				if (this.OnRpcMessage != null)
				{
					this.OnRpcMessage(this, message);
				}
			}
			catch (Exception ex)
			{
				Logger.Error("Unhandled Exception while processing event: {0}", ex.GetType().FullName);
				Logger.Error(ex.Message);
				Logger.Error(ex.StackTrace);
			}
			if (_maxRxQueueSize == 0)
			{
				Logger.Trace("Enqueued Message, but queue size is 0.");
				return;
			}
			Logger.Trace("Enqueue Message: {0}", message.Type);
			lock (l_rxqueue)
			{
				if (_rxqueue.Count == _maxRxQueueSize)
				{
					Logger.Warning("Too many enqueued messages, dropping oldest one.");
					_rxqueue.Dequeue();
				}
				_rxqueue.Enqueue(message);
			}
		}

		internal IMessage DequeueMessage()
		{
			lock (l_rxqueue)
			{
				if (_rxqueue.Count == 0)
				{
					return null;
				}
				return _rxqueue.Dequeue();
			}
		}

		internal IMessage[] DequeueMessages()
		{
			lock (l_rxqueue)
			{
				IMessage[] result = _rxqueue.ToArray();
				_rxqueue.Clear();
				return result;
			}
		}

		private void MainLoop()
		{
			Logger.Info("RPC Connection Started");
			if (Logger.Level <= LogLevel.Trace)
			{
				Logger.Trace("============================");
				Logger.Trace("Assembly:             " + Assembly.GetAssembly(typeof(RichPresence)).FullName);
				Logger.Trace("Pipe:                 " + namedPipe.GetType().FullName);
				Logger.Trace("Platform:             " + Environment.OSVersion.ToString());
				Logger.Trace("DotNet:               " + Environment.Version.ToString());
				Logger.Trace("applicationID:        " + applicationID);
				Logger.Trace("targetPipe:           " + targetPipe);
				ILogger logger = Logger;
				int pOLL_RATE = POLL_RATE;
				logger.Trace("POLL_RATE:            " + pOLL_RATE);
				ILogger logger2 = Logger;
				uint maxRtQueueSize = _maxRtQueueSize;
				logger2.Trace("_maxRtQueueSize:      " + maxRtQueueSize);
				ILogger logger3 = Logger;
				maxRtQueueSize = _maxRxQueueSize;
				logger3.Trace("_maxRxQueueSize:      " + maxRtQueueSize);
				Logger.Trace("============================");
			}
			while (!aborting && !shutdown)
			{
				try
				{
					if (namedPipe == null)
					{
						Logger.Error("Something bad has happened with our pipe client!");
						aborting = true;
						return;
					}
					Logger.Trace("Connecting to the pipe through the {0}", namedPipe.GetType().FullName);
					if (namedPipe.Connect(targetPipe))
					{
						Logger.Trace("Connected to the pipe. Attempting to establish handshake...");
						EnqueueMessage(new ConnectionEstablishedMessage
						{
							ConnectedPipe = namedPipe.ConnectedPipe
						});
						EstablishHandshake();
						Logger.Trace("Connection Established. Starting reading loop...");
						bool flag = true;
						while (flag && !aborting && !shutdown && namedPipe.IsConnected)
						{
							if (namedPipe.ReadFrame(out var frame))
							{
								Logger.Trace("Read Payload: {0}", frame.Opcode);
								switch (frame.Opcode)
								{
								case Opcode.Close:
								{
									ClosePayload @object = frame.GetObject<ClosePayload>();
									Logger.Warning("We have been told to terminate by discord: ({0}) {1}", @object.Code, @object.Reason);
									EnqueueMessage(new CloseMessage
									{
										Code = @object.Code,
										Reason = @object.Reason
									});
									flag = false;
									break;
								}
								case Opcode.Ping:
									Logger.Trace("PING");
									frame.Opcode = Opcode.Pong;
									namedPipe.WriteFrame(frame);
									break;
								case Opcode.Pong:
									Logger.Trace("PONG");
									break;
								case Opcode.Frame:
								{
									if (shutdown)
									{
										Logger.Warning("Skipping frame because we are shutting down.");
										break;
									}
									if (frame.Data == null)
									{
										Logger.Error("We received no data from the frame so we cannot get the event payload!");
										break;
									}
									EventPayload eventPayload = null;
									try
									{
										eventPayload = frame.GetObject<EventPayload>();
									}
									catch (Exception ex)
									{
										Logger.Error("Failed to parse event! {0}", ex.Message);
										Logger.Error("Data: {0}", frame.Message);
									}
									try
									{
										if (eventPayload != null)
										{
											ProcessFrame(eventPayload);
										}
									}
									catch (Exception ex2)
									{
										Logger.Error("Failed to process event! {0}", ex2.Message);
										Logger.Error("Data: {0}", frame.Message);
									}
									break;
								}
								default:
									Logger.Error("Invalid opcode: {0}", frame.Opcode);
									flag = false;
									break;
								}
							}
							if (!aborting && namedPipe.IsConnected)
							{
								ProcessCommandQueue();
								queueUpdatedEvent.WaitOne(POLL_RATE);
							}
						}
						Logger.Trace("Left main read loop for some reason. Aborting: {0}, Shutting Down: {1}", aborting, shutdown);
					}
					else
					{
						Logger.Error("Failed to connect for some reason.");
						EnqueueMessage(new ConnectionFailedMessage
						{
							FailedPipe = targetPipe
						});
					}
					if (!aborting && !shutdown)
					{
						long num = delay.NextDelay();
						Logger.Trace("Waiting {0}ms before attempting to connect again", num);
						Thread.Sleep(delay.NextDelay());
					}
				}
				catch (Exception ex3)
				{
					Logger.Error("Unhandled Exception: {0}", ex3.GetType().FullName);
					Logger.Error(ex3.Message);
					Logger.Error(ex3.StackTrace);
				}
				finally
				{
					if (namedPipe.IsConnected)
					{
						Logger.Trace("Closing the named pipe.");
						namedPipe.Close();
					}
					SetConnectionState(RpcState.Disconnected);
				}
			}
			Logger.Trace("Left Main Loop");
			if (namedPipe != null)
			{
				namedPipe.Dispose();
			}
			Logger.Info("Thread Terminated, no longer performing RPC connection.");
		}

		private void ProcessFrame(EventPayload response)
		{
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			Logger.Info("Handling Response. Cmd: {0}, Event: {1}", response.Command, response.Event);
			if (response.Event.HasValue && response.Event.Value == ServerEvent.Error)
			{
				Logger.Error("Error received from the RPC");
				ErrorMessage @object = response.GetObject<ErrorMessage>();
				Logger.Error("Server responded with an error message: ({0}) {1}", @object.Code.ToString(), @object.Message);
				EnqueueMessage(@object);
			}
			else if (State == RpcState.Connecting && response.Command == Command.Dispatch && response.Event.HasValue && response.Event.Value == ServerEvent.Ready)
			{
				Logger.Info("Connection established with the RPC");
				SetConnectionState(RpcState.Connected);
				delay.Reset();
				ReadyMessage object2 = response.GetObject<ReadyMessage>();
				lock (l_config)
				{
					_configuration = object2.Configuration;
					object2.User.SetConfiguration(_configuration);
				}
				EnqueueMessage(object2);
			}
			else if (State == RpcState.Connected)
			{
				switch (response.Command)
				{
				case Command.Dispatch:
					ProcessDispatch(response);
					break;
				case Command.SetActivity:
				{
					if (response.Data == null)
					{
						EnqueueMessage(new PresenceMessage());
						break;
					}
					RichPresenceResponse object3 = response.GetObject<RichPresenceResponse>();
					EnqueueMessage(new PresenceMessage(object3));
					break;
				}
				case Command.Subscribe:
				case Command.Unsubscribe:
				{
					((Collection<JsonConverter>)(object)new JsonSerializer().Converters).Add((JsonConverter)(object)new EnumSnakeCaseConverter());
					ServerEvent value = response.GetObject<EventPayload>().Event.Value;
					if (response.Command == Command.Subscribe)
					{
						EnqueueMessage(new SubscribeMessage(value));
					}
					else
					{
						EnqueueMessage(new UnsubscribeMessage(value));
					}
					break;
				}
				case Command.SendActivityJoinInvite:
					Logger.Trace("Got invite response ack.");
					break;
				case Command.CloseActivityJoinRequest:
					Logger.Trace("Got invite response reject ack.");
					break;
				default:
					Logger.Error("Unknown frame was received! {0}", response.Command);
					break;
				}
			}
			else
			{
				Logger.Trace("Received a frame while we are disconnected. Ignoring. Cmd: {0}, Event: {1}", response.Command, response.Event);
			}
		}

		private void ProcessDispatch(EventPayload response)
		{
			if (response.Command == Command.Dispatch && response.Event.HasValue)
			{
				switch (response.Event.Value)
				{
				case ServerEvent.ActivitySpectate:
				{
					SpectateMessage object3 = response.GetObject<SpectateMessage>();
					EnqueueMessage(object3);
					break;
				}
				case ServerEvent.ActivityJoin:
				{
					JoinMessage object2 = response.GetObject<JoinMessage>();
					EnqueueMessage(object2);
					break;
				}
				case ServerEvent.ActivityJoinRequest:
				{
					JoinRequestMessage @object = response.GetObject<JoinRequestMessage>();
					EnqueueMessage(@object);
					break;
				}
				default:
					Logger.Warning("Ignoring {0}", response.Event.Value);
					break;
				}
			}
		}

		private void ProcessCommandQueue()
		{
			if (State != RpcState.Connected)
			{
				return;
			}
			if (aborting)
			{
				Logger.Warning("We have been told to write a queue but we have also been aborted.");
			}
			bool flag = true;
			ICommand command = null;
			while (flag && namedPipe.IsConnected)
			{
				lock (l_rtqueue)
				{
					flag = _rtqueue.Count > 0;
					if (!flag)
					{
						break;
					}
					command = _rtqueue.Peek();
				}
				if (shutdown || (!aborting && LOCK_STEP))
				{
					flag = false;
				}
				IPayload payload = command.PreparePayload(GetNextNonce());
				Logger.Trace("Attempting to send payload: {0}", payload.Command);
				PipeFrame frame = default(PipeFrame);
				if (command is CloseCommand)
				{
					SendHandwave();
					Logger.Trace("Handwave sent, ending queue processing.");
					lock (l_rtqueue)
					{
						_rtqueue.Dequeue();
						break;
					}
				}
				if (aborting)
				{
					Logger.Warning("- skipping frame because of abort.");
					lock (l_rtqueue)
					{
						_rtqueue.Dequeue();
					}
					continue;
				}
				frame.SetObject(Opcode.Frame, payload);
				Logger.Trace("Sending payload: {0}", payload.Command);
				if (namedPipe.WriteFrame(frame))
				{
					Logger.Trace("Sent Successfully.");
					lock (l_rtqueue)
					{
						_rtqueue.Dequeue();
					}
					continue;
				}
				Logger.Warning("Something went wrong during writing!");
				break;
			}
		}

		private void EstablishHandshake()
		{
			Logger.Trace("Attempting to establish a handshake...");
			if (State != 0)
			{
				Logger.Error("State must be disconnected in order to start a handshake!");
				return;
			}
			Logger.Trace("Sending Handshake...");
			if (!namedPipe.WriteFrame(new PipeFrame(Opcode.Handshake, new Handshake
			{
				Version = VERSION,
				ClientID = applicationID
			})))
			{
				Logger.Error("Failed to write a handshake.");
			}
			else
			{
				SetConnectionState(RpcState.Connecting);
			}
		}

		private void SendHandwave()
		{
			Logger.Info("Attempting to wave goodbye...");
			if (State == RpcState.Disconnected)
			{
				Logger.Error("State must NOT be disconnected in order to send a handwave!");
			}
			else if (!namedPipe.WriteFrame(new PipeFrame(Opcode.Close, new Handshake
			{
				Version = VERSION,
				ClientID = applicationID
			})))
			{
				Logger.Error("failed to write a handwave.");
			}
		}

		public bool AttemptConnection()
		{
			Logger.Info("Attempting a new connection");
			if (thread != null)
			{
				Logger.Error("Cannot attempt a new connection as the previous connection thread is not null!");
				return false;
			}
			if (State != 0)
			{
				Logger.Warning("Cannot attempt a new connection as the previous connection hasn't changed state yet.");
				return false;
			}
			if (aborting)
			{
				Logger.Error("Cannot attempt a new connection while aborting!");
				return false;
			}
			thread = new Thread(MainLoop);
			thread.Name = "Discord IPC Thread";
			thread.IsBackground = true;
			thread.Start();
			return true;
		}

		private void SetConnectionState(RpcState state)
		{
			Logger.Trace("Setting the connection state to {0}", state.ToString().ToSnakeCase().ToUpperInvariant());
			lock (l_states)
			{
				_state = state;
			}
		}

		public void Shutdown()
		{
			Logger.Trace("Initiated shutdown procedure");
			shutdown = true;
			lock (l_rtqueue)
			{
				_rtqueue.Clear();
				if (CLEAR_ON_SHUTDOWN)
				{
					_rtqueue.Enqueue(new PresenceCommand
					{
						PID = processID,
						Presence = null
					});
				}
				_rtqueue.Enqueue(new CloseCommand());
			}
			queueUpdatedEvent.Set();
		}

		public void Close()
		{
			if (thread == null)
			{
				Logger.Error("Cannot close as it is not available!");
				return;
			}
			if (aborting)
			{
				Logger.Error("Cannot abort as it has already been aborted");
				return;
			}
			if (ShutdownOnly)
			{
				Shutdown();
				return;
			}
			Logger.Trace("Updating Abort State...");
			aborting = true;
			queueUpdatedEvent.Set();
		}

		public void Dispose()
		{
			ShutdownOnly = false;
			Close();
		}
	}
	internal enum RpcState
	{
		Disconnected,
		Connecting,
		Connected
	}
}
namespace DiscordRPC.RPC.Payload
{
	internal class ClosePayload : IPayload
	{
		[JsonProperty("code")]
		public int Code { get; set; }

		[JsonProperty("message")]
		public string Reason { get; set; }

		[JsonConstructor]
		public ClosePayload()
		{
			Code = -1;
			Reason = "";
		}
	}
	internal enum Command
	{
		[EnumValue("DISPATCH")]
		Dispatch,
		[EnumValue("SET_ACTIVITY")]
		SetActivity,
		[EnumValue("SUBSCRIBE")]
		Subscribe,
		[EnumValue("UNSUBSCRIBE")]
		Unsubscribe,
		[EnumValue("SEND_ACTIVITY_JOIN_INVITE")]
		SendActivityJoinInvite,
		[EnumValue("CLOSE_ACTIVITY_JOIN_REQUEST")]
		CloseActivityJoinRequest,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		Authorize,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		Authenticate,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		GetGuild,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		GetGuilds,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		GetChannel,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		GetChannels,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		SetUserVoiceSettings,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		SelectVoiceChannel,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		GetSelectedVoiceChannel,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		SelectTextChannel,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		GetVoiceSettings,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		SetVoiceSettings,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		CaptureShortcut
	}
	internal abstract class IPayload
	{
		[JsonProperty("cmd")]
		[JsonConverter(typeof(EnumSnakeCaseConverter))]
		public Command Command { get; set; }

		[JsonProperty("nonce")]
		public string Nonce { get; set; }

		protected IPayload()
		{
		}

		protected IPayload(long nonce)
		{
			Nonce = nonce.ToString();
		}

		public override string ToString()
		{
			return $"Payload || Command: {Command}, Nonce: {Nonce}";
		}
	}
	internal class ArgumentPayload : IPayload
	{
		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public JObject Arguments { get; set; }

		public ArgumentPayload()
		{
			Arguments = null;
		}

		public ArgumentPayload(long nonce)
			: base(nonce)
		{
			Arguments = null;
		}

		public ArgumentPayload(object args, long nonce)
			: base(nonce)
		{
			SetObject(args);
		}

		public void SetObject(object obj)
		{
			Arguments = JObject.FromObject(obj);
		}

		public T GetObject<T>()
		{
			return ((JToken)Arguments).ToObject<T>();
		}

		public override string ToString()
		{
			return "Argument " + base.ToString();
		}
	}
	internal class EventPayload : IPayload
	{
		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public JObject Data { get; set; }

		[JsonProperty("evt")]
		[JsonConverter(typeof(EnumSnakeCaseConverter))]
		public ServerEvent? Event { get; set; }

		public EventPayload()
		{
			Data = null;
		}

		public EventPayload(long nonce)
			: base(nonce)
		{
			Data = null;
		}

		public T GetObject<T>()
		{
			if (Data == null)
			{
				return default(T);
			}
			return ((JToken)Data).ToObject<T>();
		}

		public override string ToString()
		{
			return "Event " + base.ToString() + ", Event: " + (Event.HasValue ? Event.ToString() : "N/A");
		}
	}
	internal enum ServerEvent
	{
		[EnumValue("READY")]
		Ready,
		[EnumValue("ERROR")]
		Error,
		[EnumValue("ACTIVITY_JOIN")]
		ActivityJoin,
		[EnumValue("ACTIVITY_SPECTATE")]
		ActivitySpectate,
		[EnumValue("ACTIVITY_JOIN_REQUEST")]
		ActivityJoinRequest
	}
}
namespace DiscordRPC.RPC.Commands
{
	internal class CloseCommand : ICommand
	{
		[JsonProperty("close_reason")]
		public string value = "Unity 5.5 doesn't handle thread aborts. Can you please close me discord?";

		[JsonProperty("pid")]
		public int PID { get; set; }

		public IPayload PreparePayload(long nonce)
		{
			return new ArgumentPayload
			{
				Command = Command.Dispatch,
				Nonce = null,
				Arguments = null
			};
		}
	}
	internal interface ICommand
	{
		IPayload PreparePayload(long nonce);
	}
	internal class PresenceCommand : ICommand
	{
		[JsonProperty("pid")]
		public int PID { get; set; }

		[JsonProperty("activity")]
		public RichPresence Presence { get; set; }

		public IPayload PreparePayload(long nonce)
		{
			return new ArgumentPayload(this, nonce)
			{
				Command = Command.SetActivity
			};
		}
	}
	internal class RespondCommand : ICommand
	{
		[JsonProperty("user_id")]
		public string UserID { get; set; }

		[JsonIgnore]
		public bool Accept { get; set; }

		public IPayload PreparePayload(long nonce)
		{
			return new ArgumentPayload(this, nonce)
			{
				Command = (Accept ? Command.SendActivityJoinInvite : Command.CloseActivityJoinRequest)
			};
		}
	}
	internal class SubscribeCommand : ICommand
	{
		public ServerEvent Event { get; set; }

		public bool IsUnsubscribe { get; set; }

		public IPayload PreparePayload(long nonce)
		{
			return new EventPayload(nonce)
			{
				Command = (IsUnsubscribe ? Command.Unsubscribe : Command.Subscribe),
				Event = Event
			};
		}
	}
}
namespace DiscordRPC.Registry
{
	public interface IRegisterUriScheme
	{
		bool Register(SchemeInfo info);
	}
	public sealed class MacUriScheme : IRegisterUriScheme
	{
		private ILogger logger;

		private static readonly string[] DiscordClientFolders = new string[3] { "discord", "discordptb", "discordcanary" };

		public MacUriScheme(ILogger logger)
		{
			this.logger = logger;
		}

		public bool Register(SchemeInfo info)
		{
			string executablePath = info.ExecutablePath;
			if (string.IsNullOrEmpty(executablePath))
			{
				logger.Error("Failed to register because the application could not be located.");
				return false;
			}
			logger.Trace("Registering Steam Command");
			string command = executablePath;
			if (info.UsingSteamApp)
			{
				command = "steam://rungameid/" + info.SteamAppID;
			}
			else
			{
				logger.Warning("This library does not fully support MacOS URI Scheme Registration.");
			}
			string[] discordClientFolders = DiscordClientFolders;
			foreach (string path in discordClientFolders)
			{
				string text = Path.Combine(Environment.GetEnvironmentVariable("HOME"), "Library/Application Support/", path);
				if (Directory.Exists(text))
				{
					logger.Trace("Discord client folder exists: {0}", text);
					RegisterSchemeForClient(text, info.ApplicationID, command);
				}
				else
				{
					logger.Trace("Discord client folder does not exist: {0}", text);
				}
			}
			return true;
		}

		private void RegisterSchemeForClient(string discordDirectory, string appId, string command)
		{
			string path = Path.Combine(discordDirectory, "games", appId + ".json");
			if (!Directory.Exists(Path.GetDirectoryName(path)))
			{
				Directory.CreateDirectory(Path.GetDirectoryName(path));
			}
			File.WriteAllText(path, "{ \"command\": \"" + command + "\" }");
		}
	}
	public sealed class UnixUriScheme : IRegisterUriScheme
	{
		private ILogger logger;

		public UnixUriScheme(ILogger logger)
		{
			this.logger = logger;
		}

		public bool Register(SchemeInfo info)
		{
			string environmentVariable = Environment.GetEnvironmentVariable("HOME");
			if (string.IsNullOrEmpty(environmentVariable))
			{
				logger.Error("Failed to register because the HOME variable was not set.");
				return false;
			}
			string executablePath = info.ExecutablePath;
			if (string.IsNullOrEmpty(executablePath))
			{
				logger.Error("Failed to register because the application was not located.");
				return false;
			}
			string text = null;
			text = ((!info.UsingSteamApp) ? executablePath : ("xdg-open steam://rungameid/" + info.SteamAppID));
			string text2 = $"[Desktop Entry]\nName=Game {info.ApplicationID}\nExec={text} %u\nType=Application\nNoDisplay=true\nCategories=Discord;Games;\nMimeType=x-scheme-handler/discord-{info.ApplicationID}";
			string text3 = "/discord-" + info.ApplicationID + ".desktop";
			string text4 = environmentVariable + "/.local/share/applications";
			if (!Directory.CreateDirectory(text4).Exists)
			{
				logger.Error("Failed to register because {0} does not exist", text4);
				return false;
			}
			File.WriteAllText(text4 + text3, text2);
			if (!RegisterMime(info.ApplicationID))
			{
				logger.Error("Failed to register because the Mime failed.");
				return false;
			}
			logger.Trace("Registered {0}, {1}, {2}", text4 + text3, text2, text);
			return true;
		}

		private bool RegisterMime(string appid)
		{
			string arguments = string.Format("default discord-{0}.desktop x-scheme-handler/discord-{0}", appid);
			Process process = Process.Start("xdg-mime", arguments);
			process.WaitForExit();
			return process.ExitCode >= 0;
		}
	}
	public struct SchemeInfo
	{
		public string ApplicationID { get; set; }

		public string SteamAppID { get; set; }

		public string ExecutablePath { get; set; }

		public bool UsingSteamApp => !string.IsNullOrEmpty(SteamAppID);
	}
	public static class UriScheme
	{
		public static bool Register(SchemeInfo info, ILogger logger = null)
		{
			if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			{
				return new WindowsUriScheme(logger).Register(info);
			}
			if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
			{
				return new UnixUriScheme(logger).Register(info);
			}
			if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
			{
				return new MacUriScheme(logger).Register(info);
			}
			logger?.Error("Unknown Platform: {0}", RuntimeInformation.OSDescription);
			throw new PlatformNotSupportedException("Platform does not support registration.");
		}
	}
	public sealed class WindowsUriScheme : IRegisterUriScheme
	{
		private ILogger logger;

		public WindowsUriScheme(ILogger logger)
		{
			this.logger = logger;
		}

		public bool Register(SchemeInfo info)
		{
			string executablePath = info.ExecutablePath;
			if (executablePath == null)
			{
				logger.Error("Failed to register application because the location was null.");
				return false;
			}
			string scheme = "discord-" + info.ApplicationID;
			string friendlyName = "Run game " + info.ApplicationID + " protocol";
			string defaultIcon = executablePath;
			string command = executablePath;
			if (info.UsingSteamApp)
			{
				string steamLocation = GetSteamLocation();
				if (steamLocation != null)
				{
					command = $"\"{steamLocation}\" steam://rungameid/{info.SteamAppID}";
				}
			}
			CreateUriScheme(scheme, friendlyName, defaultIcon, command);
			return true;
		}

		private void CreateUriScheme(string scheme, string friendlyName, string defaultIcon, string command)
		{
			if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			{
				throw new PlatformNotSupportedException("Requires Windows to use the Registry");
			}
			using (RegistryKey registryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("SOFTWARE\\Classes\\" + scheme))
			{
				registryKey.SetValue("", "URL:" + friendlyName);
				registryKey.SetValue("URL Protocol", "");
				using (RegistryKey registryKey2 = registryKey.CreateSubKey("DefaultIcon"))
				{
					registryKey2.SetValue("", defaultIcon);
				}
				using RegistryKey registryKey3 = registryKey.CreateSubKey("shell\\open\\command");
				registryKey3.SetValue("", command);
			}
			logger.Trace("Registered {0}, {1}, {2}", scheme, friendlyName, command);
		}

		public string GetSteamLocation()
		{
			if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			{
				throw new PlatformNotSupportedException("Requires Windows to use the Registry");
			}
			using RegistryKey registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\Valve\\Steam");
			if (registryKey == null)
			{
				return null;
			}
			return registryKey.GetValue("SteamExe") as string;
		}
	}
}
namespace DiscordRPC.Message
{
	public class CloseMessage : IMessage
	{
		public override MessageType Type => MessageType.Close;

		public string Reason { get; internal set; }

		public int Code { get; internal set; }

		internal CloseMessage()
		{
		}

		internal CloseMessage(string reason)
		{
			Reason = reason;
		}
	}
	public class ConnectionEstablishedMessage : IMessage
	{
		public override MessageType Type => MessageType.ConnectionEstablished;

		[Obsolete("The connected pipe is not neccessary information.")]
		public int ConnectedPipe { get; internal set; }
	}
	public class ConnectionFailedMessage : IMessage
	{
		public override MessageType Type => MessageType.ConnectionFailed;

		public int FailedPipe { get; internal set; }
	}
	public class ErrorMessage : IMessage
	{
		public override MessageType Type => MessageType.Error;

		[JsonProperty("code")]
		public ErrorCode Code { get; internal set; }

		[JsonProperty("message")]
		public string Message { get; internal set; }
	}
	public enum ErrorCode
	{
		Success = 0,
		PipeException = 1,
		ReadCorrupt = 2,
		NotImplemented = 10,
		UnknownError = 1000,
		InvalidPayload = 4000,
		InvalidCommand = 4002,
		InvalidEvent = 4004
	}
	public abstract class IMessage
	{
		private DateTime _timecreated;

		public abstract MessageType Type { get; }

		public DateTime TimeCreated => _timecreated;

		public IMessage()
		{
			_timecreated = DateTime.Now;
		}
	}
	public class JoinMessage : IMessage
	{
		public override MessageType Type => MessageType.Join;

		[JsonProperty("secret")]
		public string Secret { get; internal set; }
	}
	public class JoinRequestMessage : IMessage
	{
		public override MessageType Type => MessageType.JoinRequest;

		[JsonProperty("user")]
		public User User { get; internal set; }
	}
	public enum MessageType
	{
		Ready,
		Close,
		Error,
		PresenceUpdate,
		Subscribe,
		Unsubscribe,
		Join,
		Spectate,
		JoinRequest,
		ConnectionEstablished,
		ConnectionFailed
	}
	public class PresenceMessage : IMessage
	{
		public override MessageType Type => MessageType.PresenceUpdate;

		public BaseRichPresence Presence { get; internal set; }

		public string Name { get; internal set; }

		public string ApplicationID { get; internal set; }

		internal PresenceMessage()
			: this(null)
		{
		}

		internal PresenceMessage(RichPresenceResponse rpr)
		{
			if (rpr == null)
			{
				Presence = null;
				Name = "No Rich Presence";
				ApplicationID = "";
			}
			else
			{
				Presence = rpr;
				Name = rpr.Name;
				ApplicationID = rpr.ClientID;
			}
		}
	}
	public class ReadyMessage : IMessage
	{
		public override MessageType Type => MessageType.Ready;

		[JsonProperty("config")]
		public Configuration Configuration { get; set; }

		[JsonProperty("user")]
		public User User { get; set; }

		[JsonProperty("v")]
		public int Version { get; set; }
	}
	public class SpectateMessage : JoinMessage
	{
		public override MessageType Type => MessageType.Spectate;
	}
	public class SubscribeMessage : IMessage
	{
		public override MessageType Type => MessageType.Subscribe;

		public EventType Event { get; internal set; }

		internal SubscribeMessage(ServerEvent evt)
		{
			if (evt == ServerEvent.ActivityJoin || evt != ServerEvent.ActivityJoinRequest)
			{
				Event = EventType.Join;
			}
			else
			{
				Event = EventType.JoinRequest;
			}
		}
	}
	public class UnsubscribeMessage : IMessage
	{
		public override MessageType Type => MessageType.Unsubscribe;

		public EventType Event { get; internal set; }

		internal UnsubscribeMessage(ServerEvent evt)
		{
			if (evt == ServerEvent.ActivityJoin || evt != ServerEvent.ActivityJoinRequest)
			{
				Event = EventType.Join;
			}
			else
			{
				Event = EventType.JoinRequest;
			}
		}
	}
}
namespace DiscordRPC.Logging
{
	public class ConsoleLogger : ILogger
	{
		public LogLevel Level { get; set; }

		public bool Coloured { get; set; }

		public bool Colored
		{
			get
			{
				return Coloured;
			}
			set
			{
				Coloured = value;
			}
		}

		public ConsoleLogger()
		{
			Level = LogLevel.Info;
			Coloured = false;
		}

		public ConsoleLogger(LogLevel level)
			: this()
		{
			Level = level;
		}

		public ConsoleLogger(LogLevel level, bool coloured)
		{
			Level = level;
			Coloured = coloured;
		}

		public void Trace(string message, params object[] args)
		{
			if (Level <= LogLevel.Trace)
			{
				if (Coloured)
				{
					Console.ForegroundColor = ConsoleColor.Gray;
				}
				string text = "TRACE: " + message;
				if (args.Length != 0)
				{
					Console.WriteLine(text, args);
				}
				else
				{
					Console.WriteLine(text);
				}
			}
		}

		public void Info(string message, params object[] args)
		{
			if (Level <= LogLevel.Info)
			{
				if (Coloured)
				{
					Console.ForegroundColor = ConsoleColor.White;
				}
				string text = "INFO: " + message;
				if (args.Length != 0)
				{
					Console.WriteLine(text, args);
				}
				else
				{
					Console.WriteLine(text);
				}
			}
		}

		public void Warning(string message, params object[] args)
		{
			if (Level <= LogLevel.Warning)
			{
				if (Coloured)
				{
					Console.ForegroundColor = ConsoleColor.Yellow;
				}
				string text = "WARN: " + message;
				if (args.Length != 0)
				{
					Console.WriteLine(text, args);
				}
				else
				{
					Console.WriteLine(text);
				}
			}
		}

		public void Error(string message, params object[] args)
		{
			if (Level <= LogLevel.Error)
			{
				if (Coloured)
				{
					Console.ForegroundColor = ConsoleColor.Red;
				}
				string text = "ERR : " + message;
				if (args.Length != 0)
				{
					Console.WriteLine(text, args);
				}
				else
				{
					Console.WriteLine(text);
				}
			}
		}
	}
	public class FileLogger : ILogger
	{
		private object filelock;

		public LogLevel Level { get; set; }

		public string File { get; set; }

		public FileLogger(string path)
			: this(path, LogLevel.Info)
		{
		}

		public FileLogger(string path, LogLevel level)
		{
			Level = level;
			File = path;
			filelock = new object();
		}

		public void Trace(string message, params object[] args)
		{
			if (Level > LogLevel.Trace)
			{
				return;
			}
			lock (filelock)
			{
				System.IO.File.AppendAllText(File, "\r\nTRCE: " + ((args.Length != 0) ? string.Format(message, args) : message));
			}
		}

		public void Info(string message, params object[] args)
		{
			if (Level > LogLevel.Info)
			{
				return;
			}
			lock (filelock)
			{
				System.IO.File.AppendAllText(File, "\r\nINFO: " + ((args.Length != 0) ? string.Format(message, args) : message));
			}
		}

		public void Warning(string message, params object[] args)
		{
			if (Level > LogLevel.Warning)
			{
				return;
			}
			lock (filelock)
			{
				System.IO.File.AppendAllText(File, "\r\nWARN: " + ((args.Length != 0) ? string.Format(message, args) : message));
			}
		}

		public void Error(string message, params object[] args)
		{
			if (Level > LogLevel.Error)
			{
				return;
			}
			lock (filelock)
			{
				System.IO.File.AppendAllText(File, "\r\nERR : " + ((args.Length != 0) ? string.Format(message, args) : message));
			}
		}
	}
	public interface ILogger
	{
		LogLevel Level { get; set; }

		void Trace(string message, params object[] args);

		void Info(string message, params object[] args);

		void Warning(string message, params object[] args);

		void Error(string message, params object[] args);
	}
	public enum LogLevel
	{
		Trace = 1,
		Info = 2,
		Warning = 3,
		Error = 4,
		None = 256
	}
	public class NullLogger : ILogger
	{
		public LogLevel Level { get; set; }

		public void Trace(string message, params object[] args)
		{
		}

		public void Info(string message, params object[] args)
		{
		}

		public void Warning(string message, params object[] args)
		{
		}

		public void Error(string message, params object[] args)
		{
		}
	}
}
namespace DiscordRPC.IO
{
	internal class Handshake
	{
		[JsonProperty("v")]
		public int Version { get; set; }

		[JsonProperty("client_id")]
		public string ClientID { get; set; }
	}
	public interface INamedPipeClient : IDisposable
	{
		ILogger Logger { get; set; }

		bool IsConnected { get; }

		[Obsolete("The connected pipe is not neccessary information.")]
		int ConnectedPipe { get; }

		bool Connect(int pipe);

		bool ReadFrame(out PipeFrame frame);

		bool WriteFrame(PipeFrame frame);

		void Close();
	}
	public sealed class ManagedNamedPipeClient : INamedPipeClient, IDisposable
	{
		private NamedPipeClientStream _stream;

		private byte[] _buffer = new byte[PipeFrame.MAX_SIZE];

		private Queue<PipeFrame> _framequeue = new Queue<PipeFrame>();

		private object _framequeuelock = new object();

		private volatile bool _isDisposed;

		private volatile bool _isClosed = true;

		private object l_stream = new object();

		public ILogger Logger { get; set; }

		public bool IsConnected
		{
			get
			{
				if (_isClosed)
				{
					return false;
				}
				lock (l_stream)
				{
					return _stream != null && _stream.IsConnected;
				}
			}
		}

		public int ConnectedPipe { get; private set; }

		public ManagedNamedPipeClient()
		{
			_buffer = new byte[PipeFrame.MAX_SIZE];
			Logger = new NullLogger();
			_stream = null;
		}

		public bool Connect(int pipe)
		{
			Logger.Trace("ManagedNamedPipeClient.Connection({0})", pipe);
			if (_isDisposed)
			{
				throw new ObjectDisposedException("NamedPipe");
			}
			if (pipe > 9)
			{
				throw new ArgumentOutOfRangeException("pipe", "Argument cannot be greater than 9");
			}
			int startPipe = 0;
			if (pipe >= 0)
			{
				startPipe = pipe;
			}
			foreach (string pipe2 in PipeLocation.GetPipes(startPipe))
			{
				if (AttemptConnection(pipe2))
				{
					BeginReadStream();
					return true;
				}
			}
			return false;
		}

		private bool AttemptConnection(string pipename)
		{
			if (_isDisposed)
			{
				throw new ObjectDisposedException("_stream");
			}
			try
			{
				lock (l_stream)
				{
					Logger.Info("Attempting to connect to '{0}'", pipename);
					_stream = new NamedPipeClientStream(".", pipename, PipeDirection.InOut, PipeOptions.Asynchronous);
					_stream.Connect(0);
					Logger.Trace("Waiting for connection...");
					do
					{
						Thread.Sleep(10);
					}
					while (!_stream.IsConnected);
				}
				Logger.Info("Connected to '{0}'", pipename);
				ConnectedPipe = int.Parse(pipename.Substring(pipename.LastIndexOf('-')));
				_isClosed = false;
			}
			catch (Exception ex)
			{
				Logger.Error("Failed connection to {0}. {1}", pipename, ex.Message);
				Close();
			}
			Logger.Trace("Done. Result: {0}", _isClosed);
			return !_isClosed;
		}

		private void BeginReadStream()
		{
			if (_isClosed)
			{
				return;
			}
			try
			{
				lock (l_stream)
				{
					if (_stream != null && _stream.IsConnected)
					{
						Logger.Trace("Begining Read of {0} bytes", _buffer.Length);
						_stream.BeginRead(_buffer, 0, _buffer.Length, EndReadStream, _stream.IsConnected);
					}
				}
			}
			catch (ObjectDisposedException)
			{
				Logger.Warning("Attempted to start reading from a disposed pipe");
			}
			catch (InvalidOperationException)
			{
				Logger.Warning("Attempted to start reading from a closed pipe");
			}
			catch (Exception ex3)
			{
				Logger.Error("An exception occured while starting to read a stream: {0}", ex3.Message);
				Logger.Error(ex3.StackTrace);
			}
		}

		private void EndReadStream(IAsyncResult callback)
		{
			Logger.Trace("Ending Read");
			int num = 0;
			try
			{
				lock (l_stream)
				{
					if (_stream == null || !_stream.IsConnected)
					{
						return;
					}
					num = _stream.EndRead(callback);
				}
			}
			catch (IOException)
			{
				Logger.Warning("Attempted to end reading from a closed pipe");
				return;
			}
			catch (NullReferenceException)
			{
				Logger.Warning("Attempted to read from a null pipe");
				return;
			}
			catch (ObjectDisposedException)
			{
				Logger.Warning("Attemped to end reading from a disposed pipe");
				return;
			}
			catch (Exception ex4)
			{
				Logger.Error("An exception occured while ending a read of a stream: {0}", ex4.Message);
				Logger.Error(ex4.StackTrace);
				return;
			}
			Logger.Trace("Read {0} bytes", num);
			if (num > 0)
			{
				using MemoryStream stream = new MemoryStream(_buffer, 0, num);
				try
				{
					PipeFrame item = default(PipeFrame);
					if (item.ReadStream(stream))
					{
						Logger.Trace("Read a frame: {0}", item.Opcode);
						lock (_framequeuelock)
						{
							_framequeue.Enqueue(item);
						}
					}
					else
					{
						Logger.Error("Pipe failed to read from the data received by the stream.");
						Close();
					}
				}
				catch (Exception ex5)
				{
					Logger.Error("A exception has occured while trying to parse the pipe data: {0}", ex5.Message);
					Close();
				}
			}
			else
			{
				Logger.Error("Empty frame was read on {0}, aborting.", Environment.OSVersion);
				Close();
			}
			if (!_isClosed && IsConnected)
			{
				Logger.Trace("Starting another read");
				BeginReadStream();
			}
		}

		public bool ReadFrame(out PipeFrame frame)
		{
			if (_isDisposed)
			{
				throw new ObjectDisposedException("_stream");
			}
			lock (_framequeuelock)
			{
				if (_framequeue.Count == 0)
				{
					frame = default(PipeFrame);
					return false;
				}
				frame = _framequeue.Dequeue();
				return true;
			}
		}

		public bool WriteFrame(PipeFrame frame)
		{
			if (_isDisposed)
			{
				throw new ObjectDisposedException("_stream");
			}
			if (_isClosed || !IsConnected)
			{
				Logger.Error("Failed to write frame because the stream is closed");
				return false;
			}
			try
			{
				frame.WriteStream(_stream);
				return true;
			}
			catch (IOException ex)
			{
				Logger.Error("Failed to write frame because of a IO Exception: {0}", ex.Message);
			}
			catch (ObjectDisposedException)
			{
				Logger.Warning("Failed to write frame as the stream was already disposed");
			}
			catch (InvalidOperationException)
			{
				Logger.Warning("Failed to write frame because of a invalid operation");
			}
			return false;
		}

		public void Close()
		{
			if (_isClosed)
			{
				Logger.Warning("Tried to close a already closed pipe.");
				return;
			}
			try
			{
				lock (l_stream)
				{
					if (_stream != null)
					{
						try
						{
							_stream.Flush();
							_stream.Dispose();
						}
						catch (Exception)
						{
						}
						_stream = null;
						_isClosed = true;
					}
					else
					{
						Logger.Warning("Stream was closed, but no stream was available to begin with!");
					}
				}
			}
			catch (ObjectDisposedException)
			{
				Logger.Warning("Tried to dispose already disposed stream");
			}
			finally
			{
				_isClosed = true;
			}
		}

		public void Dispose()
		{
			if (_isDisposed)
			{
				return;
			}
			if (!_isClosed)
			{
				Close();
			}
			lock (l_stream)
			{
				if (_stream != null)
				{
					_stream.Dispose();
					_stream = null;
				}
			}
			_isDisposed = true;
		}

		[Obsolete("Use PipePermutation.GetPipes instead", true)]
		public static string GetPipeName(int pipe)
		{
			return string.Empty;
		}

		[Obsolete("Use PipePermutation.GetPipes instead", true)]
		public static string GetPipeName(int pipe, string sandbox)
		{
			return string.Empty;
		}

		[Obsolete("Use PipePermutation.GetPipes instead", true)]
		public static string GetPipeSandbox()
		{
			return string.Empty;
		}

		[Obsolete("Use PipePermutation.GetPipes instead", true)]
		public static bool IsUnix()
		{
			return true;
		}
	}
	public enum Opcode : uint
	{
		Handshake,
		Frame,
		Close,
		Ping,
		Pong
	}
	public struct PipeFrame : IEquatable<PipeFrame>
	{
		public static readonly int MAX_SIZE = 16384;

		public Opcode Opcode { get; set; }

		public uint Length => (uint)Data.Length;

		public byte[] Data { get; set; }

		public string Message
		{
			get
			{
				return GetMessage();
			}
			set
			{
				SetMessage(value);
			}
		}

		public Encoding MessageEncoding => Encoding.UTF8;

		public PipeFrame(Opcode opcode, object data)
		{
			Opcode = opcode;
			Data = null;
			SetObject(data);
		}

		private void SetMessage(string str)
		{
			Data = MessageEncoding.GetBytes(str);
		}

		private string GetMessage()
		{
			return MessageEncoding.GetString(Data);
		}

		public void SetObject(object obj)
		{
			string message = JsonConvert.SerializeObject(obj);
			SetMessage(message);
		}

		public void SetObject(Opcode opcode, object obj)
		{
			Opcode = opcode;
			SetObject(obj);
		}

		public T GetObject<T>()
		{
			return JsonConvert.DeserializeObject<T>(GetMessage());
		}

		public bool ReadStream(Stream stream)
		{
			if (!TryReadUInt32(stream, out var value))
			{
				return false;
			}
			if (!TryReadUInt32(stream, out var value2))
			{
				return false;
			}
			uint num = value2;
			using MemoryStream memoryStream = new MemoryStream();
			uint num2 = (uint)Min(2048, value2);
			byte[] array = new byte[num2];
			int count;
			while ((count = stream.Read(array, 0, Min(array.Length, num))) > 0)
			{
				num -= num2;
				memoryStream.Write(array, 0, count);
			}
			byte[] array2 = memoryStream.ToArray();
			if (array2.LongLength != value2)
			{
				return false;
			}
			Opcode = (Opcode)value;
			Data = array2;
			return true;
		}

		private int Min(int a, uint b)
		{
			if (b >= a)
			{
				return a;
			}
			return (int)b;
		}

		private bool TryReadUInt32(Stream stream, out uint value)
		{
			byte[] array = new byte[4];
			if (stream.Read(array, 0, array.Length) != 4)
			{
				value = 0u;
				return false;
			}
			value = BitConverter.ToUInt32(array, 0);
			return true;
		}

		public void WriteStream(Stream stream)
		{
			byte[] bytes = BitConverter.GetBytes((uint)Opcode);
			byte[] bytes2 = BitConverter.GetBytes(Length);
			byte[] array = new byte[bytes.Length + bytes2.Length + Data.Length];
			bytes.CopyTo(array, 0);
			bytes2.CopyTo(array, bytes.Length);
			Data.CopyTo(array, bytes.Length + bytes2.Length);
			stream.Write(array, 0, array.Length);
		}

		public bool Equals(PipeFrame other)
		{
			if (Opcode == other.Opcode && Length == other.Length)
			{
				return Data == other.Data;
			}
			return false;
		}
	}
	public static class PipeLocation
	{
		[CompilerGenerated]
		private sealed class <GetUnixPipes>d__5 : IEnumerable<string>, IEnumerable, IEnumerator<string>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private string <>2__current;

			private int <>l__initialThreadId;

			private int index;

			public int <>3__index;

			private IEnumerator<string> <>7__wrap1;

			private string <tempDir>5__3;

			private string[] <>7__wrap3;

			private int <>7__wrap4;

			string IEnumerator<string>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <GetUnixPipes>d__5(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				int num = <>1__state;
				if (num == -3 || (uint)(num - 1) <= 1u)
				{
					try
					{
					}
					finally
					{
						<>m__Finally1();
					}
				}
				<>7__wrap1 = null;
				<tempDir>5__3 = null;
				<>7__wrap3 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				try
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<>7__wrap1 = TemporaryDirectories().GetEnumerator();
						<>1__state = -3;
						break;
					case 1:
						<>1__state = -3;
						<>7__wrap3 = LinuxPackageManagers;
						<>7__wrap4 = 0;
						goto IL_0105;
					case 2:
						{
							<>1__state = -3;
							<>7__wrap4++;
							goto IL_0105;
						}
						IL_0105:
						if (<>7__wrap4 < <>7__wrap3.Length)
						{
							string path = <>7__wrap3[<>7__wrap4];
							<>2__current = Path.Combine(<tempDir>5__3, path, string.Format("{0}{1}", "discord-ipc-", index));
							<>1__state = 2;
							return true;
						}
						<>7__wrap3 = null;
						<tempDir>5__3 = null;
						break;
					}
					if (<>7__wrap1.MoveNext())
					{
						<tempDir>5__3 = <>7__wrap1.Current;
						<>2__current = Path.Combine(<tempDir>5__3, string.Format("{0}{1}", "discord-ipc-", index));
						<>1__state = 1;
						return true;
					}
					<>m__Finally1();
					<>7__wrap1 = null;
					return false;
				}
				catch
				{
					//try-fault
					((IDisposable)this).Dispose();
					throw;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			private void <>m__Finally1()
			{
				<>1__state = -1;
				if (<>7__wrap1 != null)
				{
					<>7__wrap1.Dispose();
				}
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			IEnumerator<string> IEnumerable<string>.GetEnumerator()
			{
				<GetUnixPipes>d__5 <GetUnixPipes>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					<GetUnixPipes>d__ = this;
				}
				else
				{
					<GetUnixPipes>d__ = new <GetUnixPipes>d__5(0);
				}
				<GetUnixPipes>d__.index = <>3__index;
				return <GetUnixPipes>d__;
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<string>)this).GetEnumerator();
			}
		}

		[CompilerGenerated]
		private sealed class <GetWindowsPipes>d__4 : IEnumerable<string>, IEnumerable, IEnumerator<string>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private string <>2__current;

			private int <>l__initialThreadId;

			private int index;

			public int <>3__index;

			string IEnumerator<string>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <GetWindowsPipes>d__4(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = string.Format("{0}{1}", "discord-ipc-", index);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					return false;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			IEnumerator<string> IEnumerable<string>.GetEnumerator()
			{
				<GetWindowsPipes>d__4 <GetWindowsPipes>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					<GetWindowsPipes>d__ = this;
				}
				else
				{
					<GetWindowsPipes>d__ = new <GetWindowsPipes>d__4(0);
				}
				<GetWindowsPipes>d__.index = <>3__index;
				return <GetWindowsPipes>d__;
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<string>)this).GetEnumerator();
			}
		}

		[CompilerGenerated]
		private sealed class <TemporaryDirectories>d__6 : IEnumerable<string>, IEnumerable, IEnumerator<string>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private string <>2__current;

			private int <>l__initialThreadId;

			string IEnumerator<string>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <TemporaryDirectories>d__6(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				string environmentVariable;
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					environmentVariable = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR");
					if (environmentVariable != null)
					{
						<>2__current = environmentVariable;
						<>1__state = 1;
						return true;
					}
					goto IL_0053;
				case 1:
					<>1__state = -1;
					goto IL_0053;
				case 2:
					<>1__state = -1;
					goto IL_0078;
				case 3:
					<>1__state = -1;
					goto IL_009d;
				case 4:
					<>1__state = -1;
					goto IL_00c2;
				case 5:
					{
						<>1__state = -1;
						return false;
					}
					IL_009d:
					environmentVariable = Environment.GetEnvironmentVariable("TEMP");
					if (environmentVariable != null)
					{
						<>2__current = environmentVariable;
						<>1__state = 4;
						return true;
					}
					goto IL_00c2;
					IL_0053:
					environmentVariable = Environment.GetEnvironmentVariable("TMPDIR");
					if (environmentVariable != null)
					{
						<>2__current = environmentVariable;
						<>1__state = 2;
						return true;
					}
					goto IL_0078;
					IL_0078:
					environmentVariable = Environment.GetEnvironmentVariable("TMP");
					if (environmentVariable != null)
					{
						<>2__current = environmentVariable;
						<>1__state = 3;
						return true;
					}
					goto IL_009d;
					IL_00c2:
					<>2__current = "/temp";
					<>1__state = 5;
					return true;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			IEnumerator<string> IEnumerable<string>.GetEnumerator()
			{
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					return this;
				}
				return new <TemporaryDirectories>d__6(0);
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<string>)this).GetEnumerator();
			}
		}

		private const string DiscordPipePrefix = "discord-ipc-";

		private const int MaximumPipeVariations = 10;

		private static readonly string[] LinuxPackageManagers = new string[3] { "app/com.discordapp.Discord/", "snap.discord/", ".flatpak/dev.vencord.Vesktop/xdg-run" };

		public static IEnumerable<string> GetPipes(int startPipe = 0)
		{
			IsOSUnix();
			if (IsOSUnix())
			{
				return Enumerable.Range(startPipe, 10).SelectMany(GetUnixPipes);
			}
			return Enumerable.Range(startPipe, 10).SelectMany(GetWindowsPipes);
		}

		[IteratorStateMachine(typeof(<GetWindowsPipes>d__4))]
		private static IEnumerable<string> GetWindowsPipes(int index)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <GetWindowsPipes>d__4(-2)
			{
				<>3__index = index
			};
		}

		[IteratorStateMachine(typeof(<GetUnixPipes>d__5))]
		private static IEnumerable<string> GetUnixPipes(int index)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <GetUnixPipes>d__5(-2)
			{
				<>3__index = index
			};
		}

		[IteratorStateMachine(typeof(<TemporaryDirectories>d__6))]
		private static IEnumerable<string> TemporaryDirectories()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <TemporaryDirectories>d__6(-2);
		}

		private static bool IsOSUnix()
		{
			if (Environment.OSVersion.Platform == PlatformID.Unix)
			{
				return true;
			}
			return false;
		}
	}
}
namespace DiscordRPC.Helper
{
	internal class BackoffDelay
	{
		private int _current;

		private int _fails;

		public int Maximum { get; private set; }

		public int Minimum { get; private set; }

		public int Current => _current;

		public int Fails => _fails;

		public Random Random { get; set; }

		private BackoffDelay()
		{
		}

		public BackoffDelay(int min, int max)
			: this(min, max, new Random())
		{
		}

		public BackoffDelay(int min, int max, Random random)
		{
			Minimum = min;
			Maximum = max;
			_current = min;
			_fails = 0;
			Random = random;
		}

		public void Reset()
		{
			_fails = 0;
			_current = Minimum;
		}

		public int NextDelay()
		{
			_fails++;
			double num = (float)(Maximum - Minimum) / 100f;
			_current = (int)Math.Floor(num * (double)_fails) + Minimum;
			return Math.Min(Math.Max(_current, Minimum), Maximum);
		}
	}
	public static class StringTools
	{
		public static string GetNullOrString(this string str)
		{
			if (str.Length != 0 && !string.IsNullOrEmpty(str.Trim()))
			{
				return str;
			}
			return null;
		}

		public static bool WithinLength(this string str, int bytes)
		{
			return str.WithinLength(bytes, Encoding.UTF8);
		}

		public static bool WithinLength(this string str, int bytes, Encoding encoding)
		{
			return encoding.GetByteCount(str) <= bytes;
		}

		public static string ToCamelCase(this string str)
		{
			return (from s in str?.ToLowerInvariant().Split(new string[2] { "_", " " }, StringSplitOptions.RemoveEmptyEntries)
				select char.ToUpper(s[0]) + s.Substring(1, s.Length - 1)).Aggregate(string.Empty, (string s1, string s2) => s1 + s2);
		}

		public static string ToSnakeCase(this string str)
		{
			if (str == null)
			{
				return null;
			}
			return string.Concat(str.Select((char x, int i) => (i <= 0 || !char.IsUpper(x)) ? x.ToString() : ("_" + x)).ToArray()).ToUpperInvariant();
		}
	}
}
namespace DiscordRPC.Exceptions
{
	public class BadPresenceException : Exception
	{
		internal BadPresenceException(string message)
			: base(message)
		{
		}
	}
	public class InvalidConfigurationException : Exception
	{
		internal InvalidConfigurationException(string message)
			: base(message)
		{
		}
	}
	[Obsolete("Not actually used anywhere")]
	public class InvalidPipeException : Exception
	{
		internal InvalidPipeException(string message)
			: base(message)
		{
		}
	}
	public class StringOutOfRangeException : Exception
	{
		public int MaximumLength { get; private set; }

		public int MinimumLength { get; private set; }

		internal StringOutOfRangeException(string message, int min, int max)
			: base(message)
		{
			MinimumLength = min;
			MaximumLength = max;
		}

		internal StringOutOfRangeException(int minumum, int max)
			: this($"Length of string is out of range. Expected a value between {minumum} and {max}", minumum, max)
		{
		}

		internal StringOutOfRangeException(int max)
			: this($"Length of string is out of range. Expected a value with a maximum length of {max}", 0, max)
		{
		}
	}
	public class UninitializedException : Exception
	{
		internal UninitializedException(string message)
			: base(message)
		{
		}

		internal UninitializedException()
			: this("Cannot perform action because the client has not been initialized yet or has been deinitialized.")
		{
		}
	}
}
namespace DiscordRPC.Events
{
	public delegate void OnReadyEvent(object sender, ReadyMessage args);

patchers/PAMultiplayer.Preloader/PAMultiplayer.Preloader.dll

Decompiled a month ago
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Mono.Cecil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("PAMultiplayer.Preloader")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+15808ff12e419599d5a33d0fe917d1cb5f77d9f0")]
[assembly: AssemblyProduct("PAMultiplayer.Preloader")]
[assembly: AssemblyTitle("PAMultiplayer.Preloader")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace PAMultiplayer.Preloader;

public static class Patcher
{
	public static IEnumerable<string> TargetDLLs { get; } = new string[2] { "Facepunch.Steamworks.Win64.dll", "DiscordRPC.dll" };

	public static void Patch(ref AssemblyDefinition assembly)
	{
		if (((AssemblyNameReference)assembly.Name).Name == "DiscordRPC")
		{
			assembly = AssemblyDefinition.ReadAssembly(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\DiscordRPC.dll");
		}
	}
}

plugins/PAMultiplayer/PAMultiplayer.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Threading.Tasks;
using Systems.SceneManagement;
using AttributeNetworkWrapperV2;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using Crosstales;
using DG.Tweening;
using DG.Tweening.Core;
using DG.Tweening.Plugins.Options;
using DiscordRPC;
using DiscordRPC.Events;
using DiscordRPC.IO;
using DiscordRPC.Logging;
using DiscordRPC.Message;
using EnhancedUI.EnhancedScroller;
using HarmonyLib;
using IEVO.UI.uGUIDirectedNavigation;
using Lachee.Discord;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using PAMultiplayer.AttributeNetworkWrapperOverrides;
using PAMultiplayer.Data;
using PAMultiplayer.Managers;
using PAMultiplayer.Patch;
using PAMultiplayer.UI;
using PaApi;
using Rewired;
using SimpleJSON;
using Steamworks;
using Steamworks.Data;
using Steamworks.Ugc;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Localization.PropertyVariants;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using VGFunctions;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("PAMultiplayer")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Multiplayer Mod")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+15808ff12e419599d5a33d0fe917d1cb5f77d9f0")]
[assembly: AssemblyProduct("PAMultiplayer")]
[assembly: AssemblyTitle("PAMultiplayer")]
[assembly: InternalsVisibleTo("AttributeNetworkWrapperV2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace AttributeNetworkWrapperV2
{
	public static class RpcFuncRegistersGenerated
	{
		static RpcFuncRegistersGenerated()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Expected O, but got Unknown
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Expected O, but got Unknown
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Expected O, but got Unknown
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Expected O, but got Unknown
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Expected O, but got Unknown
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Expected O, but got Unknown
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Expected O, but got Unknown
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Expected O, but got Unknown
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Expected O, but got Unknown
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Expected O, but got Unknown
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Expected O, but got Unknown
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Expected O, but got Unknown
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Expected O, but got Unknown
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Expected O, but got Unknown
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Expected O, but got Unknown
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Expected O, but got Unknown
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Expected O, but got Unknown
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Expected O, but got Unknown
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Expected O, but got Unknown
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_026d: Expected O, but got Unknown
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_0284: Expected O, but got Unknown
			//IL_0290: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Expected O, but got Unknown
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b2: Expected O, but got Unknown
			//IL_02be: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c9: Expected O, but got Unknown
			//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e0: Expected O, but got Unknown
			//IL_02ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Expected O, but got Unknown
			RpcHandler.RegisterRpc((ushort)58818, new RpcDelegate(PaMNetworkManager.Deserialize_Server_SendModVer_58818), (CallType)0);
			RpcHandler.RegisterRpc((ushort)34771, new RpcDelegate(ChallengeManager.Deserialize_Server_UnknownLevelIds_34771), (CallType)0);
			RpcHandler.RegisterRpc((ushort)7811, new RpcDelegate(VoterCell.Deserialize_Server_LevelVoted_7811), (CallType)0);
			RpcHandler.RegisterRpc((ushort)65336, new RpcDelegate(NetworkManager.Deserialize_Server_PlayerPos_65336), (CallType)0);
			RpcHandler.RegisterRpc((ushort)28267, new RpcDelegate(PointsManager.Deserialize_Client_SendResults_28267), (CallType)0);
			RpcHandler.RegisterRpc((ushort)40931, new RpcDelegate(DebugControllerPatch.Deserialize_Server_AddQueueLevel_40931), (CallType)0);
			RpcHandler.RegisterRpc((ushort)34247, new RpcDelegate(GameManagerPatch.Deserialize_Server_RequestLobbyState_34247), (CallType)0);
			RpcHandler.RegisterRpc((ushort)23559, new RpcDelegate(PlayerPatch.Deserialize_Server_PlayerDamaged_23559), (CallType)0);
			RpcHandler.RegisterRpc((ushort)26403, new RpcDelegate(PlayerPatch.Deserialize_Server_PlayerBoost_26403), (CallType)0);
			RpcHandler.RegisterRpc((ushort)42018, new RpcDelegate(PaMNetworkManager.Deserialize_Client_RegisterPlayerId_42018), (CallType)1);
			RpcHandler.RegisterRpc((ushort)14931, new RpcDelegate(PaMNetworkManager.Deserialize_Client_SetMainLobbyData_14931), (CallType)1);
			RpcHandler.RegisterRpc((ushort)37620, new RpcDelegate(PaMNetworkManager.Deserialize_Client_AskForMod_37620), (CallType)1);
			RpcHandler.RegisterRpc((ushort)8766, new RpcDelegate(PaMNetworkManager.Deserialize_Client_MissingMod_8766), (CallType)1);
			RpcHandler.RegisterRpc((ushort)56878, new RpcDelegate(ChallengeManager.Deserialize_Client_AudioData_56878), (CallType)1);
			RpcHandler.RegisterRpc((ushort)11993, new RpcDelegate(GameManagerPatch.Deserialize_Client_LobbyState_11993), (CallType)1);
			RpcHandler.RegisterRpc((ushort)22680, new RpcDelegate(PaMNetworkManager.Deserialize_Multi_RegisterJoinedPlayerId_22680), (CallType)2);
			RpcHandler.RegisterRpc((ushort)54154, new RpcDelegate(PaMNetworkManager.Deserialize_Multi_UpdateLobbyState_54154), (CallType)2);
			RpcHandler.RegisterRpc((ushort)43472, new RpcDelegate(PaMNetworkManager.Deserialize_Multi_UpdateModifier_43472), (CallType)2);
			RpcHandler.RegisterRpc((ushort)18518, new RpcDelegate(PaMNetworkManager.Deserialize_Multi_PlayerLeft_18518), (CallType)2);
			RpcHandler.RegisterRpc((ushort)65375, new RpcDelegate(ChallengeManager.Deserialize_Multi_StartVoting_65375), (CallType)2);
			RpcHandler.RegisterRpc((ushort)27550, new RpcDelegate(ChallengeManager.Deserialize_Multi_VoteWinner_27550), (CallType)2);
			RpcHandler.RegisterRpc((ushort)47253, new RpcDelegate(ChallengeManager.Deserialize_Multi_CheckLevelIds_47253), (CallType)2);
			RpcHandler.RegisterRpc((ushort)13413, new RpcDelegate(NetworkManager.Deserialize_Multi_PlayerPos_13413), (CallType)2);
			RpcHandler.RegisterRpc((ushort)49432, new RpcDelegate(PointsManager.Deserialize_Multi_SetPlayerResults_49432), (CallType)2);
			RpcHandler.RegisterRpc((ushort)10245, new RpcDelegate(GameManagerPatch.Deserialize_Multi_LatePlayerJoin_10245), (CallType)2);
			RpcHandler.RegisterRpc((ushort)62198, new RpcDelegate(GameManagerPatch.Deserialize_Multi_NextQueueLevel_62198), (CallType)2);
			RpcHandler.RegisterRpc((ushort)65142, new RpcDelegate(GameManagerPatch.Deserialize_Multi_OpenChallenge_65142), (CallType)2);
			RpcHandler.RegisterRpc((ushort)33609, new RpcDelegate(PlayerPatch.Deserialize_Multi_PlayerDamaged_33609), (CallType)2);
			RpcHandler.RegisterRpc((ushort)43036, new RpcDelegate(PlayerPatch.Deserialize_Multi_DamageAll_43036), (CallType)2);
			RpcHandler.RegisterRpc((ushort)47954, new RpcDelegate(PlayerPatch.Deserialize_Multi_PlayerBoost_47954), (CallType)2);
			RpcHandler.RegisterRpc((ushort)16372, new RpcDelegate(CheckpointHandler.Deserialize_Multi_CheckpointHit_16372), (CallType)2);
			RpcHandler.RegisterRpc((ushort)11649, new RpcDelegate(RewindHandler.Deserialize_Multi_RewindToCheckpoint_11649), (CallType)2);
			RpcHandler.RegisterRpc((ushort)34174, new RpcDelegate(PauseLobbyPatch.Deserialize_Multi_StartLevel_34174), (CallType)2);
		}
	}
}
namespace PAMultiplayer
{
	public class CoroutineWrapper
	{
		public bool IsCompleted { get; private set; }

		public Coroutine Coroutine { get; private set; }

		public CoroutineWrapper(MonoBehaviour mb, IEnumerator coroutine)
		{
			Coroutine = mb.StartCoroutine(Wrapper(coroutine));
		}

		private IEnumerator Wrapper(IEnumerator coroutine)
		{
			IsCompleted = false;
			try
			{
				yield return coroutine;
			}
			finally
			{
				IsCompleted = true;
			}
		}
	}
	public static class MPUtility
	{
		private static List<VGLevel> _storyLevels;

		public static int StoryLevelCount => _storyLevels?.Count ?? 0;

		public static VGLevel LookForLevel(string levelID)
		{
			VGLevel val = GetStoryLevel(levelID);
			if (!Object.op_Implicit((Object)(object)val))
			{
				val = SingletonBase<ArcadeLevelDataManager>.Inst.GetLocalCustomLevel(levelID);
			}
			return val;
		}

		public static VGLevel GetStoryLevel(string id)
		{
			return _storyLevels?.FirstOrDefault((Func<VGLevel, bool>)((VGLevel x) => x.BaseLevelData.LevelID == id));
		}

		public static List<VGLevel> GetStoryLevels()
		{
			return _storyLevels;
		}

		public static bool IsStoryModeBeaten()
		{
			if (Object.op_Implicit((Object)(object)SingletonBase<SavesManager>.Inst))
			{
				return !string.IsNullOrEmpty(SingletonBase<SavesManager>.Inst.GetLastEndingId());
			}
			return false;
		}

		public static void SetFullTextGradient(TMP_TextInfo textInfo, Color32 colorLeft, Color32 colorRight)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			float num = float.MaxValue;
			float num2 = float.MinValue;
			for (int i = 0; i < textInfo.characterCount; i++)
			{
				if (textInfo.characterInfo[i].isVisible)
				{
					int materialReferenceIndex = textInfo.characterInfo[i].materialReferenceIndex;
					int vertexIndex = textInfo.characterInfo[i].vertexIndex;
					Vector3[] vertices = textInfo.meshInfo[materialReferenceIndex].vertices;
					float x = vertices[vertexIndex].x;
					num = Mathf.Min(num, x);
					x = vertices[vertexIndex + 2].x;
					num2 = Mathf.Max(num2, x);
				}
			}
			for (int j = 0; j < textInfo.characterCount; j++)
			{
				if (textInfo.characterInfo[j].isVisible)
				{
					int materialReferenceIndex2 = textInfo.characterInfo[j].materialReferenceIndex;
					int vertexIndex2 = textInfo.characterInfo[j].vertexIndex;
					Vector3[] vertices2 = textInfo.meshInfo[materialReferenceIndex2].vertices;
					Color32 val = Color32.Lerp(colorLeft, colorRight, Mathf.InverseLerp(num, num2, vertices2[vertexIndex2].x));
					Color32 val2 = Color32.Lerp(colorLeft, colorRight, Mathf.InverseLerp(num, num2, vertices2[vertexIndex2 + 2].x));
					Color32[] colors = textInfo.meshInfo[materialReferenceIndex2].colors32;
					colors[vertexIndex2] = val;
					colors[vertexIndex2 + 1] = val;
					colors[vertexIndex2 + 2] = val2;
					colors[vertexIndex2 + 3] = val2;
				}
			}
		}

		public static void ReleaseClip(AudioClip clip, bool baked = false)
		{
			if (LevelMusicLoader.Manager.IsPlaybackClip(clip))
			{
				AudioManager inst = SingletonBase<AudioManager>.Inst;
				if (inst != null)
				{
					inst.ReleaseMusicClip(clip);
				}
				LevelMusicLoader.playbackLevel.LevelMusic = null;
				LevelMusicLoader.Manager.ReleasePlayback();
			}
			else if (Object.op_Implicit((Object)(object)clip))
			{
				clip.UnloadAudioData();
				if (!baked)
				{
					Object.Destroy((Object)(object)clip);
				}
			}
		}

		public static void DelayLoadScene(string sceneId)
		{
			((MonoBehaviour)SystemManager.inst).StartCoroutine(InternalDelayLoadScene(sceneId));
		}

		private static IEnumerator InternalDelayLoadScene(string id)
		{
			if (Object.op_Implicit((Object)(object)SingletonBase<MultiplayerUIManager>.Inst) && SingletonBase<MultiplayerUIManager>.Inst.IsActive)
			{
				SingletonBase<MultiplayerUIManager>.Inst.CloseUI();
			}
			yield return (object)new WaitUntil((Func<bool>)(() => SingletonBase<SceneLoader>.Inst.CanLoadSceneGroup));
			if (_storyLevels == null)
			{
				if (id != "Arcade")
				{
					LoadingTipsPatch.IgnoreArcade = true;
				}
				SingletonBase<SceneLoader>.Inst.LoadSceneGroup("Arcade");
				yield return (object)new WaitUntil((Func<bool>)(() => SingletonBase<SceneLoader>.Inst.CanLoadSceneGroup));
				_storyLevels = new List<VGLevel>();
				IEnumerable<VGLevel> collection = from x in Resources.FindObjectsOfTypeAll<VGLevel>()
					where x.IsBakedLevel
					select x;
				_storyLevels.AddRange(collection);
				if (id == "Arcade")
				{
					yield break;
				}
			}
			SingletonBase<SceneLoader>.Inst.LoadSceneGroup(id);
		}

		public static CoroutineWrapper WrapCoroutine(this MonoBehaviour mb, IEnumerator coroutine)
		{
			return new CoroutineWrapper(mb, coroutine);
		}

		public static WaitUntil WaitUntilComplete(this Task task)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			return new WaitUntil((Func<bool>)(() => task.IsCompleted));
		}
	}
	[BepInPlugin("me.ytarame.Multiplayer", "Multiplayer", "1.4.2")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class PAM : BaseUnityPlugin
	{
		internal static ManualLogSource Logger;

		private Harmony _harmony;

		public const string Guid = "me.ytarame.Multiplayer";

		private const string Name = "Multiplayer";

		public const string Version = "1.4.2";

		internal static GameObject ErrorScreenPrefab { get; private set; }

		internal static GameObject LobbyScreenPrefab { get; private set; }

		internal static GameObject LobbyPlayerEntryPrefab { get; private set; }

		internal static GameObject LobbyQueueEntryPrefab { get; private set; }

		internal static GameObject QueueIconPrefab { get; private set; }

		private void Awake()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			Logger = ((BaseUnityPlugin)this).Logger;
			_harmony = new Harmony("me.ytarame.Multiplayer");
			_harmony.PatchAll();
			Settings.Initialize(((BaseUnityPlugin)this).Config);
			using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("PAMultiplayer.Assets.lobbymenuv2"))
			{
				AssetBundle obj = AssetBundle.LoadFromMemory(ExtensionMethods.CTReadFully(stream));
				Object obj2 = obj.LoadAsset(obj.GetAllAssetNames()[0]);
				ErrorScreenPrefab = (GameObject)(object)((obj2 is GameObject) ? obj2 : null);
				Object obj3 = obj.LoadAsset(obj.GetAllAssetNames()[2]);
				LobbyScreenPrefab = (GameObject)(object)((obj3 is GameObject) ? obj3 : null);
				Object obj4 = obj.LoadAsset(obj.GetAllAssetNames()[3]);
				LobbyPlayerEntryPrefab = (GameObject)(object)((obj4 is GameObject) ? obj4 : null);
				Object obj5 = obj.LoadAsset(obj.GetAllAssetNames()[4]);
				LobbyQueueEntryPrefab = (GameObject)(object)((obj5 is GameObject) ? obj5 : null);
				obj.Unload(false);
			}
			SettingsHelper.RegisterModSettings("me.ytarame.Multiplayer", "Multiplayer", (Color?)Color.red, ((BaseUnityPlugin)this).Config, (Action<SettingsBuilder>)delegate(SettingsBuilder builder)
			{
				builder.Label("<b>TRANSPARENT NANOS</b> - and related settings");
				builder.Toggle("Transparent Nanos", "Remote players are transparent", "Remote players are opaque", Settings.Transparent, (Action<bool>)null);
				builder.Slider("Transparent Opacity", Settings.TransparentAlpha, (VisualType)1, new string[3] { "35%", "50%", "85%" });
				builder.Spacer();
				builder.Label("<b>MISCELLANEOUS</b> - other settings");
				builder.Slider("No Repeats in Challenge", Settings.NoRepeat, (VisualType)1, new string[5] { "0 Rounds", "1 Round", "2 Rounds", "3 Rounds", "Infinite" });
				builder.Toggle("Chat Enabled", "Chat appears above their nano and terminal", "Player chat is not shown", Settings.Chat, (Action<bool>)null);
				builder.Toggle("Disable Rich Text", "Chat Rich text enabled", "Chat rich text disabled", Settings.DisableRichText, (Action<bool>)null);
				builder.Toggle("Linked Health Hit Popup", "Popup for which player caused the hit", "No popup appears", Settings.Linked, (Action<bool>)null);
				builder.Toggle("Allow hidden workshop levels", "Non public levels are allowed", "Only public are allowed", Settings.AllowNonPublicLevels, (Action<bool>)null);
			});
			using (Stream stream2 = Assembly.GetExecutingAssembly().GetManifestResourceStream("PAMultiplayer.Assets.challenge"))
			{
				string text = AssetBundle.LoadFromMemory(ExtensionMethods.CTReadFully(stream2)).GetAllScenePaths()[0];
				SceneHelpers.AddNewSceneGroup<ChallengeManager>("Challenge", text, (SceneGroupType)4);
			}
			using (Stream stream3 = Assembly.GetExecutingAssembly().GetManifestResourceStream("PAMultiplayer.Assets.queue assets"))
			{
				AssetBundle obj6 = AssetBundle.LoadFromMemory(ExtensionMethods.CTReadFully(stream3));
				Object obj7 = obj6.LoadAsset(obj6.GetAllAssetNames()[0]);
				QueueIconPrefab = (GameObject)(object)((obj7 is GameObject) ? obj7 : null);
				obj6.Unload(false);
			}
			Logger.LogInfo((object)"Multiplayer 1.4.2 has loaded!");
		}
	}
	internal static class Settings
	{
		public static ConfigEntry<string> ChallengeBlacklist;

		public static ConfigEntry<int> WarpSfx { get; private set; }

		public static ConfigEntry<int> HitSfx { get; private set; }

		public static ConfigEntry<bool> Transparent { get; private set; }

		public static ConfigEntry<int> TransparentAlpha { get; private set; }

		public static ConfigEntry<int> NoRepeat { get; private set; }

		public static ConfigEntry<bool> Chat { get; private set; }

		public static ConfigEntry<bool> DisableRichText { get; private set; }

		public static ConfigEntry<bool> Linked { get; private set; }

		public static ConfigEntry<bool> AllowNonPublicLevels { get; private set; }

		public static ConfigEntry<int> Score { get; private set; }

		internal static void Initialize(ConfigFile config)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			//IL_0032: Expected O, but got Unknown
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Expected O, but got Unknown
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Expected O, but got Unknown
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Expected O, but got Unknown
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Expected O, but got Unknown
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Expected O, but got Unknown
			//IL_0159: Expected O, but got Unknown
			if (WarpSfx == null)
			{
				ChallengeBlacklist = config.Bind<string>(new ConfigDefinition("Challenge", "BlackList"), "", new ConfigDescription("List of level id's that are never chosen in challenge, separated by '/'. like id/id2/id3, no spaces", (AcceptableValueBase)null, Array.Empty<object>()));
				WarpSfx = config.Bind<int>(new ConfigDefinition("General", "Player Warp SFX"), 1, (ConfigDescription)null);
				HitSfx = config.Bind<int>(new ConfigDefinition("General", "Player Hit SFX"), 0, (ConfigDescription)null);
				Transparent = config.Bind<bool>(new ConfigDefinition("General", "Transparent Nanos"), true, (ConfigDescription)null);
				TransparentAlpha = config.Bind<int>(new ConfigDefinition("General", "Transparent Alpha"), 0, (ConfigDescription)null);
				NoRepeat = config.Bind<int>(new ConfigDefinition("General", "No Repeat"), 0, (ConfigDescription)null);
				Chat = config.Bind<bool>(new ConfigDefinition("General", "Chat Enabled"), true, (ConfigDescription)null);
				DisableRichText = config.Bind<bool>(new ConfigDefinition("General", "Disable Rich Text"), false, (ConfigDescription)null);
				Linked = config.Bind<bool>(new ConfigDefinition("General", "Linked Health Popup"), true, (ConfigDescription)null);
				AllowNonPublicLevels = config.Bind<bool>(new ConfigDefinition("General", "Allow Private Levels"), false, (ConfigDescription)null);
				Score = config.Bind<int>(new ConfigDefinition("General", "Score"), 0, new ConfigDescription("I know you're thinking about it, dont do it... be legitimate...", (AcceptableValueBase)null, Array.Empty<object>()));
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "PAMultiplayer";

		public const string PLUGIN_NAME = "PAMultiplayer";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace PAMultiplayer.UI
{
	public class ErrorScreen : MonoBehaviour
	{
		private UI_Menu _menu;

		private TextMeshProUGUI _text;

		private MultiElementButton _button;

		private string _errorMessage;

		private GameObject _last;

		public static void CreateErrorScreen(string errorMessage)
		{
			Transform parent = ((Component)SingletonBase<PauseUIManager>.Inst).transform.parent;
			GameObject obj = Object.Instantiate<GameObject>(PAM.ErrorScreenPrefab, parent);
			obj.transform.SetSiblingIndex(0);
			obj.AddComponent<ErrorScreen>()._errorMessage = errorMessage;
		}

		private void Start()
		{
			((TMP_Text)_text).text = _errorMessage;
			SingletonBase<UIStateManager>.Inst.RefreshTextCache(_text, _errorMessage);
			_last = EventSystem.current.currentSelectedGameObject;
			_menu.ShowBase();
			_menu.SwapView("main");
			((Selectable)((SerializableDictionary<string, UIView>)(object)_menu.AllViews)["main"].PossibleFirstButtons[0]).Select();
		}

		private void Awake()
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			_menu = ((Component)this).GetComponent<UI_Menu>();
			_text = ((Component)((Component)this).transform.Find("ErrorMessage")).GetComponent<TextMeshProUGUI>();
			_button = ((Component)((Component)this).transform.Find("Close/Close")).GetComponent<MultiElementButton>();
			((UnityEvent)((Button)_button).onClick).AddListener(new UnityAction(Close));
		}

		private void Close()
		{
			_menu.HideAll();
			Object.Destroy((Object)(object)((Component)this).gameObject, 1f);
			if (Object.op_Implicit((Object)(object)_last))
			{
				EventSystem.current.SetSelectedGameObject(_last);
			}
		}
	}
	public class QueueButton : MonoBehaviour
	{
		private delegate void QueueUpdated();

		private TextMeshProUGUI queueText;

		private string currentLevel = "";

		private string currentLevelName = "MISSING";

		private int queueIndex;

		public UI_Button UIQueueButton { get; private set; }

		private static event QueueUpdated _queueUpdated;

		private void Start()
		{
			_queueUpdated += UpdateButton;
		}

		private void OnDestroy()
		{
			_queueUpdated -= UpdateButton;
		}

		private void UpdateButton()
		{
			int num = GlobalsManager.Queue.IndexOfLevel(currentLevel) + 1;
			if (num > 0 && num != queueIndex)
			{
				queueIndex = num;
				((UIElement)UIQueueButton).Show((Action)null);
				((TMP_Text)queueText).text = num.ToString();
			}
		}

		public void OnClick()
		{
			if (GlobalsManager.Queue.ContainsLevel(currentLevel))
			{
				GlobalsManager.Queue.RemoveLevel(currentLevel);
				queueIndex = 0;
				((TMP_Text)queueText).text = "+";
				QueueButton._queueUpdated?.Invoke();
			}
			else
			{
				GlobalsManager.Queue.AddLevel(currentLevelName, currentLevel);
				queueIndex = GlobalsManager.Queue.Count;
				((TMP_Text)queueText).text = queueIndex.ToString();
			}
		}

		public void SetLevel(string levelId, string name)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			if ((Object)(object)UIQueueButton == (Object)null)
			{
				UIQueueButton = ((Component)this).gameObject.GetComponent<UI_Button>();
				queueText = ((Component)this).gameObject.GetComponentInChildren<TextMeshProUGUI>();
				((UnityEvent)((Button)((Component)UIQueueButton).GetComponent<MultiElementButton>()).onClick).AddListener(new UnityAction(OnClick));
			}
			UIQueueButton = ((Component)this).gameObject.GetComponent<UI_Button>();
			((UIElement)UIQueueButton).Show((Action)null);
			currentLevel = levelId;
			currentLevelName = name;
			queueIndex = GlobalsManager.Queue.IndexOfLevel(levelId) + 1;
			((TMP_Text)queueText).text = ((queueIndex > 0) ? queueIndex.ToString() : "+");
		}
	}
}
namespace PAMultiplayer.Patch
{
	[HarmonyPatch(typeof(DebugController))]
	public static class DebugControllerPatch
	{
		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void PostAwake(DebugController __instance)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Expected O, but got Unknown
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Expected O, but got Unknown
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Expected O, but got Unknown
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Expected O, but got Unknown
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Expected O, but got Unknown
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Expected O, but got Unknown
			//IL_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Expected O, but got Unknown
			//IL_0355: Unknown result type (might be due to invalid IL or missing references)
			//IL_035c: Expected O, but got Unknown
			DebugCommand item = new DebugCommand("Ping", "Prints current ping (multiplayer mod, any)", (Action)delegate
			{
				if (!GlobalsManager.IsMultiplayer)
				{
					__instance.AddLog("-1 ms");
				}
				else
				{
					__instance.AddLog($"{PaMNetworkManager.PamInstance.GetPing()} ms");
				}
			});
			__instance.CommandList.Add(item);
			DebugCommand<int> item2 = new DebugCommand<int>("MPLeaderboard", "Top 10 leaderboard, page starts at 0 (multiplayer mod, any)", "int(page)", (Action<int>)async delegate(int page)
			{
				_ = 1;
				try
				{
					Leaderboard? val = await SteamUserStats.FindOrCreateLeaderboardAsync("MP_MOD_Points", (LeaderboardSort)2, (LeaderboardDisplay)1);
					if (!val.HasValue)
					{
						__instance.AddLog("Failed to get leaderboard");
					}
					else
					{
						Leaderboard value = val.Value;
						LeaderboardEntry[] array = await ((Leaderboard)(ref value)).GetScoresAsync(10, 1 + 10 * page);
						if (array == null)
						{
							__instance.AddLog("Failed to get leaderboard");
						}
						else
						{
							for (int i = 0; i < array.Length; i++)
							{
								LeaderboardEntry val2 = array[i];
								__instance.AddLog($"{val2.GlobalRank}. {((Friend)(ref val2.User)).Name} // {val2.Score}");
							}
						}
					}
				}
				catch (Exception ex)
				{
					PAM.Logger.LogError((object)ex);
				}
			});
			__instance.CommandList.Add(item2);
			DebugCommand item3 = new DebugCommand("MPFriendLeaderboard", "Top 10 friends only leaderboard, page starts at 0 (multiplayer mod, any)", (Action)async delegate
			{
				_ = 1;
				try
				{
					Leaderboard? val = await SteamUserStats.FindOrCreateLeaderboardAsync("MP_MOD_Points", (LeaderboardSort)2, (LeaderboardDisplay)1);
					if (!val.HasValue)
					{
						__instance.AddLog("Failed to get leaderboard");
					}
					else
					{
						Leaderboard value = val.Value;
						LeaderboardEntry[] array = await ((Leaderboard)(ref value)).GetScoresFromFriendsAsync();
						if (array == null)
						{
							__instance.AddLog("Failed to get leaderboard");
						}
						else
						{
							for (int i = 0; i < array.Length; i++)
							{
								LeaderboardEntry val2 = array[i];
								__instance.AddLog($"{val2.GlobalRank}. {((Friend)(ref val2.User)).Name} // {val2.Score}");
							}
						}
					}
				}
				catch (Exception ex)
				{
					PAM.Logger.LogError((object)ex);
				}
			});
			__instance.CommandList.Add(item3);
			DebugCommand item4 = new DebugCommand("SelfMPLeaderboard", "your leaderboard (multiplayer mod, any)", (Action)async delegate
			{
				_ = 1;
				try
				{
					Leaderboard? val = await SteamUserStats.FindOrCreateLeaderboardAsync("MP_MOD_Points", (LeaderboardSort)2, (LeaderboardDisplay)1);
					if (!val.HasValue)
					{
						__instance.AddLog("Failed to get leaderboard");
					}
					else
					{
						Leaderboard value = val.Value;
						LeaderboardEntry[] array = await ((Leaderboard)(ref value)).GetScoresAroundUserAsync(-5, 5);
						if (array == null)
						{
							__instance.AddLog("Failed to get leaderboard");
						}
						else
						{
							for (int i = 0; i < array.Length; i++)
							{
								LeaderboardEntry val2 = array[i];
								__instance.AddLog($"{val2.GlobalRank}. {((Friend)(ref val2.User)).Name} // {val2.Score}");
							}
						}
					}
				}
				catch (Exception ex)
				{
					PAM.Logger.LogError((object)ex);
				}
			});
			__instance.CommandList.Add(item4);
			DebugCommand item5 = new DebugCommand("KillAll", "Kills all players (multiplayer mod, any)", (Action)delegate
			{
				if (GlobalsManager.IsMultiplayer)
				{
					if (GlobalsManager.IsHosting)
					{
						__instance.AddLog("Is host, Killing all players.");
						int num = 0;
						if (DataManager.inst.GetSettingEnum("ArcadeHealthMod", 0) <= 1)
						{
							num = SingletonBase<GameManager>.Inst.currentCheckpointIndex;
						}
						int index = num;
						PaMNetworkManager pamInstance = PaMNetworkManager.PamInstance;
						RewindHandler.CallRpc_Multi_RewindToCheckpoint(index, (pamInstance != null) ? (pamInstance.LobbyInfo.RewindCounter + 1) : 0u);
					}
					else
					{
						__instance.AddLog("Is client, Killing self only.");
						if (GlobalsManager.LocalPlayerObj.IsValidPlayer())
						{
							GlobalsManager.LocalPlayerObj.Health = 1;
							GlobalsManager.LocalPlayerObj.PlayerHit();
						}
					}
					return;
				}
				__instance.AddLog("Killing All Players.");
				foreach (VGPlayerData player in SingletonBase<VGPlayerManager>.Inst.players)
				{
					if (player.PlayerObject.IsValidPlayer())
					{
						player.PlayerObject.Health = 1;
						player.PlayerObject.PlayerHit();
					}
				}
			});
			__instance.CommandList.Add(item5);
			DebugCommand item6 = new DebugCommand("ForceDisconnect", "Disconnects you from the lobby (multiplayer mod, any)", (Action)delegate
			{
				__instance.AddLog("Attempting to disconnect from the lobby.");
				GlobalsManager.LocalPlayerObjectId = 0;
				SteamManager.Inst.DisconnectAll();
				GlobalsManager.Players.Clear();
			});
			__instance.CommandList.Add(item6);
			Action<string> action = delegate(string message)
			{
				__instance.OnToggleDebug();
				if (!GlobalsManager.IsMultiplayer)
				{
					__instance.AddLog("Not currently in a lobby.");
				}
				else
				{
					PAM.Logger.LogInfo((object)("Sending message: [" + message + "]"));
					if (message.Length > 25)
					{
						PAM.Logger.LogInfo((object)"Message is longer than 25 characters. Cutting message.");
						message = message.Substring(0, 25);
					}
					((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SendChatString(message);
				}
			};
			DebugCommand<string> item7 = new DebugCommand<string>("chat", "Makes your Nano say something. (multiplayer mod, any)", "string(message)", action);
			__instance.CommandList.Add(item7);
			DebugCommand<string> item8 = new DebugCommand<string>("c", "Same as Chat (multiplayer mod, any)", "string(message)", action);
			__instance.CommandList.Add(item8);
			DebugCommand<string> item9 = new DebugCommand<string>("AddQueue", "Adds a level to the queue, the level has to be downloaded. (multiplayer mod, any)", "string(level_id)", (Action<string>)delegate(string levelId)
			{
				ulong result2;
				if (GlobalsManager.IsMultiplayer && !GlobalsManager.IsHosting)
				{
					PaMNetworkManager pamInstance = PaMNetworkManager.PamInstance;
					ulong result;
					if (pamInstance != null && !pamInstance.LobbyInfo.AllowClientLevels)
					{
						__instance.AddLog("This lobby does not allow clients to add levels");
						ErrorScreen.CreateErrorScreen("This lobby does not allow clients to add levels to the Queue.");
					}
					else if (ulong.TryParse(levelId, out result))
					{
						CallRpc_Server_AddQueueLevel(result);
						__instance.AddLog("Requesting queue level to server");
					}
					else
					{
						__instance.AddLog("Clients can only pass ulong level ids");
					}
				}
				else if (!AddLevelToQueue(levelId.Trim()) && ulong.TryParse(levelId, out result2))
				{
					((MonoBehaviour)__instance).StartCoroutine(AddWorkshopLevelToQueue(result2));
				}
			});
			__instance.CommandList.Add(item9);
			DebugCommand<int> item10 = new DebugCommand<int>("RemoveQueue", "Removes a level from the queue (multiplayer mod, host)", "int(index)", (Action<int>)delegate(int index)
			{
				if ((!GlobalsManager.IsMultiplayer || GlobalsManager.IsHosting) && index >= 0 && GlobalsManager.Queue.Count > index)
				{
					GlobalsManager.Queue.RemoveLevelAt(index);
					GlobalsManager.Queue.InsertLevel(SingletonBase<ArcadeManager>.Inst.CurrentArcadeLevel.TrackName, SingletonBase<ArcadeManager>.Inst.CurrentArcadeLevel.BaseLevelData.LevelID);
					DebugController.inst.AddLog($"removing the [{index}] level from the queue.");
					((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SetData("LevelQueue", JsonConvert.SerializeObject((object)GlobalsManager.Queue.GetQueueLevelNames()));
					GlobalsManager.Queue.RemoveLevelAt(0);
				}
			});
			__instance.CommandList.Add(item10);
			DebugCommand item11 = new DebugCommand("ToggleTransparency", "toggles Transparent Nanos. (multiplayer mod, any)", (Action)delegate
			{
				if (!GlobalsManager.IsMultiplayer)
				{
					__instance.AddLog("Not in multiplayer, not toggling transparency.");
				}
				else
				{
					bool flag = !Settings.Transparent.Value;
					Settings.Transparent.Value = flag;
					foreach (VGPlayerData player2 in SingletonBase<VGPlayerManager>.Inst.players)
					{
						if (player2.PlayerObject.IsValidPlayer() && !player2.PlayerObject.IsLocalPlayer())
						{
							foreach (PlayerTrailReference item20 in player2.PlayerObject.Player_Trail.Trail)
							{
								((Renderer)item20.Render_Trail).enabled = flag;
							}
						}
					}
					__instance.AddLog($"Toggle Transparency to [{flag}].");
				}
			});
			__instance.CommandList.Add(item11);
			DebugCommand item12 = new DebugCommand("ToggleLinked", "Toggles the modifier Linked Health. (multiplayer mod, host)", (Action)delegate
			{
				bool flag = !DataManager.inst.GetSettingBool("mp_linkedHealth", false);
				DataManager.inst.UpdateSettingBool("mp_linkedHealth", flag);
				if (GlobalsManager.IsMultiplayer)
				{
					((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SetData("LinkedMod", flag.ToString());
					PaMNetworkManager.CallRpc_Multi_UpdateModifier(2, flag ? ((byte)1) : ((byte)0));
				}
				__instance.AddLog($"Toggle Linked Health to [{flag}].");
			});
			__instance.CommandList.Add(item12);
			DebugCommand item13 = new DebugCommand("PlayerList", "shows all player ids. (multiplayer mod, any)", (Action)delegate
			{
				if (!GlobalsManager.IsMultiplayer)
				{
					__instance.AddLog("Not in multiplayer.");
					return;
				}
				__instance.AddLog("Showing all players.");
				if (GlobalsManager.IsHosting)
				{
					foreach (KeyValuePair<ulong, int> item21 in PaMNetworkManager.PamInstance.SteamIdToNetId)
					{
						__instance.AddLog($"ID [{item21.Value}], Name [{GlobalsManager.Players[item21.Key].Name}]");
					}
					return;
				}
				foreach (KeyValuePair<ulong, PlayerData> player3 in GlobalsManager.Players)
				{
					__instance.AddLog(player3.Value.Name);
				}
			});
			__instance.CommandList.Add(item13);
			DebugCommand<int> item14 = new DebugCommand<int>("Kick", "attempts to kick a player from the lobby. (multiplayer mod, host)", "int(player_id)", (Action<int>)delegate(int playerId)
			{
				if (!GlobalsManager.IsMultiplayer || !GlobalsManager.IsHosting)
				{
					__instance.AddLog("Not in multiplayer or not the host. not kicking player.");
				}
				else
				{
					((NetworkManager)PaMNetworkManager.PamInstance).KickClient(playerId);
					__instance.AddLog("Attempting to kick player from server.");
				}
			});
			__instance.CommandList.Add(item14);
			DebugCommand<string> item15 = new DebugCommand<string>("SetLobbyPrivacy", "set the lobby privacy setting. (multiplayer mod, host)", "bool(private)", (Action<string>)delegate(string isPrivateStr)
			{
				if (!bool.TryParse(isPrivateStr.ToLower(), out var result))
				{
					__instance.AddLog("Invalid parameter, pass \"true\" or \"false\".");
				}
				else if (!GlobalsManager.IsMultiplayer || !GlobalsManager.IsHosting)
				{
					__instance.AddLog("Not in multiplayer or not the host.");
				}
				else if (result)
				{
					((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SetFriendsOnly();
					__instance.AddLog("Lobby was made private.");
				}
				else
				{
					((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SetPublic();
					__instance.AddLog("Lobby was made public.");
				}
			});
			__instance.CommandList.Add(item15);
			DebugCommand<int> item16 = new DebugCommand<int>("SetLobbySize", "attempts to change the lobby size. (multiplayer mod, host) | 1 - 4 players. | 2 - 8 players. | 3 - 12 players. | 4 - 16 players.", "int(player_count)", (Action<int>)delegate(int playerCount)
			{
				if (!GlobalsManager.IsMultiplayer || !GlobalsManager.IsHosting)
				{
					__instance.AddLog("Not in multiplayer or not the host.");
				}
				else
				{
					playerCount = Mathf.Clamp(playerCount * 4, 4, 16);
					if (((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).MemberCount < playerCount)
					{
						__instance.AddLog("Tried to set lobby size to less than the lobby player count.");
					}
					else
					{
						((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).MaxMembers = playerCount;
						LobbyCreationManager.Instance.PlayerCount = playerCount;
						__instance.AddLog($"Set lobby max players to [{playerCount}]");
					}
				}
			});
			__instance.CommandList.Add(item16);
			DebugCommand item17 = new DebugCommand("DebugErrorScreen", "Creates a error screen. (multiplayer mod, any)", (Action)delegate
			{
				ErrorScreen.CreateErrorScreen("Test error Screen, Test error message.\n\nFun fact: I have no idea what I am doing anymore");
			});
			__instance.CommandList.Add(item17);
			DebugCommand<int> item18 = new DebugCommand<int>("DebugPacketLoss", "sets packet loss 0-100. (multiplayer mod, any)", "int(loss%)", (Action<int>)delegate(int loss)
			{
				SteamNetworkingUtils.FakeRecvPacketLoss = loss;
				SteamNetworkingUtils.FakeSendPacketLoss = loss;
			});
			__instance.CommandList.Add(item18);
			DebugCommand<int> item19 = new DebugCommand<int>("DebugSetPacketDelay", "sets delay on packets. (multiplayer mod, any)", "int(ms delay)", (Action<int>)delegate(int ms)
			{
				SteamNetworkingUtils.FakeRecvPacketLag = ms;
				SteamNetworkingUtils.FakeSendPacketLag = ms;
			});
			__instance.CommandList.Add(item19);
		}

		private static bool AddLevelToQueue(string id)
		{
			VGLevel val = MPUtility.LookForLevel(id);
			if (Object.op_Implicit((Object)(object)val))
			{
				GlobalsManager.Queue.InsertLevel(SingletonBase<ArcadeManager>.Inst.CurrentArcadeLevel.TrackName, SingletonBase<ArcadeManager>.Inst.CurrentArcadeLevel.BaseLevelData.LevelID);
				GlobalsManager.Queue.AddLevel(val.TrackName, id);
				DebugController.inst.AddLog("Adding level with id [" + id + "] to queue.");
				((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SetData("LevelQueue", JsonConvert.SerializeObject((object)GlobalsManager.Queue.GetQueueLevelNames()));
				GlobalsManager.Queue.RemoveLevelAt(0);
				return true;
			}
			DebugController.inst.AddLog("Level with id [" + id + "] wasn't found downloaded.");
			return false;
		}

		private static IEnumerator AddWorkshopLevelToQueue(ulong id)
		{
			Task<SteamWorkshopLevel?> task = SteamManager.GetSteamLevel(id);
			while (!task.IsCompleted)
			{
				yield return (object)new WaitForUpdate();
			}
			SteamWorkshopLevel? result = task.Result;
			bool flag = !result.HasValue || result.Value.Visibility == SteamWorkshopLevel.VisibilityType.Private;
			if (!flag)
			{
				SteamWorkshopLevel.VisibilityType visibility = result.Value.Visibility;
				bool flag2 = (uint)(visibility - 1) <= 1u;
				flag = flag2 && !Settings.AllowNonPublicLevels.Value;
			}
			if (flag)
			{
				PAM.Logger.LogWarning((object)$"Client tried to add disallowed level [{id}]");
				yield break;
			}
			GlobalsManager.Queue.InsertLevel(SingletonBase<ArcadeManager>.Inst.CurrentArcadeLevel.TrackName, SingletonBase<ArcadeManager>.Inst.CurrentArcadeLevel.BaseLevelData.LevelID);
			LevelQueue queue = GlobalsManager.Queue;
			SteamWorkshopLevel value = result.Value;
			queue.AddLevel(((Item)(ref value.LevelItem)).Title, id.ToString());
			DebugController.inst.AddLog($"Adding level with id [{id}] to queue.");
			((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SetData("LevelQueue", JsonConvert.SerializeObject((object)GlobalsManager.Queue.GetQueueLevelNames()));
			GlobalsManager.Queue.RemoveLevelAt(0);
		}

		[ServerRpc(/*Could not decode attribute arguments.*/)]
		private static void Server_AddQueueLevel(ClientNetworkConnection conn, ulong levelId)
		{
			if (LobbyCreationManager.Instance.AllowClientLevels)
			{
				if (!AddLevelToQueue(levelId.ToString()))
				{
					((MonoBehaviour)DebugController.inst).StartCoroutine(AddWorkshopLevelToQueue(levelId));
				}
			}
			else
			{
				DebugController.inst.AddLog($"player {((NetworkConnection)conn).Address} tried to request level {levelId} but its disallowed.");
			}
		}

		[HarmonyPatch("HandleInput")]
		[HarmonyPrefix]
		private static void PreHandleInput(ref string _input)
		{
			if (_input.Length >= 5 && _input.ToLower().Substring(0, 5) == "chat ")
			{
				_input = "chat " + _input.Substring(5).Replace(' ', '_');
			}
			if (_input.Length >= 2 && _input.ToLower().Substring(0, 2) == "c ")
			{
				_input = "c " + _input.Substring(2).Replace(' ', '_');
			}
		}

		private static void CallRpc_Server_AddQueueLevel(ulong levelId)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			if (NetworkManager.Instance == null)
			{
				return;
			}
			if (NetworkManager.Instance.PeerServer)
			{
				Server_AddQueueLevel(NetworkManager.Instance.ServerSelfPeerConnection, levelId);
				return;
			}
			NetworkWriter val = new NetworkWriter();
			try
			{
				NetWriterExtensions.Write(val, (ushort)40931);
				NetWriterExtensions.Write(val, levelId);
				NetworkManager.Instance.SendToServer(val.GetData(), (SendType)0);
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		internal static void Deserialize_Server_AddQueueLevel_40931(ClientNetworkConnection senderConn, NetworkReader reader)
		{
			Server_AddQueueLevel(senderConn, NetReaderExtensions.ReadUInt64(reader));
		}
	}
	[HarmonyPatch(typeof(DiscordManager))]
	public static class DiscordManagerPatch
	{
		[HarmonyPatch("Awake")]
		[HarmonyPrefix]
		private static void stopPresence(DiscordManager __instance)
		{
			JsonConvert.DefaultSettings = null;
			((Component)__instance).gameObject.AddComponent<MultiplayerDiscordManager>();
			Object.Destroy((Object)(object)__instance);
		}
	}
	[HarmonyPatch(typeof(GameManager))]
	public class GameManagerPatch
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__1_0;

			public static Func<Task> <>9__1_1;

			public static Func<Task> <>9__1_2;

			public static Func<Task> <>9__1_3;

			public static Func<bool> <>9__11_1;

			public static Func<bool> <>9__11_2;

			public static Func<bool> <>9__11_9;

			public static Func<Task> <>9__11_8;

			public static Comparison<Checkpoint> <>9__11_0;

			internal void <PostStart>b__1_0()
			{
				if (GlobalsManager.IsChallenge)
				{
					SingletonBase<PauseUIManager>.Inst.CloseUI();
					if (GlobalsManager.IsMultiplayer)
					{
						SteamLobbyManager.Inst.UnloadAll();
					}
					if (GlobalsManager.IsMultiplayer && GlobalsManager.IsHosting)
					{
						CallRpc_Multi_OpenChallenge();
					}
					MPUtility.DelayLoadScene("Challenge");
				}
				else
				{
					SingletonBase<PauseUIManager>.Inst.CloseUI();
					if (GlobalsManager.IsMultiplayer)
					{
						SteamLobbyManager.Inst.UnloadAll();
					}
					GlobalsManager.PlayQueue(null);
				}
			}

			internal async Task <PostStart>b__1_1()
			{
				while (!SteamLobbyManager.Inst.InLobby)
				{
					await Task.Delay(100);
				}
			}

			internal async Task <PostStart>b__1_2()
			{
				while (true)
				{
					if (PaMNetworkManager.PamInstance != null)
					{
						NetworkManager instance = NetworkManager.Instance;
						if (instance == null || instance.TransportActive)
						{
							break;
						}
					}
					await Task.Delay(100);
				}
			}

			internal async Task <PostStart>b__1_3()
			{
				while (true)
				{
					PaMNetworkManager pamInstance = PaMNetworkManager.PamInstance;
					if (pamInstance != null && pamInstance.LobbyInfo.HasLoadedAllInfo)
					{
						break;
					}
					await Task.Delay(100);
				}
			}

			internal bool <CustomLoadGame>b__11_1()
			{
				return SteamLobbyManager.Inst.InLobby;
			}

			internal bool <CustomLoadGame>b__11_2()
			{
				return NetworkManager.Instance.TransportActive;
			}

			internal async Task <CustomLoadGame>b__11_8()
			{
				SimpleCoroutineAwaiter val = IEnumeratorAwaitExtensions.GetAwaiter(new WaitUntil((Func<bool>)(() => !GlobalsManager.IsDownloading)));
				if (!val.IsCompleted)
				{
					await val;
					object obj = default(object);
					val = (SimpleCoroutineAwaiter)obj;
				}
				val.GetResult();
			}

			internal bool <CustomLoadGame>b__11_9()
			{
				return !GlobalsManager.IsDownloading;
			}

			internal int <CustomLoadGame>b__11_0(Checkpoint x, Checkpoint y)
			{
				return x.time.CompareTo(y.time);
			}
		}

		private static bool paused;

		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		private static void PreStart(GameManager __instance)
		{
			if (Object.op_Implicit((Object)(object)SingletonBase<StoryLevelLoader>.Inst))
			{
				__instance.IsArcade = SingletonBase<StoryLevelLoader>.Inst.IsArcade;
			}
			else
			{
				__instance.IsArcade = true;
			}
		}

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void PostStart(ref GameManager __instance)
		{
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Expected O, but got Unknown
			//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_00fe: Expected O, but got Unknown
			if (!__instance.IsArcade)
			{
				return;
			}
			Transform val = ((Component)SingletonBase<PauseUIManager>.Inst).transform.Find("sizer/Pause Menu");
			Transform val2 = val.Find("Restart");
			Transform val3 = val.Find("Skip Queue Level");
			if (!Object.op_Implicit((Object)(object)val3))
			{
				val3 = Object.Instantiate<Transform>(val2, val);
				((Object)val3).name = "Skip Queue Level";
				val3.SetSiblingIndex(2);
				SingletonBase<UIStateManager>.Inst.RefreshTextCache(((Component)val3.Find("Title Wrapper/Title")).GetComponent<TextMeshProUGUI>(), "Skip Level");
				SingletonBase<UIStateManager>.Inst.RefreshTextCache(((Component)val3.Find("Content/Text")).GetComponent<TextMeshProUGUI>(), "Skips the current level in queue");
				((SerializableDictionary<string, UIView>)(object)SingletonBase<PauseUIManager>.Inst.PauseMenu.AllViews)["main"].Elements.Add((UIElement)(object)((Component)val3).GetComponent<UI_Button>());
			}
			MultiElementButton component = ((Component)val3).GetComponent<MultiElementButton>();
			component.UnlockUIButton();
			((Button)component).onClick = new ButtonClickedEvent();
			ButtonClickedEvent onClick = ((Button)component).onClick;
			object obj = <>c.<>9__1_0;
			if (obj == null)
			{
				UnityAction val4 = delegate
				{
					if (GlobalsManager.IsChallenge)
					{
						SingletonBase<PauseUIManager>.Inst.CloseUI();
						if (GlobalsManager.IsMultiplayer)
						{
							SteamLobbyManager.Inst.UnloadAll();
						}
						if (GlobalsManager.IsMultiplayer && GlobalsManager.IsHosting)
						{
							CallRpc_Multi_OpenChallenge();
						}
						MPUtility.DelayLoadScene("Challenge");
					}
					else
					{
						SingletonBase<PauseUIManager>.Inst.CloseUI();
						if (GlobalsManager.IsMultiplayer)
						{
							SteamLobbyManager.Inst.UnloadAll();
						}
						GlobalsManager.PlayQueue(null);
					}
				};
				<>c.<>9__1_0 = val4;
				obj = (object)val4;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj);
			DirectedNavigation component2 = ((Component)val3).GetComponent<DirectedNavigation>();
			if (Object.op_Implicit((Object)(object)component2))
			{
				component2.ConfigUp.Type = (Value)1;
			}
			((Component)__instance).gameObject.AddComponent<PointsManager>();
			if (!GlobalsManager.IsMultiplayer)
			{
				((Component)val2).gameObject.SetActive(true);
				return;
			}
			((Component)val2).gameObject.SetActive(false);
			GlobalsManager.HitsQueue.Clear();
			((Component)__instance).gameObject.AddComponent<NetworkManager>();
			if (GlobalsManager.IsHosting)
			{
				SingletonBase<SceneLoader>.Inst.manager.AddToLoadingTasks("Creating Lobby", Task.Run(async delegate
				{
					while (!SteamLobbyManager.Inst.InLobby)
					{
						await Task.Delay(100);
					}
				}), (string)null, (string)null, (Func<string>)null);
				return;
			}
			SingletonBase<SceneLoader>.Inst.manager.AddToLoadingTasks("Connecting to Server", Task.Run(async delegate
			{
				while (true)
				{
					if (PaMNetworkManager.PamInstance != null)
					{
						NetworkManager instance = NetworkManager.Instance;
						if (instance == null || instance.TransportActive)
						{
							break;
						}
					}
					await Task.Delay(100);
				}
			}), (string)null, (string)null, (Func<string>)null);
			SingletonBase<SceneLoader>.Inst.manager.AddToLoadingTasks("Server Info", Task.Run(async delegate
			{
				while (true)
				{
					PaMNetworkManager pamInstance = PaMNetworkManager.PamInstance;
					if (pamInstance != null && pamInstance.LobbyInfo.HasLoadedAllInfo)
					{
						break;
					}
					await Task.Delay(100);
				}
			}), (string)null, (string)null, (Func<string>)null);
			((Component)val3).gameObject.SetActive(false);
		}

		[HarmonyPatch("OnDestroy")]
		[HarmonyPostfix]
		private static void PostDestroy()
		{
			GlobalsManager.HitsQueue.Clear();
			for (int i = 0; i < SingletonBase<CameraDB>.Inst.CameraParentedRoot.childCount; i++)
			{
				Object.Destroy((Object)(object)((Component)SingletonBase<CameraDB>.Inst.CameraParentedRoot.GetChild(i)).gameObject);
			}
			if (MultiplayerDiscordManager.IsInitialized)
			{
				MultiplayerDiscordManager.Instance.SetMenuPresence();
			}
		}

		private static IEnumerator FetchExternalData()
		{
			UnityWebRequest webRequest = UnityWebRequest.Get("https://raw.githubusercontent.com/aiden-ytarame/PAMultiplayer/master/ColoredNames.json");
			yield return webRequest.SendWebRequest();
			if ((int)webRequest.result != 1)
			{
				PAM.Logger.LogError((object)"Failed to fetch external data :(");
				yield break;
			}
			JSONNode obj = JSON.Parse(webRequest.downloadHandler.text);
			LobbyScreenManager.SpecialColors.Clear();
			Enumerator enumerator = obj.GetEnumerator();
			Color val = default(Color);
			Color val2 = default(Color);
			while (((Enumerator)(ref enumerator)).MoveNext())
			{
				KeyValuePair<string, JSONNode> current = ((Enumerator)(ref enumerator)).Current;
				if (!ulong.TryParse(current.Key, out var result) || !current.Value.HasKey("color"))
				{
					continue;
				}
				string text = JSONNode.op_Implicit(current.Value["color"]);
				string text2 = JSONNode.op_Implicit(current.Value["color2"]);
				if (!string.IsNullOrEmpty(text) && ColorUtility.TryParseHtmlString("#" + text, ref val))
				{
					PAM.Logger.LogInfo((object)("Loaded custom color for " + current.Value["name"].Value));
					if (!string.IsNullOrEmpty(text2) && ColorUtility.TryParseHtmlString("#" + text2, ref val2))
					{
						LobbyScreenManager.SpecialColors.Add(result, (Color[])(object)new Color[2] { val, val2 });
					}
					else
					{
						LobbyScreenManager.SpecialColors.Add(result, (Color[])(object)new Color[1] { val });
					}
				}
			}
			if (Object.op_Implicit((Object)(object)LobbyScreenManager.Instance))
			{
				LobbyScreenManager.Instance.SpecialColorsUpdated();
			}
		}

		[HarmonyPatch("Pause")]
		[HarmonyPrefix]
		private static bool PrePause(ref GameManager __instance, bool _showUI)
		{
			if (!GlobalsManager.IsMultiplayer)
			{
				return true;
			}
			PaMNetworkManager pamInstance = PaMNetworkManager.PamInstance;
			if (pamInstance == null || !pamInstance.LobbyInfo.HasStarted)
			{
				return true;
			}
			if (paused)
			{
				__instance.UnPause();
				paused = false;
				return false;
			}
			__instance.Paused = false;
			paused = true;
			return false;
		}

		[HarmonyPatch("UnPause")]
		[HarmonyPostfix]
		private static void PostUnPause()
		{
			if (GlobalsManager.IsMultiplayer)
			{
				paused = false;
			}
		}

		[HarmonyPatch("PlayGame")]
		[HarmonyPostfix]
		private static void PostPlay(GameManager __instance)
		{
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Expected O, but got Unknown
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: Unknown result type (might be due to invalid IL or missing references)
			GlobalsManager.Queue.RemoveLevel(GlobalsManager.LevelId);
			if (!GlobalsManager.IsMultiplayer)
			{
				if (MultiplayerDiscordManager.IsInitialized)
				{
					if (SingletonBase<GameManager>.Inst.IsEditor)
					{
						MultiplayerDiscordManager.Instance.SetLevelPresence("Editing " + SingletonBase<GameManager>.Inst.TrackName, "", "palogo");
					}
					else if (!__instance.IsArcade)
					{
						MultiplayerDiscordManager.Instance.SetLevelPresence("Playing Story Mode!", SingletonBase<GameManager>.Inst.TrackName + " by " + SingletonBase<GameManager>.Inst.ArtistName, "palogo");
					}
					else
					{
						setupLevelPresence("Playing Singleplayer!");
					}
				}
				return;
			}
			PaMNetworkManager pamInstance = PaMNetworkManager.PamInstance;
			if (pamInstance == null || pamInstance.LobbyInfo.LobbyState != SteamLobbyManager.LobbyState.Playing)
			{
				__instance.Pause(false);
				__instance.Paused = true;
				((Component)__instance).gameObject.AddComponent<LobbyScreenManager>();
			}
			else
			{
				__instance.Pause(false);
				__instance.Paused = true;
				PaMNetworkManager pamInstance2 = PaMNetworkManager.PamInstance;
				if (pamInstance2 != null)
				{
					pamInstance2.LobbyInfo.HasStarted = true;
				}
			}
			EventManager.inst.HasJiggle = false;
			foreach (VGPlayerData player in SingletonBase<VGPlayerManager>.Inst.players)
			{
				VGPlayer playerObject = player.PlayerObject;
				if (playerObject != null)
				{
					playerObject.PlayerDeath(0f);
				}
			}
			SingletonBase<VGPlayerManager>.Inst.players.Clear();
			if (GlobalsManager.IsHosting)
			{
				if (!GlobalsManager.Players.ContainsKey(SteamId.op_Implicit(GlobalsManager.LocalPlayerId)))
				{
					VGPlayerData vgPlayerData = new VGPlayerData
					{
						PlayerID = 0,
						ControllerID = 0
					};
					GlobalsManager.Players.TryAdd(SteamId.op_Implicit(GlobalsManager.LocalPlayerId), new PlayerData(vgPlayerData, SteamClient.Name));
				}
				foreach (KeyValuePair<ulong, PlayerData> player2 in GlobalsManager.Players)
				{
					SingletonBase<VGPlayerManager>.Inst.players.Add(player2.Value.VGPlayerData);
				}
				((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SetMemberData("IsLoaded", "1");
			}
			else
			{
				if (NetworkManager.Instance == null)
				{
					SingletonBase<SceneLoader>.Inst.manager.ClearLoadingTasks();
					MPUtility.DelayLoadScene("Menu");
					return;
				}
				((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SetMemberData("IsLoaded", "1");
				foreach (KeyValuePair<ulong, PlayerData> player3 in GlobalsManager.Players)
				{
					SingletonBase<VGPlayerManager>.Inst.players.Add(player3.Value.VGPlayerData);
				}
				PaMNetworkManager pamInstance3 = PaMNetworkManager.PamInstance;
				if (pamInstance3 == null || pamInstance3.LobbyInfo.LobbyState != SteamLobbyManager.LobbyState.Playing)
				{
					PaMNetworkManager pamInstance4 = PaMNetworkManager.PamInstance;
					if (pamInstance4 != null)
					{
						pamInstance4.LobbyInfo.HasLoadedMidLobbyInfo = true;
					}
					BeatmapData val = DataManager.inst.gameData?.beatmapData;
					if (val != null)
					{
						__instance.SpawnPlayers(Vector2.op_Implicit(val.GetFirstCheckpointPos()));
					}
				}
				else
				{
					CallRpc_Server_RequestLobbyState();
				}
			}
			if (MultiplayerDiscordManager.IsInitialized)
			{
				setupLevelPresence("Playing Multiplayer!");
			}
			static async void setupLevelPresence(string state)
			{
				if (Object.op_Implicit((Object)(object)SingletonBase<ArcadeManager>.Inst.CurrentArcadeLevel))
				{
					Item? val2;
					Item value;
					if (SingletonBase<ArcadeManager>.Inst.CurrentArcadeLevel.SteamInfo != null)
					{
						val2 = await SteamUGC.QueryFileAsync(SingletonBase<ArcadeManager>.Inst.CurrentArcadeLevel.SteamInfo.ItemID);
					}
					else
					{
						value = default(Item);
						val2 = value;
					}
					Item? val3 = val2;
					string levelCoverUrl = "null_level";
					if (val3.HasValue)
					{
						value = val3.Value;
						if ((int)((Item)(ref value)).Result == 1)
						{
							value = val3.Value;
							levelCoverUrl = ((Item)(ref value)).PreviewImageUrl;
						}
					}
					MultiplayerDiscordManager.Instance.SetLevelPresence(state, SingletonBase<GameManager>.Inst.TrackName + " by " + SingletonBase<GameManager>.Inst.ArtistName, levelCoverUrl);
				}
			}
		}

		[ServerRpc(/*Could not decode attribute arguments.*/)]
		private static async void Server_RequestLobbyState(ClientNetworkConnection conn)
		{
			try
			{
				LevelEndScreen endScreen = Object.FindFirstObjectByType<LevelEndScreen>();
				if (!Object.op_Implicit((Object)(object)endScreen))
				{
					return;
				}
				while ((int)SingletonBase<GameManager>.Inst.CurGameState == 2)
				{
					await Task.Delay(200);
				}
				List<ulong> list = new List<ulong>();
				List<short> list2 = new List<short>();
				foreach (KeyValuePair<ulong, PlayerData> player in GlobalsManager.Players)
				{
					list.Add(player.Key);
					if (Object.op_Implicit((Object)(object)player.Value.VGPlayerData.PlayerObject))
					{
						list2.Add((short)player.Value.VGPlayerData.PlayerObject.Health);
					}
					else
					{
						list2.Add(0);
					}
				}
				CallRpc_Client_LobbyState(conn, endScreen.Hits.Count, SingletonBase<GameManager>.Inst.CurrentSongTime, list, list2.ToArray());
				if (conn.TryGetSteamId(out var steamId))
				{
					CallRpc_Multi_LatePlayerJoin(steamId);
				}
			}
			catch (Exception ex)
			{
				PAM.Logger.LogError((object)ex);
			}
		}

		[ClientRpc(/*Could not decode attribute arguments.*/)]
		private static void Client_LobbyState(int hitCount, float currentTime, List<ulong> playerIds, ReadOnlySpan<short> healths)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			ActionMoment item = new ActionMoment
			{
				position = Vector3.zero,
				time = currentTime
			};
			LevelEndScreen instance = LevelEndScreenPatch.Instance;
			if (!Object.op_Implicit((Object)(object)instance))
			{
				return;
			}
			if (instance.Hits != null)
			{
				for (int i = 0; i < hitCount; i++)
				{
					instance.Hits.Add(item);
				}
			}
			LobbyInfo lobbyInfo = PaMNetworkManager.PamInstance?.LobbyInfo;
			if (lobbyInfo != null && lobbyInfo.HasLoadedMidLobbyInfo)
			{
				return;
			}
			if (lobbyInfo != null)
			{
				lobbyInfo.HasLoadedMidLobbyInfo = true;
			}
			if (!Object.op_Implicit((Object)(object)SingletonBase<GameManager>.Inst))
			{
				PAM.Logger.LogError((object)"GameManager is null");
				return;
			}
			SingletonBase<GameManager>.Inst.UnPause();
			if (DataManager.inst.gameData.beatmapData.checkpoints.Count > 0)
			{
				int num = -1;
				for (int j = 0; j < DataManager.inst.gameData.beatmapData.checkpoints.Count; j++)
				{
					if (j > SingletonBase<GameManager>.Inst.currentCheckpointIndex && !(DataManager.inst.gameData.beatmapData.checkpoints[j].time > currentTime))
					{
						num = j;
					}
				}
				if (num != -1)
				{
					SingletonBase<GameManager>.Inst.currentCheckpointIndex = num;
				}
			}
			SingletonBase<AudioManager>.Inst.CurrentAudioSource.time = currentTime;
			SingletonBase<VGPlayerManager>.inst.RespawnPlayers();
			for (int k = 0; k < playerIds.Count; k++)
			{
				ulong key = playerIds[k];
				short num2 = healths[k];
				if (GlobalsManager.Players.TryGetValue(key, out var value) && value.VGPlayerData.PlayerObject.IsValidPlayer())
				{
					value.VGPlayerData.PlayerObject.Health = num2;
					if (num2 <= 0)
					{
						Object.Destroy((Object)(object)value.VGPlayerData.PlayerObject);
					}
				}
			}
			SingletonBase<CameraDB>.Inst.SetUIVolumeWeight(0f, 0f);
		}

		[MultiRpc(/*Could not decode attribute arguments.*/)]
		private static void Multi_LatePlayerJoin(SteamId playerId)
		{
			//IL_000f: 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)
			if (!SingletonBase<VGPlayerManager>.Inst.players.Contains(GlobalsManager.Players[SteamId.op_Implicit(playerId)].VGPlayerData))
			{
				SingletonBase<VGPlayerManager>.Inst.players.Add(GlobalsManager.Players[SteamId.op_Implicit(playerId)].VGPlayerData);
			}
		}

		private static IEnumerator CustomLoadGame(VGLevel _level)
		{
			GameManager gm = SingletonBase<GameManager>.Inst;
			gm.LoadTimer = new Stopwatch();
			gm.LoadTimer.Start();
			VoidMaskController.ResetForLevelLoad();
			LevelInkLibrary.Unload();
			bool justCreatedLobby = false;
			if (PaMNetworkManager.PamInstance == null)
			{
				if (GlobalsManager.IsHosting)
				{
					SteamLobbyManager.Inst.CreateLobby();
					((MonoBehaviour)SingletonBase<GameManager>.Inst).StartCoroutine(FetchExternalData());
					LobbyInfo lobbyInfo = PaMNetworkManager.PamInstance.LobbyInfo;
					lobbyInfo.HasLoadedMidLobbyInfo = true;
					lobbyInfo.HasLoadedMainLobbyInfo = true;
					lobbyInfo.LobbyState = SteamLobbyManager.LobbyState.Lobby;
					yield return (object)new WaitUntil((Func<bool>)(() => SteamLobbyManager.Inst.InLobby));
					((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SetData("LobbyState", ((ushort)0).ToString());
				}
				else
				{
					SteamManager.Inst.StartClient(((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).Owner.Id);
					((MonoBehaviour)SingletonBase<GameManager>.Inst).StartCoroutine(FetchExternalData());
					LobbyInfo lobby = PaMNetworkManager.PamInstance.LobbyInfo;
					yield return (object)new WaitUntil((Func<bool>)(() => NetworkManager.Instance.TransportActive));
					yield return (object)new WaitUntil((Func<bool>)(() => lobby.HasLoadedMainLobbyInfo));
					yield return (object)new WaitUntil((Func<bool>)(() => lobby.HasLoadedAllInfo));
					if (lobby.LobbyState == SteamLobbyManager.LobbyState.Challenge)
					{
						((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SetMemberData("IsLoaded", "1");
						SingletonBase<SceneLoader>.Inst.manager.AddToLoadingTasks("Challenge Level Vote", Task.Run(async delegate
						{
							while (lobby.LobbyState == SteamLobbyManager.LobbyState.Challenge)
							{
								await Task.Delay(100);
							}
						}), (string)null, (string)null, (Func<string>)null);
						lobby.HasLoadedMidLobbyInfo = true;
						yield return (object)new WaitUntil((Func<bool>)(() => lobby.LobbyState != SteamLobbyManager.LobbyState.Challenge));
						yield break;
					}
					if (lobby.LobbyState == SteamLobbyManager.LobbyState.Playing)
					{
						lobby.HasLoadedMidLobbyInfo = false;
						lobby.JoinedMidLevel = true;
						SingletonBase<SceneLoader>.Inst.manager.AddToLoadingTasks("Lobby State", Task.Run(async delegate
						{
							while (!lobby.HasLoadedMidLobbyInfo)
							{
								await Task.Delay(100);
							}
						}), (string)null, (string)null, (Func<string>)null);
					}
					else
					{
						lobby.HasLoadedMidLobbyInfo = true;
						lobby.JoinedMidLevel = false;
					}
				}
				justCreatedLobby = true;
			}
			else
			{
				((MonoBehaviour)SingletonBase<GameManager>.Inst).StartCoroutine(FetchExternalData());
			}
			VGLevel levelTest;
			do
			{
				levelTest = MPUtility.LookForLevel(GlobalsManager.LevelId);
				if (Object.op_Implicit((Object)(object)levelTest))
				{
					break;
				}
				yield return (object)new WaitForSeconds(1f);
			}
			while (SteamWorkshopFacepunch.inst.isLoadingLevels);
			if (!Object.op_Implicit((Object)(object)levelTest))
			{
				GlobalsManager.IsDownloading = true;
				SingletonBase<SceneLoader>.Inst.manager.AddToLoadingTasks("Downloading Level", Task.Run(async delegate
				{
					SimpleCoroutineAwaiter val = IEnumeratorAwaitExtensions.GetAwaiter(new WaitUntil((Func<bool>)(() => !GlobalsManager.IsDownloading)));
					if (!val.IsCompleted)
					{
						await val;
						object obj = default(object);
						val = (SimpleCoroutineAwaiter)obj;
					}
					val.GetResult();
				}), (string)null, (string)null, (Func<string>)null);
				Task<Item> item = DownloadLevel();
				while (!item.IsCompleted)
				{
					yield return (object)new WaitForUpdate();
				}
				Item result = item.Result;
				if (((Item)(ref result)).Id == PublishedFileId.op_Implicit(0uL))
				{
					SingletonBase<SceneLoader>.Inst.manager.ClearLoadingTasks();
					MPUtility.DelayLoadScene("Menu");
					SteamManager.Inst?.DisconnectAll();
					ErrorScreen.CreateErrorScreen("Failed to download level with id [<b>" + GlobalsManager.LevelId + "</b>]\n\nDisconnected from lobby.");
					yield break;
				}
				VGLevel vgLevel = ScriptableObject.CreateInstance<VGLevel>();
				vgLevel.InitArcadeData(((Item)(ref result)).Directory);
				InitSteamInfo(ref vgLevel, ((Item)(ref result)).Id, ((Item)(ref result)).Directory, result);
				SingletonBase<ArcadeLevelDataManager>.Inst.ArcadeLevels.Add(vgLevel);
				yield return ((MonoBehaviour)gm).StartCoroutine(FileManager.inst.LoadAlbumArt(((object)((Item)(ref result)).Id/*cast due to .constrained prefix*/).ToString(), ((Item)(ref result)).Directory));
				yield return ((MonoBehaviour)gm).StartCoroutine(FileManager.inst.LoadMusic(((object)((Item)(ref result)).Id/*cast due to .constrained prefix*/).ToString(), ((Item)(ref result)).Directory));
				_level = vgLevel;
				SingletonBase<ArcadeManager>.Inst.CurrentArcadeLevel = vgLevel;
				result = default(Item);
			}
			else
			{
				_level = levelTest;
				SingletonBase<ArcadeManager>.Inst.CurrentArcadeLevel = _level;
			}
			LevelSaveData.BeginLevel(_level);
			gm.playbackStarted = false;
			VoidMaskController.LoadLevelFolderMasks(_level.LevelData?.LocalFolder);
			LevelInkLibrary.LoadLevelFolder(_level.LevelData?.LocalFolder);
			yield return LevelInkLibrary.EnsureDialogRuntime();
			gm.LoadMetadata(_level);
			if (!Object.op_Implicit((Object)(object)_level.LevelMusic))
			{
				Task<AudioClip> task = LevelMusicLoader.LoadForPlaybackAsync(_level);
				yield return (object)new WaitUntil((Func<bool>)(() => task.IsCompleted));
			}
			yield return ((MonoBehaviour)gm).StartCoroutine(gm.LoadAudio(_level));
			bool skipLevel;
			if (GlobalsManager.IsHosting)
			{
				skipLevel = true;
				ulong result2;
				if (_level.IsBakedLevel)
				{
					skipLevel = false;
				}
				else if (ulong.TryParse(GlobalsManager.LevelId, out result2))
				{
					Task<Item?> result3 = SteamUGC.QueryFileAsync(PublishedFileId.op_Implicit(result2));
					while (!result3.IsCompleted)
					{
						yield return (object)new WaitForUpdate();
					}
					Item? result4 = result3.Result;
					bool value = Settings.AllowNonPublicLevels.Value;
					if (result4.HasValue)
					{
						Item value2 = result4.Value;
						if ((int)((Item)(ref value2)).Result == 1)
						{
							value2 = result4.Value;
							if (((Item)(ref value2)).IsPublic || value)
							{
								goto IL_07dd;
							}
							value2 = result4.Value;
							if (!((Item)(ref value2)).IsFriendsOnly)
							{
								value2 = result4.Value;
								if (!((Item)(ref value2)).IsPrivate)
								{
									goto IL_07dd;
								}
							}
							goto IL_07f8;
						}
					}
					if (value)
					{
						skipLevel = false;
					}
				}
				goto IL_07f8;
			}
			if (int.TryParse(((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).GetData("seed"), out var result5))
			{
				SteamLobbyManager.Inst.RandSeed = result5;
			}
			RNGSync.Seed = SteamLobbyManager.Inst.RandSeed;
			ObjectManager.inst.SetSeed(SteamLobbyManager.Inst.RandSeed);
			goto IL_09f6;
			IL_07dd:
			skipLevel = false;
			goto IL_07f8;
			IL_07f8:
			if (skipLevel)
			{
				PAM.Logger.LogError((object)"tried playing local or non public level while [Allow hidden levels] is disabled");
				SteamLobbyManager.Inst.UnloadAll();
				SingletonBase<SceneLoader>.Inst.manager.ClearLoadingTasks();
				yield return (object)new WaitForSeconds(1f);
				if (GlobalsManager.IsChallenge)
				{
					CallRpc_Multi_OpenChallenge();
					MPUtility.DelayLoadScene("Challenge");
					yield break;
				}
				GlobalsManager.Queue.RemoveLevel(GlobalsManager.LevelId);
				if (GlobalsManager.Queue.Count == 0)
				{
					MPUtility.DelayLoadScene("Arcade");
					SteamManager.Inst.EndServer();
				}
				else
				{
					GlobalsManager.PlayQueue(null);
				}
				yield break;
			}
			PAM.Logger.LogError((object)Random.seed.ToString());
			SteamLobbyManager.Inst.RandSeed = Random.seed;
			ObjectManager.inst.SetSeed(Random.seed);
			RNGSync.Seed = SteamLobbyManager.Inst.RandSeed;
			if (!justCreatedLobby)
			{
				((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SetData("LevelId", GlobalsManager.LevelId);
				((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SetData("seed", SteamLobbyManager.Inst.RandSeed.ToString());
				PaMNetworkManager.CallRpc_Multi_UpdateLobbyState(0);
				((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SetData("LobbyState", ((ushort)0).ToString());
				if (!GlobalsManager.IsChallenge)
				{
					((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SetData("LevelQueue", JsonConvert.SerializeObject((object)GlobalsManager.Queue.GetQueueLevelNames()));
				}
				PAM.Logger.LogError((object)SteamLobbyManager.Inst.RandSeed);
				CallRpc_Multi_NextQueueLevel(GlobalsManager.LevelId, SteamLobbyManager.Inst.RandSeed);
			}
			goto IL_09f6;
			IL_09f6:
			try
			{
				gm.LoadData(_level);
			}
			catch (Exception ex)
			{
				PAM.Logger.LogFatal((object)"LEVEL FAILED TO LOAD, going back to menu");
				PAM.Logger.LogDebug((object)ex);
				if (!GlobalsManager.IsHosting)
				{
					SteamManager.Inst.EndClient();
				}
				SingletonBase<SceneLoader>.Inst.manager.ClearLoadingTasks();
				MPUtility.DelayLoadScene("Menu");
				yield break;
			}
			yield return ((MonoBehaviour)gm).StartCoroutine(gm.LoadBackgrounds(_level));
			yield return ((MonoBehaviour)gm).StartCoroutine(gm.LoadObjects(_level));
			yield return ((MonoBehaviour)gm).StartCoroutine(gm.LoadTweens());
			Comparison<Checkpoint> comparison = (Checkpoint x, Checkpoint y) => x.time.CompareTo(y.time);
			DataManager.inst.gameData.beatmapData.checkpoints.Sort(comparison);
			if (SingletonBase<VGPlayerManager>.Inst.players.Count == 0)
			{
				SingletonBase<VGPlayerManager>.Inst.players.Add(new VGPlayerData
				{
					PlayerID = 0,
					ControllerID = 0
				});
			}
			gm.PlayGame();
		}

		[MultiRpc(/*Could not decode attribute arguments.*/)]
		private static void Multi_NextQueueLevel(string levelID, int seed)
		{
			if (!GlobalsManager.IsHosting)
			{
				PAM.Logger.LogInfo((object)$"New random seed : {seed}");
				GlobalsManager.LevelId = levelID;
				SteamLobbyManager.Inst.RandSeed = seed;
				LobbyInfo lobbyInfo = PaMNetworkManager.PamInstance?.LobbyInfo;
				if (lobbyInfo != null)
				{
					lobbyInfo.LobbyState = SteamLobbyManager.LobbyState.Lobby;
					lobbyInfo.HasLoadedMidLobbyInfo = true;
				}
				((MonoBehaviour)DataManager.inst).StartCoroutine(NextQueueLevelIEnu());
			}
		}

		private static IEnumerator NextQueueLevelIEnu()
		{
			SingletonBase<SceneLoader>.Inst.manager.ClearLoadingTasks();
			yield return (object)new WaitForSeconds(1f);
			VGLevel val = MPUtility.LookForLevel(GlobalsManager.LevelId);
			if (Object.op_Implicit((Object)(object)val))
			{
				SingletonBase<ArcadeManager>.Inst.CurrentArcadeLevel = val;
				MPUtility.DelayLoadScene("Arcade_Level");
			}
			else
			{
				GlobalsManager.IsDownloading = true;
				PAM.Logger.LogError((object)"You did not have the lobby's level downloaded!, Downloading Level...");
				MPUtility.DelayLoadScene("Arcade_Level");
			}
		}

		[MultiRpc(/*Could not decode attribute arguments.*/)]
		public static void Multi_OpenChallenge()
		{
			if (!GlobalsManager.IsHosting)
			{
				((Lobby)(ref SteamLobbyManager.Inst.CurrentLobby)).SetMemberData("IsLoaded", "0");
				PaMNetworkManager pamInstance = PaMNetworkManager.PamInstance;
				if (pamInstance != null)
				{
					pamInstance.LobbyInfo.HasLoadedMidLobbyInfo = true;
				}
				SingletonBase<SceneLoader>.Inst.manager.ClearLoadingTasks();
				MPUtility.DelayLoadScene("Challenge");
			}
		}

		private unsafe static void InitSteamInfo(ref VGLevel _level, PublishedFileId _id, string _folder, Item _item)
		{
			//IL_0009: 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_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			if (!string.IsNullOrEmpty(_folder))
			{
				LevelDataBase val = new LevelDataBase
				{
					LevelID = ((object)(*(PublishedFileId*)(&_id))/*cast due to .constrained prefix*/).ToString(),
					LocalFolder = _folder
				};
				((Object)_level).name = _id.Value.ToString();
				_level.LevelData = val;
				_level.BaseLevelData = val;
				_level.SteamInfo = new SteamData
				{
					ItemID = _id
				};
			}
		}

		private static async Task<Item> DownloadLevel()
		{
			if (!ulong.TryParse(GlobalsManager.LevelId, out var result))
			{
				FailLoad("Invalid level ID to download");
				return default(Item);
			}
			Item? val = await SteamUGC.QueryFileAsync(PublishedFileId.op_Implicit(result));
			if (!val.HasValue)
			{
				FailLoad("Level not found, is it deleted from the workshop?");
				return default(Item);
			}
			Item level = val.Value;
			if (AppId.op_Implicit(((Item)(ref level)).ConsumerApp) != 440310)
			{
				FailLoad("Workshop item is not from PA");
				return default(Item);
			}
			ManualLogSource logger = PAM.Logger;
			string[] obj = new string[5]
			{
				"Downloading [",
				((Item)(ref level)).Title,
				"] created by [",
				null,
				null
			};
			Friend owner = ((Item)(ref level)).Owner;
			obj[3] = ((Friend)(ref owner)).Name;
			obj[4] = "]";
			logger.LogInfo((object)string.Concat(obj));
			if (string.IsNullOrEmpty(((Item)(ref level)).Directory))
			{
				await ((Item)(ref level)).Subscribe();
				for (int i = 0; i < 3; i++)
				{
					if (await ((Item)(ref level)).DownloadAsync((Action<float>)null, 60, default(CancellationToken)))
					{
						break;
					}
					PAM.Logger.LogWarning((object)$"Failed to to download level, retrying.. [{i + 1}/3]");
					await Task.Delay(1000);
				}
			}
			if (!((Item)(ref level)).IsInstalled)
			{
				FailLoad("Failed to download level");
				return default(Item);
			}
			GlobalsManager.IsDownloading = false;
			return level;
			static void FailLoad(string errorMessage)
			{
				PAM.Logger.LogError((object)errorMessage);
				ErrorScreen.CreateErrorScreen("Failed to download the lobby's level, reason:\n\n" + errorMessage);
				GlobalsManager.IsDownloading = false;
				SingletonBase<SceneLoader>.Inst.manager.ClearLoadingTasks();
				MPUtility.DelayLoadScene("Menu");
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("LoadGame")]
		public static bool OverrideLoadGame(ref IEnumerator __result)
		{
			if (GlobalsManager.IsMultiplayer && !SingletonBase<GameManager>.Inst.IsArcade)
			{
				ErrorScreen.CreateErrorScreen("Tried to create a lobby outside of arcade. how did this happen?\n\nTry again, if issue persists report the issue.");
				return true;
			}
			if (!SingletonBase<GameManager>.Inst.IsArcade || !GlobalsManager.IsMultiplayer)
			{
				return true;
			}
			__result = CustomLoadGame(SingletonBase<ArcadeManager>.Inst.CurrentArcadeLevel);
			return false;
		}

		private static void CallRpc_Server_RequestLobbyState()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			if (NetworkManager.Instance == null)
			{
				return;
			}
			if (NetworkManager.Instance.PeerServer)
			{
				Server_RequestLobbyState(NetworkManager.Instance.ServerSelfPeerConnection);
				return;
			}
			NetworkWriter val = new NetworkWriter();
			try
			{
				NetWriterExtensions.Write(val, (ushort)34247);
				NetworkManager.Instance.SendToServer(val.GetData(), (SendType)0);
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		internal static void Deserialize_Server_RequestLobbyState_34247(ClientNetworkConnection senderConn, NetworkReader reader)
		{
			Server_RequestLobbyState(senderConn);
		}

		private static void CallRpc_Client_LobbyState(ClientNetworkConnection target, int hitCount, float currentTime, List<ulong> playerIds, ReadOnlySpan<short> healths)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			if (NetworkManager.Instance == null)
			{
				return;
			}
			if (NetworkManager.Instance.PeerServer && target == NetworkManager.Instance.ServerSelfPeerConnection)
			{
				Client_LobbyState(hitCount, currentTime, playerIds, healths);
				return;
			}
			NetworkWriter val = new NetworkWriter();
			try
			{
				NetWriterExtensions.Write(val, (ushort)11993);
				NetWriterExtensions.Write(val, hitCount);
				NetWriterExtensions.Write(val, currentTime);
				val.WriteUlongs(playerIds);
				val.WriteSongData(healths);
				NetworkManager.Instance.SendToClient(target, val.GetData(), (SendType)0);
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		internal static void Deserialize_Client_LobbyState_11993(ClientNetworkConnection senderConn, NetworkReader reader)
		{
			Client_LobbyState(NetReaderExtensions.ReadInt32(reader), NetReaderExtensions.ReadSingle(reader), reader.ReadUlongs(), reader.ReadSongData());
		}

		private static void CallRpc_Multi_LatePlayerJoin(SteamId playerId)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkManager.Instance == null)
			{
				return;
			}
			if (NetworkManager.Instance.PeerServer)
			{
				Multi_LatePlayerJoin(playerId);
			}
			NetworkWriter val = new NetworkWriter();
			try
			{
				NetWriterExtensions.Write(val, (ushort)10245);
				val.WriteSteamId(playerId);
				NetworkManager.Instance.SendToAllClients(val.GetData(), (SendType)0);
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		internal static void Deserialize_Multi_LatePlayerJoin_10245(ClientNetworkConnection senderConn, NetworkReader reader)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			Multi_LatePlayerJoin(reader.ReadSteamId());
		}

		private static void CallRpc_Multi_NextQueueLevel(string levelID, int seed)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			if (NetworkManager.Instance == null)
			{
				return;
			}
			if (NetworkManager.Instance.PeerServer)
			{
				Multi_NextQueueLevel(levelID, seed);
			}
			NetworkWriter val = new NetworkWriter();
			try
			{
				NetWriterExtensions.Write(val, (ushort)62198);
				NetWriterExtensions.Write(val, levelID);
				NetWriterExtensions.Write(val, seed);
				NetworkManager.Instance.SendToAllClients(val.GetData(), (SendType)0);
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		internal static void Deserialize_Multi_NextQueueLevel_62198(ClientNetworkConnection senderConn, NetworkReader reader)
		{
			Multi_NextQueueLevel(NetReaderExtensions.ReadString(reader), NetReaderExtensions.ReadInt32(reader));
		}

		public static void CallRpc_Multi_OpenChallenge()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			if (NetworkManager.Instance == null)
			{
				return;
			}
			if (NetworkManager.Instance.PeerServer)
			{
				Multi_OpenChallenge();
			}
			NetworkWriter val = new NetworkWriter();
			try
			{
				NetWriterExtensions.Write(val, (ushort)65142);
				NetworkManager.Instance.SendToAllClients(val.GetData(), (SendType)0);
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		internal static void Deserialize_Multi_OpenChallenge_65142(ClientNetworkConnection senderConn, NetworkReader reader)
		{
			Multi_OpenChallenge();
		}
	}
	[HarmonyPatch(typeof(ObjectManager))]
	public static class RNGSync
	{
		public static int Seed;

		[HarmonyPatch("CreateObjectData")]
		[HarmonyPostfix]
		public static void PostCreateData(int _i, ref GameObjectRef __result)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if (GlobalsManager.IsMultiplayer)
			{
				Random.InitState(Seed);
				__result.sequence.randomState = Random.state;
				Seed = Random.RandomRangeInt(int.MinValue, int.MaxValue);
			}
		}
	}
	[HarmonyPatch(typeof(LevelListController))]
	internal static class LevelListControllerPatch
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static CellViewInstantiated <0>__OnCellInstantiated;

			public static CellViewVisibilityChangedDelegate <1>__OnCellVisibilityChanged;
		}

		private static List<QueueButton> _queueButtons = new List<QueueButton>();

		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void PostAwake(LevelListController __instance)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Expected O, but got Unknown
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			GlobalsManager.Queue.Clear();
			_queueButtons.Clear();
			EnhancedScroller scroller = __instance.Scroller.Scroller;
			CellViewInstantiated cellViewInstantiated = scroller.cellViewInstantiated;
			object obj = <>O.<0>__OnCellInstantiated;
			if (obj == null)
			{
				CellViewInstantiated val = OnCellInstantiated;
				<>O.<0>__OnCellInstantiated = val;
				obj = (object)val;
			}
			scroller.cellViewInstantiated = (CellViewInstantiated)Delegate.Combine((Delegate?)(object)cellViewInstantiated, (Delegate?)obj);
			EnhancedScroller scroller2 = __instance.Scroller.Scroller;
			CellViewVisibilityChangedDelegate cellViewVisibilityChanged = scroller2.cellViewVisibilityChanged;
			object obj2 = <>O.<1>__OnCellVisibilityChanged;
			if (obj2 == null)
			{
				CellViewVisibilityChangedDelegate val2 = OnCellVisibilityChanged;
				<>O.<1>__OnCellVisibilityChanged = val2;
				obj2 = (object)val2;
			}
			scroller2.cellViewVisibilityChanged = (CellViewVisibilityChangedDelegate)Delegate.Combine((Delegate?)(object)cellViewVisibilityChanged, (Delegate?)obj2);
			((MonoBehaviour)SystemManager.inst).StartCoroutine(CheckForInput(__instance));
		}

		[HarmonyPatch("OnDestroy")]
		[HarmonyPostfix]
		private static void PostDestroy(LevelListController __instance)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Expected O, but got Unknown
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			EnhancedScroller scroller = __instance.Scroller.Scroller;
			CellViewInstantiated cellViewInstantiated = scroller.cellViewInstantiated;
			object obj = <>O.<0>__OnCellInstantiated;
			if (obj == null)
			{
				CellViewInstantiated val = OnCellInstantiated;
				<>O.<0>__OnCellInstantiated = val;
				obj = (object)val;
			}
			scroller.cellViewInstantiated = (CellViewInstantiated)Delegate.Remove((Delegate?)(object)cellViewInstantiated, (Delegate?)obj);
			EnhancedScroller scroller2 = __instance.Scroller.Scroller;
			CellViewVisibilityChangedDelegate cellViewVisibilityChanged = scroller2.cellViewVisibilityChanged;
			object obj2 = <>O.<1>__OnCellVisibilityChanged;
			if (obj2 == null)
			{
				CellViewVisibilityChangedDelegate val2 = OnCellVisibilityChanged;
				<>O.<1>__OnCellVisibilityChanged = val2;
				obj2 = (object)val2;
			}
			scroller2.cellViewVisibilityChanged = (CellViewVisibilityChangedDelegate)Delegate.Remove((Delegate?)(object)cellViewVisibilityChanged, (Delegate?)obj2);
		}

		private static void OnCellInstantiated(EnhancedScroller scroller, EnhancedScrollerCellView view)
		{
			//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)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(PAM.QueueIconPrefab, ((Component)view).transform);
			MultiElementButton component = val.GetComponent<MultiElementButton>();
			Navigation navigation = ((Selectable)component).navigation;
			((Navigation)(ref navigation)).mode = (Mode)0;
			((Selectable)component).navigation = navigation;
			Transform transform = ((Component)component).transform;
			RectTransform val2 = (RectTransform)(object)((transform is RectTransform) ? transform : null);
			if (val2 != null)
			{
				val2.anchorMax = new Vector2(0f, 1f);
				val2.anchorMin = new Vector2(0f, 1f);
			}
			_queueButtons.Add(val.AddComponent<QueueButton>());
		}

		private static void OnCellVisibilityChanged(EnhancedScrollerCellView cellView)
		{
			if (!((Object)(object)cellView == (Object)null) && cellView.active)
			{
				EnhancedScrollerCellView obj = ((cellView is LevelRowCellView) ? cellView : null);
				UI_LevelButton val = ((obj != null) ? ((LevelRowCellView)obj).LevelButton : null);
				if (Object.op_Implicit((Object)(object)val) && LevelButtonBinder.BoundLevels.TryGetValue(val, out var value))
				{
					((Component)cellView).GetComponentInChildren<QueueButton>()?.SetLevel(value.BaseLevelData.LevelID, value.TrackName);
				}
			}
		}

		private static IEnumerator CheckForInput(LevelListController instance)
		{
			while (Object.op_Implicit((Object)(object)instance))
			{
				if ((Input.GetKeyDown((KeyCode)121) || Input.GetKeyDown((KeyCode)333)) && Object.op_Implicit((Object)(object)EventSystem.current) && Object.op_Implicit((Object)(object)EventSystem.current.currentSelectedGameObject))
				{
					EventSystem.current.currentSelectedGameObject.GetComponentInChildren<QueueButton>()?.OnClick();
				}
				yield return (object)new WaitForUpdate();
			}
		}
	}
	[HarmonyPatch(typeof(NetSession))]
	internal static class NetSessionPatch
	{
		[HarmonyPatch("Update")]
		[HarmonyPrefix]
		private static bool PreUpdate()
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(VGPlayer))]
	public class PlayerPatch
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static CloseCallDelegate <>9__14_0;

			public static HitDelegate <>9__14_1;

			public static DeathDelegate <>9__14_2;

			internal void <PostSpawn>b__14_0(Vector3 _)
			{
				PointsManager.Inst.AddCloseCall();
			}

			internal void <PostSpawn>b__14_1(int _, Vector3 _)
			{
				PointsManager.Inst.AddHit();
			}

			internal void <PostSpawn>b__14_2(Vector3 _)
			{
				PointsManager.Inst.AddDeath();
			}
		}

		public static bool IsDamageAll;

		public static Mesh CircleMesh;

		public static Mesh ArrowMesh;

		public static Mesh TriangleMesh;

		private static float _holdingBoost;

		private static bool _revertMoveX;

		private static bool _revertMoveY;

		private static bool _revertBoost;

		[HarmonyPatch("CheckForObjectCollision")]
		[HarmonyPrefix]
		private static bool PreCollision(VGPlayer __instance, Collider2D _other, ref bool __result)
		{
			if (!GlobalsManager.IsMultiplayer)
			{
				return true;
			}
			if (!__instance.IsLocalPlayer())
			{
				__result = false;
				return false;
			}
			return true;
		}

		[HarmonyPatch("PlayerHit")]
		[HarmonyPrefix]
		private static bool Hit_Pre(ref VGPlayer __instance)
		{
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			if (!SingletonBase<GameManager>.Inst.IsArcade || SingletonBase<GameManager>.Inst.IsEditor)
			{
				return true;
			}
			if (SingletonBase<GameManager>.Inst.Paused)
			{
				return false;
			}
			if (DataManager.inst.GetSettingEnum("ArcadeHealthMod", 0) == 1)
			{
				return false;
			}
			VGPlayer val = __instance;
			bool flag = !GlobalsManager.IsMultiplayer || val.IsLocalPlayer();
			if (flag)
			{
				bool settingBool = DataManager.inst.GetSettingBool("mp_linkedHealth", false);
				if (GlobalsManager.IsMultiplayer)
				{
					if (GlobalsManager.IsHosting)
					{
						if (settingBool)
						{
							if (!IsDamageAll)
							{
								CallRpc_Multi_DamageAll(val.Health, SingletonBase<GameManager>.Inst.currentCheckpointIndex, GlobalsManager.LocalPlayerId);
								return false;
							}
						}
						else
						{
							CallRpc_Multi_PlayerDamaged(GlobalsManager.LocalPlayerId, val.Health, SingletonBase<GameManager>.Inst.currentCheckpointIndex);
						}
					}
					else if (!settingBool || !IsDamageAll)
					{
						CallRpc_Server_PlayerDamaged(val.Health, SingletonBase<GameManager>.Inst.currentCheckpointIndex, PaMNetworkManager.PamInstance?.LobbyInfo.RewindCounter ?? 0);
					}
					IsDamageAll = false;
					val.Health--;
				}
				else
				{
					val.Health--;
					if (settingBool)
					{
						foreach (VGPlayerData player in SingletonBase<VGPlayerManager>.Inst.players)
						{
							if (player.PlayerObject.IsValidPlayer() && (Object)(object)player.PlayerObject != (Object)(object)__instance && player.PlayerObject.Health > val.Health)
							{
								player.PlayerObject.PlayerHit();
							}
						}
					}
				}
			}
			else
			{
				val.Health--;
			}
			((MonoBehaviour)val).StopCoroutine("RegisterCloseCall");
			if (EventHelper.GetDeathEvent(val) != null && val.Health <= 0)
			{
				EventHelper.GetDeathEvent(val).Invoke(val.Player_Wrapper.position);
			}
			else if (EventHelper.GetHitEvent(val) != null)
			{
				EventHelper.GetHitEvent(val).Invoke(val.Health, val.Player_Wrapper.position);
			}
			if (val.Health > 0)
			{
				val.StartHurtDecay();
				int value = Settings.WarpSfx.Value;
				if (value == 0 || (value == 1 && val.IsLocalPlayer()))
				{
					SingletonBase<AudioManager>.Inst.ApplyLowPass(0.05f, 0.8f, 1.5f);
					SingletonBase<AudioManager>.Inst.ApplyLowPassResonance(0f, 0.6f, 0.2f);
				}
				int value2 = Settings.HitSfx.Value;
				if (value2 == 0 || (value2 == 1 && val.IsLocalPlayer()))
				{
					SingletonBase<AudioManager>.Inst.PlaySound("Player_Hurt", 0.6f);
				}
				if (flag)
				{
					val.PlayerHitAnimation();
				}
				else
				{
					val.PlayParticles((ParticleTypes)2);
				}
			}
			else
			{
				val.PlayerDeath(0.2f);
				if (flag)
				{
					val.PlayerDeathAnimation();
				}
				else
				{
					val.PlayParticles((ParticleTypes)3);
				}
			}
			return false;
		}

		[ServerRpc(/*Could not decode attribute arguments.*/)]
		private static void Server_PlayerDamaged(ClientNetworkConnection conn, int healthPreHit, int checkpointIndex, uint rewindCounter)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Invalid comparison between Unknown and I4
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)SingletonBase<GameManager>.Inst) || SingletonBase<GameManager>.Inst.currentCheckpointIndex < checkpointIndex || (int)SingletonBase<GameManager>.Inst.CurGameState != 1 || (PaMNetworkManager.PamInstance?.LobbyInfo.RewindCounter ?? 0) > rewindCounter || !conn.TryGetSteamId(out var steamId))
			{
				return;
			}
			if (DataManager.inst.GetSettingBool("mp_linkedHealth", false))
			{
				if (GlobalsManager.LocalPlayerObj.Health >= healthPreHit)
				{
					CallRpc_Multi_DamageAll(healthPreHit, checkpointIndex, steamId);
				}
			}
			else
			{
				CallRpc_Multi_PlayerDamaged(steamId, healthPreHit, checkpointIndex);
			}
		}

		[MultiRpc(/*Could not decode attribute arguments.*/)]
		public static void Multi_PlayerDamaged(SteamId steamID, int healthPreHit, int checkpointIndex)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Invalid comparison between Unknown and I4
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			if (healthPreHit == 1)
			{
				PointsManager.Inst?.PlayerHasDied(SteamId.op_Implicit(steamID));
			}
			if (steamID.IsLocalPlayer() || !Object.op_Implicit((Object)(object)SingletonBase<GameManager>.Inst))
			{
				return;
			}
			PlayerData value;
			if (checkpointIndex < SingletonBase<GameManager>.Inst.currentCheckpointIndex)
			{
				if (Object.op_Implicit((Object)(object)LevelEndScreenPatch.Instance))
				{
					LevelEndScreenPatch.Insta

plugins/PAMultiplayer/AttributeNetworkWrapperV2.dll

Decompiled a month ago
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Aiden")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.2.0")]
[assembly: AssemblyInformationalVersion("1.1.2+c0aa79832b3f8f7f881d442a77f8dd3776915342")]
[assembly: AssemblyProduct("AttributeNetworkWrapperV2")]
[assembly: AssemblyTitle("AttributeNetworkWrapperV2")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Aiden-ytarame/AttributeNetworkWrapperV2/")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.2.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[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]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace AttributeNetworkWrapperV2
{
	public enum SendType : ushort
	{
		Reliable,
		Unreliable
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class ServerRpcAttribute : Attribute
	{
		private SendType sendType;

		public ServerRpcAttribute(SendType sendType = SendType.Reliable)
		{
			this.sendType = sendType;
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class ClientRpcAttribute : Attribute
	{
		private SendType sendType;

		public ClientRpcAttribute(SendType sendType = SendType.Reliable)
		{
			this.sendType = sendType;
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class MultiRpcAttribute : Attribute
	{
		private SendType sendType;

		public MultiRpcAttribute(SendType sendType = SendType.Reliable)
		{
			this.sendType = sendType;
		}
	}
	public class NullServerException : Exception
	{
		public NullServerException(string message)
			: base(message)
		{
		}
	}
	public static class Extensions
	{
		public static ushort GetStableHashCode(this string text)
		{
			uint num = 2166136261u;
			uint num2 = 16777619u;
			for (int i = 0; i < text.Length; i++)
			{
				byte b = (byte)text[i];
				num ^= b;
				num *= num2;
			}
			return (ushort)((num >> 16) ^ num);
		}
	}
	public abstract class NetworkConnection
	{
		public readonly int ConnectionId;

		public string Address { get; private set; }

		internal NetworkConnection()
		{
		}

		internal NetworkConnection(int connectionId, string address)
		{
			ConnectionId = connectionId;
			Address = address;
		}

		public abstract void SendRpcToTransport(ReadOnlySpan<byte> data, SendType sendType = SendType.Reliable);

		public abstract void Disconnect();
	}
	public class ServerNetworkConnection : NetworkConnection
	{
		public ServerNetworkConnection(string address)
			: base(0, address)
		{
		}

		public override void SendRpcToTransport(ReadOnlySpan<byte> data, SendType sendType = SendType.Reliable)
		{
			Transport.Instance?.SendMessageToServer(data, sendType);
		}

		public override void Disconnect()
		{
			NetworkManager.Instance?.Disconnect();
		}
	}
	public class ClientNetworkConnection : NetworkConnection
	{
		public ClientNetworkConnection(int connectionId, string address)
			: base(connectionId, address)
		{
		}

		public override void SendRpcToTransport(ReadOnlySpan<byte> data, SendType sendType = SendType.Reliable)
		{
			Transport.Instance?.SendMessageToClient(ConnectionId, data, sendType);
		}

		public override void Disconnect()
		{
			NetworkManager.Instance?.KickClient(ConnectionId);
		}
	}
	public class NetworkManager
	{
		protected ServerNetworkConnection? ServerConnection;

		protected Dictionary<int, ClientNetworkConnection> ClientConnections = new Dictionary<int, ClientNetworkConnection>();

		private bool _eventsSet;

		public static NetworkManager? Instance { get; private set; }

		public bool TransportActive => Transport.IsActive;

		public bool Server => Transport.IsServer;

		public bool PeerServer { get; protected set; }

		public ClientNetworkConnection? ServerSelfPeerConnection { get; protected set; }

		protected Transport Transport => AttributeNetworkWrapperV2.Transport.Instance;

		public bool Init(Transport transport)
		{
			if (Instance != null)
			{
				return false;
			}
			Instance = this;
			AttributeNetworkWrapperV2.Transport.Instance = transport;
			SetupEvents();
			return true;
		}

		public void Shutdown()
		{
			if (this == Instance)
			{
				DeSetupEvents();
				Instance = null;
				AttributeNetworkWrapperV2.Transport.Instance = null;
			}
		}

		private void SetupEvents()
		{
			if (!_eventsSet)
			{
				Transport transport = Transport;
				transport.OnClientConnected = (Action<ServerNetworkConnection>)Delegate.Combine(transport.OnClientConnected, new Action<ServerNetworkConnection>(OnClientConnected));
				Transport transport2 = Transport;
				transport2.OnServerStarted = (Action)Delegate.Combine(transport2.OnServerStarted, new Action(OnServerStarted));
				Transport transport3 = Transport;
				transport3.OnClientDisconnected = (Action)Delegate.Combine(transport3.OnClientDisconnected, new Action(OnClientDisconnected));
				Transport transport4 = Transport;
				transport4.OnServerClientConnected = (Action<ClientNetworkConnection>)Delegate.Combine(transport4.OnServerClientConnected, new Action<ClientNetworkConnection>(OnServerClientConnected));
				Transport transport5 = Transport;
				transport5.OnServerClientDisconnected = (Action<ClientNetworkConnection>)Delegate.Combine(transport5.OnServerClientDisconnected, new Action<ClientNetworkConnection>(OnServerClientDisconnected));
				Transport transport6 = Transport;
				transport6.OnServerDataReceived = (Transport.OnServerDataReceivedDelegate)Delegate.Combine(transport6.OnServerDataReceived, new Transport.OnServerDataReceivedDelegate(OnServerTransportDataReceived));
				Transport transport7 = Transport;
				transport7.OnClientDataReceived = (Transport.OnClientDataReceivedDelegate)Delegate.Combine(transport7.OnClientDataReceived, new Transport.OnClientDataReceivedDelegate(OnClientTransportDataReceived));
				_eventsSet = true;
			}
		}

		private void DeSetupEvents()
		{
			if (_eventsSet)
			{
				Transport transport = Transport;
				transport.OnClientConnected = (Action<ServerNetworkConnection>)Delegate.Remove(transport.OnClientConnected, new Action<ServerNetworkConnection>(OnClientConnected));
				Transport transport2 = Transport;
				transport2.OnServerStarted = (Action)Delegate.Remove(transport2.OnServerStarted, new Action(OnServerStarted));
				Transport transport3 = Transport;
				transport3.OnClientDisconnected = (Action)Delegate.Remove(transport3.OnClientDisconnected, new Action(OnClientDisconnected));
				Transport transport4 = Transport;
				transport4.OnServerClientConnected = (Action<ClientNetworkConnection>)Delegate.Remove(transport4.OnServerClientConnected, new Action<ClientNetworkConnection>(OnServerClientConnected));
				Transport transport5 = Transport;
				transport5.OnServerClientDisconnected = (Action<ClientNetworkConnection>)Delegate.Remove(transport5.OnServerClientDisconnected, new Action<ClientNetworkConnection>(OnServerClientDisconnected));
				Transport transport6 = Transport;
				transport6.OnServerDataReceived = (Transport.OnServerDataReceivedDelegate)Delegate.Remove(transport6.OnServerDataReceived, new Transport.OnServerDataReceivedDelegate(OnServerTransportDataReceived));
				Transport transport7 = Transport;
				transport7.OnClientDataReceived = (Transport.OnClientDataReceivedDelegate)Delegate.Remove(transport7.OnClientDataReceived, new Transport.OnClientDataReceivedDelegate(OnClientTransportDataReceived));
				_eventsSet = false;
			}
		}

		public virtual void ConnectToServer(string address)
		{
			Transport.ConnectClient(address);
		}

		public virtual void Disconnect()
		{
			Transport.StopClient();
		}

		public virtual void KickClient(int clientId)
		{
			Transport.KickConnection(clientId);
		}

		public virtual void OnClientConnected(ServerNetworkConnection connection)
		{
			ServerConnection = connection;
		}

		public virtual void OnClientDisconnected()
		{
			ServerConnection = null;
		}

		public virtual void SendToServer(ReadOnlySpan<byte> data, SendType sendType)
		{
			if (ServerConnection == null || Transport == null || !Transport.IsActive)
			{
				throw new NullServerException("Tried calling a server rpc while server is Null!");
			}
			ServerConnection.SendRpcToTransport(data, sendType);
		}

		internal unsafe static void OnClientTransportDataReceived(ReadOnlySpan<byte> data)
		{
			if (data.Length < 2)
			{
				Console.WriteLine("Data was too small, idk what we do for now");
				return;
			}
			fixed (byte* ptr = data)
			{
				using NetworkReader reader = new NetworkReader(ptr, data.Length);
				if (RpcHandler.TryGetRpcInvoker(reader.ReadUInt16(), out var invoker))
				{
					if (invoker.CallType != RpcHandler.CallType.Server)
					{
						invoker.RpcFunc(null, reader);
					}
					else
					{
						Console.WriteLine("Received server rcp as a client!");
					}
				}
				else
				{
					Console.WriteLine("Received invalid id!");
				}
			}
		}

		public virtual void StartServer(bool serverIsPeer)
		{
			ClientConnections.Clear();
			PeerServer = serverIsPeer;
			ServerSelfPeerConnection = new ClientNetworkConnection(0, "addr");
			ClientConnections.Add(0, ServerSelfPeerConnection);
			Transport.StartServer();
		}

		public virtual void EndServer()
		{
			PeerServer = false;
			ClientConnections.Clear();
			ServerSelfPeerConnection = null;
			Transport.StopServer();
		}

		public virtual void OnServerClientDisconnected(ClientNetworkConnection connection)
		{
			ClientConnections.Remove(connection.ConnectionId);
		}

		public virtual void OnServerClientConnected(ClientNetworkConnection connection)
		{
			ClientConnections.Add(connection.ConnectionId, connection);
		}

		public virtual void OnServerStarted()
		{
		}

		public virtual void SendToClient(ClientNetworkConnection connection, ReadOnlySpan<byte> data, SendType sendType)
		{
			if (Transport == null || !Transport.IsActive)
			{
				throw new NullServerException("Tried calling a Client rpc while transport is Null!");
			}
			if (connection != null)
			{
				connection.SendRpcToTransport(data, sendType);
				return;
			}
			throw new ArgumentException("Tried to send rpc to invalid connection ID!");
		}

		public virtual void SendToAllClients(ReadOnlySpan<byte> data, SendType sendType)
		{
			if (Transport == null || !Transport.IsActive)
			{
				throw new NullServerException("Tried calling a Client rpc while transport is Null!");
			}
			foreach (KeyValuePair<int, ClientNetworkConnection> clientConnection in ClientConnections)
			{
				if (!PeerServer || ServerSelfPeerConnection != clientConnection.Value)
				{
					clientConnection.Value.SendRpcToTransport(data, sendType);
				}
			}
		}

		internal unsafe static void OnServerTransportDataReceived(ClientNetworkConnection connection, ReadOnlySpan<byte> data)
		{
			if (data.Length < 2)
			{
				Console.WriteLine("Data was too small, idk what we do for now");
				return;
			}
			fixed (byte* ptr = data)
			{
				using NetworkReader reader = new NetworkReader(ptr, data.Length);
				if (RpcHandler.TryGetRpcInvoker(reader.ReadUInt16(), out var invoker))
				{
					if (invoker.CallType == RpcHandler.CallType.Server)
					{
						invoker.RpcFunc(connection, reader);
					}
					else
					{
						Console.WriteLine("Received client rcp as a server!");
					}
				}
				else
				{
					Console.WriteLine("Received invalid id!");
				}
			}
		}
	}
	public class NetworkReader : IDisposable
	{
		private int _position;

		private int _length;

		private unsafe byte* _dataPtr;

		private MemoryHandle? _handle;

		public unsafe NetworkReader(ReadOnlyMemory<byte> data)
		{
			_handle = data.Pin();
			Init((byte*)_handle.Value.Pointer, data.Length);
		}

		public unsafe NetworkReader(byte* ptr, int size)
		{
			Init(ptr, size);
		}

		private unsafe void Init(byte* ptr, int size)
		{
			_dataPtr = ptr;
			_length = size;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private bool HasBytes(int count)
		{
			return _length >= _position + count;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe T ReadValue<T>() where T : unmanaged
		{
			int num = sizeof(T);
			if (!HasBytes(num))
			{
				throw new ArgumentException("There was not enough bytes to read");
			}
			byte* num2 = _dataPtr + _position;
			_position += num;
			return *(T*)num2;
		}

		public unsafe ReadOnlySpan<byte> ReadBytes(int count)
		{
			if (count <= 0 || !HasBytes(count))
			{
				return null;
			}
			byte* pointer = _dataPtr + _position;
			_position += count;
			return new ReadOnlySpan<byte>(pointer, count);
		}

		public void Dispose()
		{
			_handle?.Dispose();
		}
	}
	public static class NetReaderExtensions
	{
		public static bool ReadBoolean(this NetworkReader reader)
		{
			return reader.ReadValue<bool>();
		}

		public static byte ReadByte(this NetworkReader reader)
		{
			return reader.ReadValue<byte>();
		}

		public static sbyte ReadSByte(this NetworkReader reader)
		{
			return reader.ReadValue<sbyte>();
		}

		public static short ReadInt16(this NetworkReader reader)
		{
			return reader.ReadValue<short>();
		}

		public static ushort ReadUInt16(this NetworkReader reader)
		{
			return reader.ReadValue<ushort>();
		}

		public static int ReadInt32(this NetworkReader reader)
		{
			return reader.ReadValue<int>();
		}

		public static uint ReadUInt32(this NetworkReader reader)
		{
			return reader.ReadValue<uint>();
		}

		public static long ReadInt64(this NetworkReader reader)
		{
			return reader.ReadValue<long>();
		}

		public static ulong ReadUInt64(this NetworkReader reader)
		{
			return reader.ReadValue<ulong>();
		}

		public static float ReadSingle(this NetworkReader reader)
		{
			return reader.ReadValue<float>();
		}

		public static double ReadDouble(this NetworkReader reader)
		{
			return reader.ReadValue<double>();
		}

		public static char ReadChar(this NetworkReader reader)
		{
			return reader.ReadValue<char>();
		}

		public unsafe static string ReadString(this NetworkReader reader)
		{
			int num = reader.ReadValue<int>();
			ReadOnlySpan<byte> readOnlySpan = reader.ReadBytes(num);
			if (readOnlySpan == null)
			{
				return "";
			}
			fixed (byte* bytes = readOnlySpan)
			{
				return Encoding.UTF8.GetString(bytes, num);
			}
		}

		public static ReadOnlySpan<byte> ReadBytes(this NetworkReader reader)
		{
			int count = reader.ReadValue<int>();
			ReadOnlySpan<byte> readOnlySpan = reader.ReadBytes(count);
			if (readOnlySpan == null)
			{
				throw new ArgumentException("There was not enough bytes to read byte array parameter");
			}
			return readOnlySpan;
		}
	}
	public static class RpcHandler
	{
		public enum CallType
		{
			Server,
			Client,
			Multi
		}

		public struct Invoker
		{
			public CallType CallType;

			public RpcDelegate RpcFunc;

			public Invoker(CallType callType, RpcDelegate func)
			{
				CallType = callType;
				RpcFunc = func;
			}
		}

		public delegate void RpcDelegate(ClientNetworkConnection conn, NetworkReader reader);

		private static Dictionary<ushort, Invoker> RpcInvokers;

		static RpcHandler()
		{
			RpcInvokers = new Dictionary<ushort, Invoker>();
			Type type = null;
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			for (int i = 0; i < assemblies.Length; i++)
			{
				type = assemblies[i].GetType("AttributeNetworkWrapperV2.RpcFuncRegistersGenerated");
				if (type != null)
				{
					break;
				}
			}
			if (type == null)
			{
				throw new ApplicationException("RpcFuncRegistersGenerated wasn't found, something terrible went wrong");
			}
			RuntimeHelpers.RunClassConstructor(type.TypeHandle);
		}

		public static bool TryGetRpcInvoker(ushort hash, out Invoker invoker)
		{
			return RpcInvokers.TryGetValue(hash, out invoker);
		}

		public static void RegisterRpc(ushort hash, RpcDelegate rpcDelegate, CallType callType)
		{
			if (TryGetRpcInvoker(hash, out var invoker))
			{
				throw new ArgumentException($"Tried to register RPC with hash {hash}, but it already exists.\n" + "Tried to Add [" + rpcDelegate.Method.DeclaringType?.Name + "." + rpcDelegate.Method.Name + "] but [" + invoker.RpcFunc.Method.DeclaringType?.Name + "." + invoker.RpcFunc.Method.Name + "] already exists. Consider renaming the RPC.");
			}
			RpcInvokers.Add(hash, new Invoker(callType, rpcDelegate));
		}
	}
	public abstract class Transport
	{
		public delegate void OnClientDataReceivedDelegate(ReadOnlySpan<byte> data);

		public delegate void OnServerDataReceivedDelegate(ClientNetworkConnection connection, ReadOnlySpan<byte> data);

		public OnClientDataReceivedDelegate OnClientDataReceived;

		public Action<ServerNetworkConnection> OnClientConnected;

		public Action OnClientDisconnected;

		public OnServerDataReceivedDelegate OnServerDataReceived;

		public Action<ClientNetworkConnection> OnServerClientConnected;

		public Action<ClientNetworkConnection> OnServerClientDisconnected;

		public Action OnServerStarted;

		public static Transport? Instance { get; set; }

		public bool IsActive { get; protected set; }

		public bool IsServer { get; protected set; }

		public abstract void ConnectClient(string address);

		public abstract void StopClient();

		public abstract void StartServer();

		public abstract void StopServer();

		public abstract void KickConnection(int connectionId);

		public abstract void SendMessageToServer(ReadOnlySpan<byte> data, SendType sendType = SendType.Reliable);

		public abstract void SendMessageToClient(int connectionId, ReadOnlySpan<byte> data, SendType sendType = SendType.Reliable);

		public abstract void Shutdown();
	}
	public class NetworkWriter : IDisposable
	{
		private byte[] _buffer = ArrayPool<byte>.Shared.Rent(1024);

		private int _position;

		public ReadOnlySpan<byte> GetData()
		{
			return new ReadOnlySpan<byte>(_buffer, 0, _position);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void EnsureCapacity(int value)
		{
			if (_buffer.Length < value)
			{
				int minimumLength = Math.Max(value, _buffer.Length * 2);
				byte[] array = ArrayPool<byte>.Shared.Rent(minimumLength);
				Buffer.BlockCopy(_buffer, 0, array, 0, _position);
				ArrayPool<byte>.Shared.Return(_buffer);
				_buffer = array;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void WriteBytes<T>(T value) where T : unmanaged
		{
			int num = sizeof(T);
			EnsureCapacity(_position + num);
			fixed (byte* ptr = &_buffer[_position])
			{
				*(T*)ptr = value;
			}
			_position += num;
		}

		public unsafe void WriteBytes(byte* ptr, int count)
		{
			if (count > 0)
			{
				EnsureCapacity(_position + count);
				fixed (byte* destination = &_buffer[_position])
				{
					Unsafe.CopyBlock(destination, ptr, (uint)count);
				}
				_position += count;
			}
		}

		public void Dispose()
		{
			ArrayPool<byte>.Shared.Return(_buffer);
			_buffer = null;
		}
	}
	public static class NetWriterExtensions
	{
		public static void Write(this NetworkWriter nw, bool value)
		{
			nw.WriteBytes(value);
		}

		public static void Write(this NetworkWriter nw, byte value)
		{
			nw.WriteBytes(value);
		}

		public static void Write(this NetworkWriter nw, sbyte value)
		{
			nw.WriteBytes(value);
		}

		public static void Write(this NetworkWriter nw, short value)
		{
			nw.WriteBytes(value);
		}

		public static void Write(this NetworkWriter nw, ushort value)
		{
			nw.WriteBytes(value);
		}

		public static void Write(this NetworkWriter nw, int value)
		{
			nw.WriteBytes(value);
		}

		public static void Write(this NetworkWriter nw, uint value)
		{
			nw.WriteBytes(value);
		}

		public static void Write(this NetworkWriter nw, long value)
		{
			nw.WriteBytes(value);
		}

		public static void Write(this NetworkWriter nw, ulong value)
		{
			nw.WriteBytes(value);
		}

		public static void Write(this NetworkWriter nw, float value)
		{
			nw.WriteBytes(value);
		}

		public static void Write(this NetworkWriter nw, double value)
		{
			nw.WriteBytes(value);
		}

		public static void Write(this NetworkWriter nw, char value)
		{
			nw.WriteBytes(value);
		}

		public unsafe static void Write(this NetworkWriter nw, string value)
		{
			byte[] bytes = Encoding.UTF8.GetBytes(value);
			nw.WriteBytes(bytes.Length);
			fixed (byte* ptr = bytes)
			{
				nw.WriteBytes(ptr, bytes.Length);
			}
		}

		public unsafe static void Write(this NetworkWriter nw, ReadOnlySpan<byte> value)
		{
			nw.WriteBytes(value.Length);
			fixed (byte* ptr = value)
			{
				nw.WriteBytes(ptr, value.Length);
			}
		}
	}
}