Decompiled source of CardShopCoopCommunity ExternalModInterop v2.3.1

BepInEx/plugins/CardShopCoop.CustomTv.dll

Decompiled 3 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using CardShopCoop.Api;
using CardShopCoop.Attributes;
using CardShopCoop.Net;
using CardShopCoop.Net.Connection;
using HarmonyLib;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("Devin 'Meepen' Korb")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("RTCGO Custom TV co-op sync for CardShopCoopCommunity. Optional separate download.")]
[assembly: AssemblyFileVersion("2.3.1.0")]
[assembly: AssemblyInformationalVersion("2.3.1+8f2e09936fa0f37fdbe5e6fa509abb0b78e52e6e")]
[assembly: AssemblyProduct("CardShopCoopCommunity Custom TV")]
[assembly: AssemblyTitle("CardShopCoop.CustomTv")]
[assembly: AssemblyVersion("2.3.1.0")]
namespace CardShopCoop.CustomTv
{
	[ClientBehaviour]
	public sealed class TvClientBehaviour : CoopBehaviour
	{
		private struct QualityState
		{
			public bool Armed;

			public string Url;

			public PlaybackUndoState Prior;
		}

		private struct GlobalInputState
		{
			public bool Next;

			public bool Previous;

			public bool Shuffle;

			public bool Power;

			public PlaybackUndoState Prior;
		}

		private static TvClientBehaviour _active;

		private static double _seekObservedPosition;

		private static bool _seekHeld;

		private bool Joined
		{
			get
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Invalid comparison between Unknown and I4
				if (((CoopBehaviour)this).Context != null)
				{
					ICoopPeer host = ((CoopBehaviour)this).Context.Host;
					if (host == null)
					{
						return false;
					}
					return (int)host.State == 3;
				}
				return false;
			}
		}

		private void OnEnable()
		{
			try
			{
				ResetSessionState();
				SceneManager.sceneLoaded += OnSceneLoaded;
				_active = this;
				ApplyPatches();
			}
			catch (Exception ex)
			{
				CoopLog.Error("TV client initialization failed: " + ex);
				SceneManager.sceneLoaded -= OnSceneLoaded;
				if (_active == this)
				{
					_active = null;
				}
				ResetSessionState();
				throw;
			}
		}

		[OnFullyJoined]
		private void MarkJoined(ICoopPeer _)
		{
			ApplyStoredStates();
		}

		[ExtendedInformationHandler]
		private void OnTvState(InteractableObject tv, InformationChange<TvState> change)
		{
			if (TvInterop.Present && !((Object)(object)tv == (Object)null) && !change.Removed)
			{
				Component val = TvInterop.ControllerFor(tv);
				if ((Object)(object)val == (Object)null)
				{
					CoopLog.Warn("TV state arrived before its VideoPlayerController: " + ((Object)tv).name);
				}
				else
				{
					ApplyTvState(val, change.Current, change.Previous);
				}
			}
		}

		private void ApplyTvState(Component controller, TvState state, TvState previous)
		{
			if (!((CoopBehaviour)this).Context.InGame || !TvInterop.Present || TvInterop.ApplyingRemote)
			{
				if (state != null)
				{
					CoopLog.Info("[tv] defer state source=" + (state.SourceUrl ?? "<null>") + " op=" + state.Operation.ToString() + " inGame=" + ((CoopBehaviour)this).Context.InGame);
				}
			}
			else
			{
				if (state == null || state == previous || (previous != null && state.Generation < previous.Generation))
				{
					return;
				}
				CoopLog.Info("[tv] apply state source=" + (state.SourceUrl ?? "<null>") + " op=" + state.Operation.ToString() + " gen=" + state.Generation);
				TvInterop.BeginFocus(controller);
				try
				{
					if (!string.IsNullOrWhiteSpace(state.SourceUrl) && !TvInterop.EnrollmentReady)
					{
						TvInterop.RequestClientEnrollment();
					}
					else
					{
						ApplyState(state);
					}
				}
				finally
				{
					TvInterop.EndFocus();
				}
			}
		}

		private void OnDisable()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
			if (_active == this)
			{
				_active = null;
			}
			ResetSessionState();
		}

		private void ResetSessionState()
		{
			TvInterop.ResetState();
		}

		private void OnSceneLoaded(Scene _, LoadSceneMode mode)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			if ((int)mode == 0)
			{
				TvInterop.ResetState();
			}
		}

		[OnClientDisconnected]
		private void ForgetHost(ICoopPeer peer, DisconnectInfo info)
		{
			if (peer == null || peer.IsHost)
			{
				ResetSessionState();
			}
		}

		private static void ApplyState(TvState state)
		{
			switch (state.Operation)
			{
			case TvOperation.Open:
			case TvOperation.Playlist:
			case TvOperation.Next:
			case TvOperation.Previous:
				TvInterop.ApplyMediaState(state);
				break;
			case TvOperation.Pause:
				TvInterop.ApplyPaused(state.Paused);
				break;
			case TvOperation.Power:
				TvInterop.ApplyPowered(state.PoweredOff);
				break;
			case TvOperation.Shuffle:
				TvInterop.ApplyShuffle(state.Shuffle);
				break;
			case TvOperation.Seek:
				TvInterop.ApplySeek(state.Position);
				break;
			case TvOperation.Barrier:
				TvInterop.ApplyBarrier(state.Barrier, state.Resume);
				break;
			case TvOperation.Error:
				TvInterop.ApplyPlaybackError();
				break;
			default:
				TvInterop.ApplyMediaState(state);
				break;
			}
		}

		private void ApplyPatches()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Expected O, but got Unknown
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: 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_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Expected O, but got Unknown
			//IL_010b: Expected O, but got Unknown
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Expected O, but got Unknown
			//IL_0147: Expected O, but got Unknown
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Expected O, but got Unknown
			//IL_0183: Expected O, but got Unknown
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Expected O, but got Unknown
			//IL_01bf: Expected O, but got Unknown
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Expected O, but got Unknown
			//IL_01fb: Expected O, but got Unknown
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Expected O, but got Unknown
			//IL_0237: Expected O, but got Unknown
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Expected O, but got Unknown
			//IL_0273: Expected O, but got Unknown
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02af: Expected O, but got Unknown
			//IL_02af: Expected O, but got Unknown
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d7: Expected O, but got Unknown
			if (TvInterop.Present)
			{
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "OnEnable", (HarmonyMethod)null, new HarmonyMethod(typeof(TvClientBehaviour), "ControllerLifecyclePostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "Start", (HarmonyMethod)null, new HarmonyMethod(typeof(TvClientBehaviour), "ControllerLifecyclePostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "ChangeVideo", (HarmonyMethod)null, new HarmonyMethod(typeof(TvClientBehaviour), "ControllerLifecyclePostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "ChangeToUrl", (HarmonyMethod)null, new HarmonyMethod(typeof(TvClientBehaviour), "ChangeToUrlPostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "StreamYouTube", (HarmonyMethod)null, new HarmonyMethod(typeof(TvClientBehaviour), "StreamYouTubePostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "HandleGlobalInput", new HarmonyMethod(typeof(TvClientBehaviour), "GlobalInputPrefix", (Type[])null), new HarmonyMethod(typeof(TvClientBehaviour), "GlobalInputPostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "OnQualityChoice", new HarmonyMethod(typeof(TvClientBehaviour), "QualityPrefix", (Type[])null), new HarmonyMethod(typeof(TvClientBehaviour), "QualityPostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "ToggleGlobalPause", new HarmonyMethod(typeof(TvClientBehaviour), "CapturePrefix", (Type[])null), new HarmonyMethod(typeof(TvClientBehaviour), "PausePostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "RemoteNext", new HarmonyMethod(typeof(TvClientBehaviour), "CapturePrefix", (Type[])null), new HarmonyMethod(typeof(TvClientBehaviour), "NextPostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "RemotePrev", new HarmonyMethod(typeof(TvClientBehaviour), "CapturePrefix", (Type[])null), new HarmonyMethod(typeof(TvClientBehaviour), "PreviousPostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "RemoteShuffle", new HarmonyMethod(typeof(TvClientBehaviour), "CapturePrefix", (Type[])null), new HarmonyMethod(typeof(TvClientBehaviour), "ShufflePostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "RemotePower", new HarmonyMethod(typeof(TvClientBehaviour), "CapturePrefix", (Type[])null), new HarmonyMethod(typeof(TvClientBehaviour), "PowerPostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "OnLocalPrepared", new HarmonyMethod(typeof(TvClientBehaviour), "LocalPreparedPrefix", (Type[])null), new HarmonyMethod(typeof(TvClientBehaviour), "LocalPreparedPostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "OnDisable", (HarmonyMethod)null, new HarmonyMethod(typeof(TvClientBehaviour), "ControllerDisablePostfix", (Type[])null), (Type[])null);
			}
		}

		private static void LocalPreparedPrefix(object __instance, object source)
		{
			Component val = (Component)((__instance is Component) ? __instance : null);
			TvInterop.RegisterController(val);
			if ((Object)(object)_active == (Object)null || (Object)(object)val == (Object)null)
			{
				return;
			}
			TvInterop.BeginFocus(val);
			try
			{
				_active.BeforeLocalPrepared(val, source);
			}
			finally
			{
				TvInterop.EndFocus();
			}
		}

		private static void LocalPreparedPostfix(object __instance, object source)
		{
			Component val = (Component)((__instance is Component) ? __instance : null);
			TvInterop.RegisterController(val);
			if ((Object)(object)_active == (Object)null || (Object)(object)val == (Object)null)
			{
				return;
			}
			TvInterop.BeginFocus(val);
			try
			{
				_active.AfterLocalPrepared(val, source);
			}
			finally
			{
				TvInterop.EndFocus();
			}
		}

		private static void ControllerLifecyclePostfix(object __instance)
		{
			Component controller = (Component)((__instance is Component) ? __instance : null);
			TvInterop.RegisterController(controller);
			_active?.OnControllerReady(controller);
		}

		private void OnControllerReady(Component controller)
		{
			if (Joined && ((CoopBehaviour)this).Context.InGame)
			{
				ApplyStoredState(controller);
			}
		}

		private void ApplyStoredStates()
		{
			if (!((CoopBehaviour)this).Context.InGame)
			{
				return;
			}
			foreach (Component item in TvInterop.Controllers())
			{
				ApplyStoredState(item);
			}
		}

		private void ApplyStoredState(Component controller)
		{
			InteractableObject obj = TvInterop.OwnerOf(controller);
			TvState tvState = ((obj != null) ? InteractableObjectExtensions.GetExtendedInformation<TvState>(obj) : null);
			if (tvState != null)
			{
				ApplyTvState(controller, tvState, null);
			}
		}

		private static void ChangeToUrlPostfix(object __instance, string url, string title)
		{
			object controller = ((__instance is Component) ? __instance : null);
			TvInterop.RegisterController((Component)controller);
			TvInterop.ChangeToUrlPostfix((Component)controller, url);
		}

		private static void StreamYouTubePostfix(object __instance, string url)
		{
			object controller = ((__instance is Component) ? __instance : null);
			TvInterop.RegisterController((Component)controller);
			TvInterop.StreamYouTubePostfix((Component)controller, url);
		}

		private void BeforeLocalPrepared(Component controller, object source)
		{
			InteractableObject val = TvInterop.OwnerOf(controller);
			if (!((Object)(object)val == (Object)null))
			{
				TvState extendedInformation = InteractableObjectExtensions.GetExtendedInformation<TvState>(val);
				if (extendedInformation != null && extendedInformation.Barrier && TvInterop.IsMainPreparedPlayer(controller, source))
				{
					TvInterop.SetSharedPausedForPrepare(paused: false);
				}
			}
		}

		private void AfterLocalPrepared(Component controller, object source)
		{
			InteractableObject val = TvInterop.OwnerOf(controller);
			if (!((Object)(object)val == (Object)null) && TvInterop.IsMainPreparedPlayer(controller, source))
			{
				TvInterop.ApplyPreparedPosition(controller);
				TvState extendedInformation = InteractableObjectExtensions.GetExtendedInformation<TvState>(val);
				if (extendedInformation != null && extendedInformation.Barrier)
				{
					TvInterop.PausePreparedStream(controller);
				}
			}
		}

		private static bool CanAct()
		{
			if ((Object)(object)_active != (Object)null && _active.Joined && ((CoopBehaviour)_active).Context.InGame)
			{
				return TvInterop.Present;
			}
			return false;
		}

		private static void Send(TvActionMessage message, PlaybackUndoState previous = default(PlaybackUndoState), double undoSeek = double.NaN)
		{
			if (CanAct() && message != null)
			{
				InteractableObject val = TvInterop.OwnerOf(TvInterop.ActionController);
				if (!((Object)(object)val == (Object)null))
				{
					message.Tv = val;
					message.Previous = previous;
					message.UndoSeek = undoSeek;
					((CoopBehaviour)_active).Context.Send((INetMessage)(object)message);
				}
			}
		}

		private static void QualityPrefix(object __instance, out QualityState __state)
		{
			Component val = (Component)((__instance is Component) ? __instance : null);
			TvInterop.RegisterController(val);
			__state = default(QualityState);
			if (!CanAct() || TvInterop.ApplyingRemote || (Object)(object)val == (Object)null)
			{
				return;
			}
			TvInterop.BeginFocus(val);
			try
			{
				string pendingUrl = TvInterop.PendingUrl;
				if (!string.IsNullOrWhiteSpace(pendingUrl))
				{
					__state.Armed = true;
					__state.Url = pendingUrl;
					__state.Prior = TvInterop.CapturePlaybackState();
				}
			}
			finally
			{
				TvInterop.EndFocus();
			}
		}

		private static void QualityPostfix(object __instance, QualityState __state)
		{
			Component val = (Component)((__instance is Component) ? __instance : null);
			TvInterop.RegisterController(val);
			if (!__state.Armed || !CanAct() || TvInterop.ApplyingRemote || (Object)(object)val == (Object)null)
			{
				return;
			}
			TvInterop.BeginFocus(val);
			try
			{
				Send(new TvOpenMessage
				{
					Url = __state.Url,
					Title = "Shared stream"
				}, __state.Prior);
			}
			finally
			{
				TvInterop.EndFocus();
			}
		}

		private static void GlobalInputPrefix(object __instance, out GlobalInputState __state)
		{
			Component controller = (Component)((__instance is Component) ? __instance : null);
			__state = default(GlobalInputState);
			if (!TvInterop.IsSoundController(controller))
			{
				return;
			}
			TvInterop.RegisterController(controller);
			TvInterop.BeginFocus(controller);
			try
			{
				bool flag = Input.GetKey((KeyCode)308) || Input.GetKey((KeyCode)307);
				double position = TvInterop.Position;
				bool seekHeld = flag && (Input.GetKey((KeyCode)93) || Input.GetKey((KeyCode)91));
				if (CanAct() && !TvInterop.ApplyingRemote && _seekHeld && Math.Abs(position - _seekObservedPosition) >= 1.0)
				{
					ForwardSeek(_seekObservedPosition, position - _seekObservedPosition);
				}
				_seekObservedPosition = position;
				_seekHeld = seekHeld;
				if (!CanAct() || TvInterop.ApplyingRemote || !flag)
				{
					return;
				}
				if (Input.GetKeyDown((KeyCode)61))
				{
					__state.Next = true;
				}
				else if (Input.GetKeyDown((KeyCode)45))
				{
					__state.Previous = true;
				}
				else if (Input.GetKeyDown((KeyCode)115))
				{
					__state.Shuffle = true;
				}
				else
				{
					if (!Input.GetKeyDown((KeyCode)111))
					{
						return;
					}
					__state.Power = true;
				}
				__state.Prior = TvInterop.CapturePlaybackState();
			}
			finally
			{
				TvInterop.EndFocus();
			}
		}

		private static void GlobalInputPostfix(object __instance, GlobalInputState __state)
		{
			Component controller = (Component)((__instance is Component) ? __instance : null);
			if (!CanAct() || TvInterop.ApplyingRemote || !TvInterop.IsSoundController(controller))
			{
				return;
			}
			TvInterop.RegisterController(controller);
			TvInterop.BeginFocus(controller);
			try
			{
				if (__state.Next)
				{
					Send(new TvNextMessage(), __state.Prior);
				}
				else if (__state.Previous)
				{
					Send(new TvPreviousMessage(), __state.Prior);
				}
				else if (__state.Shuffle)
				{
					ForwardSelfApplied(new TvShuffleMessage(), __state.Prior);
				}
				else if (__state.Power)
				{
					ForwardSelfApplied(new TvPowerMessage(), __state.Prior);
				}
			}
			finally
			{
				TvInterop.EndFocus();
			}
		}

		private static void CapturePrefix(object __instance, out PlaybackUndoState __state)
		{
			Component val = (Component)((__instance is Component) ? __instance : null);
			TvInterop.RegisterController(val);
			if ((Object)(object)val == (Object)null)
			{
				__state = default(PlaybackUndoState);
				return;
			}
			TvInterop.BeginFocus(val);
			try
			{
				__state = TvInterop.CapturePlaybackState();
			}
			finally
			{
				TvInterop.EndFocus();
			}
		}

		private static void ControllerDisablePostfix(object __instance)
		{
			TvInterop.ForgetController((Component)((__instance is Component) ? __instance : null));
		}

		private static void PausePostfix(PlaybackUndoState __state)
		{
			if (CanAct() && !TvInterop.ApplyingRemote && TvInterop.Paused != __state.Paused)
			{
				Send(new TvPauseMessage(), __state);
			}
		}

		private static void PowerPostfix(PlaybackUndoState __state)
		{
			if (CanAct() && !TvInterop.ApplyingRemote && TvInterop.PoweredOff != __state.PoweredOff)
			{
				Send(new TvPowerMessage(), __state);
			}
		}

		private static void ShufflePostfix(PlaybackUndoState __state)
		{
			if (CanAct() && !TvInterop.ApplyingRemote && TvInterop.Shuffle != __state.Shuffle)
			{
				Send(new TvShuffleMessage(), __state);
			}
		}

		private static void NextPostfix(PlaybackUndoState __state)
		{
			Send(new TvNextMessage(), __state);
		}

		private static void PreviousPostfix(PlaybackUndoState __state)
		{
			Send(new TvPreviousMessage(), __state);
		}

		private static void ForwardSelfApplied(TvActionMessage message, PlaybackUndoState prior)
		{
			if (TvInterop.ApplyOperation(message.Operation, null, null, 0.0))
			{
				Send(message, prior);
			}
		}

		private static void ForwardSeek(double fromPosition, double delta)
		{
			Send(new TvSeekMessage
			{
				Delta = delta
			}, default(PlaybackUndoState), fromPosition);
		}
	}
	[ServerBehaviour]
	public sealed class TvHostBehaviour : CoopBehaviour
	{
		private static TvHostBehaviour _active;

		private float _lastSeekInputTime;

		private void OnEnable()
		{
			try
			{
				ResetSessionState();
				_active = this;
				SceneManager.sceneLoaded += OnSceneLoaded;
				ApplyPatches();
				foreach (Component item in TvInterop.Controllers())
				{
					OnControllerLifecycle(item);
				}
			}
			catch (Exception ex)
			{
				CoopLog.Error("TV host initialization failed: " + ex);
				SceneManager.sceneLoaded -= OnSceneLoaded;
				if (_active == this)
				{
					_active = null;
				}
				ResetSessionState();
				throw;
			}
		}

		[IntentValidator]
		private IntentValidation ValidateNext(CoopMessageContext context, TvNextMessage message)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return ValidateAction(message);
		}

		[IntentValidator]
		private IntentValidation ValidatePrevious(CoopMessageContext context, TvPreviousMessage message)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return ValidateAction(message);
		}

		[IntentValidator]
		private IntentValidation ValidateOpen(CoopMessageContext context, TvOpenMessage message)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return ValidateAction(message);
		}

		[IntentValidator]
		private IntentValidation ValidatePause(CoopMessageContext context, TvPauseMessage message)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return ValidateAction(message);
		}

		[IntentValidator]
		private IntentValidation ValidatePower(CoopMessageContext context, TvPowerMessage message)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return ValidateAction(message);
		}

		[IntentValidator]
		private IntentValidation ValidateShuffle(CoopMessageContext context, TvShuffleMessage message)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return ValidateAction(message);
		}

		[IntentValidator]
		private IntentValidation ValidateSeek(CoopMessageContext context, TvSeekMessage message)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return ValidateAction(message);
		}

		private static IntentValidation ValidateAction(TvActionMessage message)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)message?.Tv == (Object)null || !TvInterop.Present || (Object)(object)TvInterop.ControllerFor(message.Tv) == (Object)null)
			{
				return IntentValidation.Deny("TV is not available");
			}
			return IntentValidation.Allow();
		}

		[IntentRejected]
		private void RejectNext(CoopMessageContext context, TvNextMessage message, string reason)
		{
			RejectAction(message);
		}

		[IntentRejected]
		private void RejectPrevious(CoopMessageContext context, TvPreviousMessage message, string reason)
		{
			RejectAction(message);
		}

		[IntentRejected]
		private void RejectOpen(CoopMessageContext context, TvOpenMessage message, string reason)
		{
			RejectAction(message);
		}

		[IntentRejected]
		private void RejectPause(CoopMessageContext context, TvPauseMessage message, string reason)
		{
			RejectAction(message);
		}

		[IntentRejected]
		private void RejectPower(CoopMessageContext context, TvPowerMessage message, string reason)
		{
			RejectAction(message);
		}

		[IntentRejected]
		private void RejectShuffle(CoopMessageContext context, TvShuffleMessage message, string reason)
		{
			RejectAction(message);
		}

		[IntentRejected]
		private void RejectSeek(CoopMessageContext context, TvSeekMessage message, string reason)
		{
			RejectAction(message);
		}

		private void RejectAction(TvActionMessage message)
		{
			Component val = ((message == null) ? null : TvInterop.ControllerFor(message.Tv));
			if ((Object)(object)val != (Object)null)
			{
				PublishRejected(val, ((ActionMessage)message).ActionId);
			}
		}

		[MessageHandler]
		private ActionOutcome HandleNext(CoopMessageContext context, TvNextMessage message)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return Handle(context, message);
		}

		[MessageHandler]
		private ActionOutcome HandlePrevious(CoopMessageContext context, TvPreviousMessage message)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return Handle(context, message);
		}

		[MessageHandler]
		private ActionOutcome HandleOpen(CoopMessageContext context, TvOpenMessage message)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return Handle(context, message);
		}

		[MessageHandler]
		private ActionOutcome HandlePause(CoopMessageContext context, TvPauseMessage message)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return Handle(context, message);
		}

		[MessageHandler]
		private ActionOutcome HandlePower(CoopMessageContext context, TvPowerMessage message)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return Handle(context, message);
		}

		[MessageHandler]
		private ActionOutcome HandleShuffle(CoopMessageContext context, TvShuffleMessage message)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return Handle(context, message);
		}

		[MessageHandler]
		private ActionOutcome HandleSeek(CoopMessageContext context, TvSeekMessage message)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return Handle(context, message);
		}

		private ActionOutcome Handle(CoopMessageContext context, TvActionMessage message)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			if (message == null || !TvInterop.Present)
			{
				return ActionOutcome.Reject("TV is not available", (ActionResponseMessage)null);
			}
			try
			{
				message.Apply();
			}
			catch (InvalidOperationException)
			{
				Component val = TvInterop.ControllerFor(message.Tv);
				if (!TvInterop.Present || (Object)(object)val == (Object)null)
				{
					goto IL_0050;
				}
				InteractableObject obj = TvInterop.OwnerOf(val);
				if (((obj != null) ? InteractableObjectExtensions.GetExtendedInformation<TvState>(obj) : null) == null)
				{
					goto IL_0050;
				}
				message.Rejected = true;
				goto end_IL_001f;
				IL_0050:
				throw;
				end_IL_001f:;
			}
			Component val2 = TvInterop.ControllerFor(message.Tv);
			if ((Object)(object)val2 == (Object)null)
			{
				CoopLog.Warn("[tv] action applied but the TV controller is gone; no state to publish for action " + ((ActionMessage)message).ActionId);
				return ActionOutcome.Applied((ActionResponseMessage)null);
			}
			if (message.Rejected)
			{
				PublishRejected(val2, ((ActionMessage)message).ActionId);
				return ActionOutcome.Reject("the host refused the TV control", (ActionResponseMessage)null);
			}
			TvOperation operation = message.Operation;
			CaptureHostState(val2, operation, ((ActionMessage)message).ActionId, message.IsMedia, out var snapshot);
			if (snapshot == null)
			{
				InteractableObject obj2 = TvInterop.OwnerOf(val2);
				TvState tvState = ((obj2 != null) ? InteractableObjectExtensions.GetExtendedInformation<TvState>(obj2) : null);
				if (tvState != null)
				{
					snapshot = CopyState(tvState, operation, ((ActionMessage)message).ActionId, tvState.Barrier, resume: false);
				}
			}
			if (snapshot != null)
			{
				PublishState(val2, snapshot);
			}
			return ActionOutcome.Applied((ActionResponseMessage)null);
		}

		private void OnDisable()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
			if (_active == this)
			{
				_active = null;
			}
			ResetSessionState();
		}

		private void ResetSessionState()
		{
			TvInterop.ResetState();
			_lastSeekInputTime = -0.25f;
		}

		private void OnSceneLoaded(Scene _, LoadSceneMode mode)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			if ((int)mode == 0)
			{
				TvInterop.ResetState();
			}
		}

		private void OnControllerLifecycle(Component controller)
		{
			if (!TvInterop.Present)
			{
				return;
			}
			if (controller == null)
			{
				controller = TvInterop.CurrentController;
			}
			if (!((Object)(object)controller == (Object)null) && !TvInterop.ApplyingRemote)
			{
				TvInterop.AttachVideoErrorHandler(controller, OnHostVideoError);
				if (!((Object)(object)TvInterop.OwnerOf(controller) == (Object)null) && CaptureHostState(controller, TvOperation.Open, Guid.Empty, startBarrier: false, out var snapshot) && !string.IsNullOrEmpty(snapshot.SourceUrl))
				{
					PublishState(controller, snapshot);
				}
			}
		}

		private bool CaptureHostState(Component controller, TvOperation operation, Guid actionId, bool startBarrier, out TvState snapshot)
		{
			snapshot = null;
			InteractableObject val = TvInterop.OwnerOf(controller);
			if ((Object)(object)controller == (Object)null || (Object)(object)val == (Object)null)
			{
				return false;
			}
			TvState extendedInformation = InteractableObjectExtensions.GetExtendedInformation<TvState>(val);
			TvInterop.BeginFocus(controller);
			try
			{
				bool isPlayingStream = TvInterop.IsPlayingStream;
				bool isFetching = TvInterop.IsFetching;
				bool poweredOff = TvInterop.PoweredOff;
				bool flag = isPlayingStream || isFetching || !string.IsNullOrWhiteSpace(TvInterop.PendingSourceUrl);
				if (isPlayingStream)
				{
					TvInterop.ClearPendingSourceUrl();
				}
				string text = ((!string.IsNullOrWhiteSpace(TvInterop.SourceUrl)) ? TvInterop.SourceUrl : (flag ? TvInterop.StreamUrl : extendedInformation?.SourceUrl));
				if (flag && string.IsNullOrWhiteSpace(text))
				{
					return false;
				}
				string text2 = (flag ? TvInterop.StreamUrl : extendedInformation?.StreamUrl);
				string text3 = (flag ? TvInterop.StreamTitle : extendedInformation?.StreamTitle);
				string text4 = (flag ? TvInterop.PlaylistUrlValue : extendedInformation?.PlaylistUrl);
				bool flag2 = flag && TvInterop.IsLive;
				bool flag3 = flag && TvInterop.IsSegmentedVod;
				bool flag4 = (flag ? TvInterop.Paused : (extendedInformation?.Paused ?? false));
				bool flag5 = (flag ? TvInterop.Shuffle : (extendedInformation?.Shuffle ?? false));
				int num = (flag ? TvInterop.PlaylistIndexValue : (extendedInformation?.PlaylistIndex ?? 0));
				double position = TvInterop.Position;
				bool flag6 = !string.Equals(text, extendedInformation?.SourceUrl, StringComparison.Ordinal) || !string.Equals(text4, extendedInformation?.PlaylistUrl, StringComparison.Ordinal) || (flag && num != extendedInformation?.PlaylistIndex);
				bool result = extendedInformation == null || flag6 || text2 != extendedInformation.StreamUrl || text3 != extendedInformation.StreamTitle || flag2 != extendedInformation.IsLive || flag3 != extendedInformation.IsSegmentedVod || flag4 != extendedInformation.Paused || poweredOff != extendedInformation.PoweredOff || flag5 != extendedInformation.Shuffle || num != extendedInformation.PlaylistIndex || position != extendedInformation.Position;
				int num2 = extendedInformation?.Generation ?? 0;
				bool barrier = extendedInformation?.Barrier ?? false;
				if (flag6)
				{
					num2++;
					if (startBarrier && !string.IsNullOrEmpty(text))
					{
						barrier = true;
						TvInterop.SetSharedPaused(paused: true);
					}
				}
				snapshot = new TvState
				{
					SourceUrl = text,
					StreamUrl = text2,
					StreamTitle = text3,
					PlaylistUrl = text4,
					IsLive = flag2,
					IsSegmentedVod = flag3,
					PlaylistIndex = num,
					Position = position,
					Paused = flag4,
					PoweredOff = poweredOff,
					Shuffle = flag5,
					Barrier = barrier,
					Resume = false,
					Generation = num2,
					Operation = operation,
					ActionId = actionId
				};
				return result;
			}
			finally
			{
				TvInterop.EndFocus();
			}
		}

		private static TvState CopyState(TvState source, TvOperation operation, Guid actionId, bool barrier, bool resume, bool rejected = false)
		{
			return new TvState
			{
				Rejected = rejected,
				SourceUrl = source.SourceUrl,
				StreamUrl = source.StreamUrl,
				StreamTitle = source.StreamTitle,
				PlaylistUrl = source.PlaylistUrl,
				IsLive = source.IsLive,
				IsSegmentedVod = source.IsSegmentedVod,
				PlaylistIndex = source.PlaylistIndex,
				Position = source.Position,
				Paused = source.Paused,
				PoweredOff = source.PoweredOff,
				Shuffle = source.Shuffle,
				Barrier = barrier,
				Resume = resume,
				Generation = source.Generation,
				Operation = operation,
				ActionId = actionId
			};
		}

		private void PublishScalarDelta(Component controller, TvOperation operation, Guid actionId)
		{
			if (((CoopBehaviour)this).Context.InGame && TvInterop.Present)
			{
				CaptureHostState(controller, operation, actionId, startBarrier: false, out var snapshot);
				if (snapshot != null)
				{
					PublishState(controller, snapshot);
				}
			}
		}

		private void PublishBarrierDelta(Component controller, bool barrier, Guid actionId)
		{
			if (((CoopBehaviour)this).Context.InGame && TvInterop.Present)
			{
				InteractableObject obj = TvInterop.OwnerOf(controller);
				TvState tvState = ((obj != null) ? InteractableObjectExtensions.GetExtendedInformation<TvState>(obj) : null);
				if (tvState != null)
				{
					PublishState(controller, CopyState(tvState, TvOperation.Barrier, actionId, barrier, resume: true));
				}
			}
		}

		private void PublishState(Component controller, TvState snapshot)
		{
			if (((CoopBehaviour)this).Context.InGame && TvInterop.Present && snapshot != null)
			{
				CoopLog.Info("[tv] host state source=" + (snapshot.SourceUrl ?? "<null>") + " op=" + snapshot.Operation.ToString() + " action=" + snapshot.ActionId);
				InteractableObject obj = TvInterop.OwnerOf(controller);
				if (obj != null)
				{
					InteractableObjectExtensions.SetExtendedInformation<TvState>(obj, snapshot);
				}
			}
		}

		private void PublishRejected(Component controller, Guid actionId)
		{
			InteractableObject obj = TvInterop.OwnerOf(controller);
			TvState tvState = ((obj != null) ? InteractableObjectExtensions.GetExtendedInformation<TvState>(obj) : null);
			if (tvState != null)
			{
				PublishState(controller, CopyState(tvState, tvState.Operation, actionId, tvState.Barrier, resume: false, rejected: true));
			}
		}

		private void ApplyPatches()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Expected O, but got Unknown
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: 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_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Expected O, but got Unknown
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Expected O, but got Unknown
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Expected O, but got Unknown
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Expected O, but got Unknown
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Expected O, but got Unknown
			//IL_01fb: Expected O, but got Unknown
			if (TvInterop.Present)
			{
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "OnEnable", (HarmonyMethod)null, new HarmonyMethod(typeof(TvHostBehaviour), "ControllerLifecyclePostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "Start", (HarmonyMethod)null, new HarmonyMethod(typeof(TvHostBehaviour), "ControllerLifecyclePostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "ChangeVideo", (HarmonyMethod)null, new HarmonyMethod(typeof(TvHostBehaviour), "ControllerLifecyclePostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "HandleGlobalInput", (HarmonyMethod)null, new HarmonyMethod(typeof(TvHostBehaviour), "HostGlobalInputPostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "StreamYouTube", (HarmonyMethod)null, new HarmonyMethod(typeof(TvHostBehaviour), "StreamYouTubePostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "ChangeToUrl", (HarmonyMethod)null, new HarmonyMethod(typeof(TvHostBehaviour), "ChangeToUrlPostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "PlayPlaylistItem", (HarmonyMethod)null, new HarmonyMethod(typeof(TvHostBehaviour), "PlaylistItemPostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "ToggleGlobalPause", (HarmonyMethod)null, new HarmonyMethod(typeof(TvHostBehaviour), "PausePostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "RemotePower", (HarmonyMethod)null, new HarmonyMethod(typeof(TvHostBehaviour), "PowerPostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "RemoteShuffle", (HarmonyMethod)null, new HarmonyMethod(typeof(TvHostBehaviour), "ShufflePostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "OnDisable", (HarmonyMethod)null, new HarmonyMethod(typeof(TvHostBehaviour), "ControllerDisablePostfix", (Type[])null), (Type[])null);
				((CoopBehaviour)this).TryPatch(TvInterop.OptionalControllerType, "OnLocalPrepared", new HarmonyMethod(typeof(TvHostBehaviour), "LocalPreparedPrefix", (Type[])null), new HarmonyMethod(typeof(TvHostBehaviour), "LocalPreparedPostfix", (Type[])null), (Type[])null);
			}
		}

		private static void StreamYouTubePostfix(object __instance, string url)
		{
			Component controller = (Component)((__instance is Component) ? __instance : null);
			TvInterop.RegisterController(controller);
			TvInterop.StreamYouTubePostfix(controller, url);
			_active?.OnMediaSourceChanged(controller);
		}

		private static void ChangeToUrlPostfix(object __instance, string url, string title)
		{
			Component controller = (Component)((__instance is Component) ? __instance : null);
			TvInterop.RegisterController(controller);
			TvInterop.ChangeToUrlPostfix(controller, url);
			_active?.OnMediaSourceChanged(controller);
		}

		private static void PlaylistItemPostfix(object __instance)
		{
			Component controller = (Component)((__instance is Component) ? __instance : null);
			TvInterop.RegisterController(controller);
			if (!((Object)(object)_active == (Object)null) && !TvInterop.ApplyingRemote)
			{
				_active.OnMediaSourceChanged(controller);
			}
		}

		private static void PausePostfix(object __instance)
		{
			RegisterScalar(__instance, TvOperation.Pause);
		}

		private static void PowerPostfix(object __instance)
		{
			RegisterScalar(__instance, TvOperation.Power);
		}

		private static void ShufflePostfix(object __instance)
		{
			RegisterScalar(__instance, TvOperation.Shuffle);
		}

		private static void RegisterScalar(object instance, TvOperation operation)
		{
			Component controller = (Component)((instance is Component) ? instance : null);
			TvInterop.RegisterController(controller);
			_active?.OnScalarChanged(controller, operation);
		}

		private void OnMediaSourceChanged(Component controller)
		{
			if (!TvInterop.ApplyingRemote && !((Object)(object)controller == (Object)null) && !((Object)(object)TvInterop.OwnerOf(controller) == (Object)null) && CaptureHostState(controller, TvOperation.Open, Guid.Empty, startBarrier: true, out var snapshot) && snapshot != null && !string.IsNullOrEmpty(snapshot.SourceUrl))
			{
				PublishState(controller, snapshot);
			}
		}

		private void OnScalarChanged(Component controller, TvOperation operation)
		{
			if (!TvInterop.ApplyingRemote && !((Object)(object)controller == (Object)null))
			{
				PublishScalarDelta(controller, operation, Guid.Empty);
			}
		}

		private static void ControllerLifecyclePostfix(object __instance)
		{
			Component controller = (Component)((__instance is Component) ? __instance : null);
			TvInterop.RegisterController(controller);
			_active?.OnControllerLifecycle(controller);
		}

		private static void ControllerDisablePostfix(object __instance)
		{
			Component val = (Component)((__instance is Component) ? __instance : null);
			TvHostBehaviour active = _active;
			if ((Object)(object)active != (Object)null && (Object)(object)val != (Object)null)
			{
				InteractableObject obj = TvInterop.OwnerOf(val);
				TvState obj2 = ((obj != null) ? InteractableObjectExtensions.GetExtendedInformation<TvState>(obj) : null);
				if (obj2 != null && obj2.Barrier)
				{
					active.AbortBarrier(val, "host TV controller playback was canceled");
					active.PublishBarrierDelta(val, barrier: false, Guid.Empty);
				}
			}
			TvInterop.ForgetController(val);
		}

		private static void HostGlobalInputPostfix()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			if ((!Input.GetKey((KeyCode)308) && !Input.GetKey((KeyCode)307)) || (!Input.GetKey((KeyCode)93) && !Input.GetKey((KeyCode)91) && Mathf.Abs(Input.mouseScrollDelta.y) <= 0.0001f) || (!TvInterop.IsPlayingStream && !TvInterop.IsFetching))
			{
				return;
			}
			Component currentController = TvInterop.CurrentController;
			if (!((Object)(object)_active == (Object)null) && !((Object)(object)currentController == (Object)null))
			{
				float unscaledTime = Time.unscaledTime;
				if (!float.IsNaN(unscaledTime) && !float.IsInfinity(unscaledTime) && unscaledTime - _active._lastSeekInputTime >= 0.25f)
				{
					_active._lastSeekInputTime = unscaledTime;
					_active.PublishScalarDelta(currentController, TvOperation.Seek, Guid.Empty);
				}
			}
		}

		private static void LocalPreparedPrefix(object __instance, object source)
		{
			Component val = (Component)((__instance is Component) ? __instance : null);
			TvInterop.RegisterController(val);
			if ((Object)(object)_active == (Object)null || (Object)(object)val == (Object)null)
			{
				return;
			}
			TvInterop.BeginFocus(val);
			try
			{
				_active.BeforeLocalPrepared(val, source);
			}
			finally
			{
				TvInterop.EndFocus();
			}
		}

		private static void LocalPreparedPostfix(object __instance, object source)
		{
			Component val = (Component)((__instance is Component) ? __instance : null);
			TvInterop.RegisterController(val);
			if (!((Object)(object)_active == (Object)null) && !((Object)(object)val == (Object)null))
			{
				TvInterop.BeginFocus(val);
				try
				{
					_active.AfterLocalPrepared(val, source);
				}
				finally
				{
					TvInterop.EndFocus();
				}
				_active.OnControllerLifecycle(val);
			}
		}

		private void BeforeLocalPrepared(Component controller, object source)
		{
			InteractableObject val = TvInterop.OwnerOf(controller);
			if (!((Object)(object)val == (Object)null))
			{
				TvState extendedInformation = InteractableObjectExtensions.GetExtendedInformation<TvState>(val);
				if (extendedInformation != null && extendedInformation.Barrier && TvInterop.IsMainPreparedPlayer(controller, source))
				{
					TvInterop.SetSharedPausedForPrepare(paused: false);
				}
			}
		}

		private void AfterLocalPrepared(Component controller, object source)
		{
			InteractableObject val = TvInterop.OwnerOf(controller);
			if (!((Object)(object)val == (Object)null))
			{
				TvState extendedInformation = InteractableObjectExtensions.GetExtendedInformation<TvState>(val);
				if (extendedInformation != null && extendedInformation.Barrier && TvInterop.IsMainPreparedPlayer(controller, source))
				{
					TvInterop.PausePreparedStream(controller);
					CompleteBarrier(controller);
					PublishBarrierDelta(controller, barrier: false, Guid.Empty);
				}
			}
		}

		private void OnHostVideoError(Component failed, string message)
		{
			InteractableObject val = TvInterop.OwnerOf(failed);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			TvState extendedInformation = InteractableObjectExtensions.GetExtendedInformation<TvState>(val);
			CoopLog.Error("Host TV VideoPlayer failed: " + (message ?? "unknown error"));
			TvInterop.BeginFocus(failed);
			try
			{
				TvInterop.AbortSharedPlayback();
				AbortBarrier(failed, "host TV playback failed");
				if (((CoopBehaviour)this).Context.InGame && TvInterop.Present)
				{
					PublishState(failed, new TvState
					{
						SourceUrl = null,
						StreamUrl = null,
						StreamTitle = null,
						PlaylistUrl = null,
						IsLive = false,
						IsSegmentedVod = false,
						PlaylistIndex = 0,
						Position = 0.0,
						Paused = false,
						PoweredOff = TvInterop.PoweredOff,
						Shuffle = TvInterop.Shuffle,
						Barrier = false,
						Resume = true,
						Generation = (extendedInformation?.Generation ?? 0),
						Operation = TvOperation.Error,
						ActionId = Guid.Empty
					});
				}
			}
			finally
			{
				TvInterop.EndFocus();
			}
		}

		private void CompleteBarrier(Component controller)
		{
			TvInterop.ResumePlayback();
		}

		private void AbortBarrier(Component controller, string reason)
		{
			TvInterop.ResumePlayback();
			CoopLog.Warn("TV load barrier aborted: " + reason);
		}
	}
	internal static class TvInterop
	{
		internal enum FeatureAvailability
		{
			Absent,
			Ready,
			Drifted
		}

		private sealed class ChannelPlayback
		{
			internal string PendingSourceUrl;

			internal string RequestedSourceUrl;

			internal string LaunchedSource;

			internal int LaunchedPlaylistIndex;

			internal bool StreamLaunchPending;

			internal int PlaybackGeneration;

			internal bool Barrier;
		}

		private sealed class PlayerPosition
		{
			internal double Pending;

			internal bool HasPending;

			internal int Generation;
		}

		private sealed class VideoErrorSink
		{
			internal Component Controller;

			internal Action<Component, string> Handler;

			internal void OnError(object _, string message)
			{
				Handler?.Invoke(Controller, message);
			}
		}

		private sealed class ErrorBinding
		{
			internal object Player;

			internal Delegate Handler;
		}

		private const string AssemblyName = "RTCGOCustomScripts";

		internal const double MaxPositionSeconds = 86400.0;

		internal const double MaxSeekDeltaSeconds = 300.0;

		private static readonly Type ControllerType = CoopReflection.OptionalType("Scripts.VideoPlayerController", "RTCGOCustomScripts");

		private static readonly Type ChannelType = CoopReflection.OptionalType("Scripts.TvChannel", "RTCGOCustomScripts");

		private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		private static readonly FieldInfo ChannelField = Field("Ch");

		private static readonly FieldInfo AllTvs = Field("AllTVs");

		private static readonly FieldInfo Enrolled = ChannelState("enrolledTVs");

		private static readonly FieldInfo SharedVideoIndex = ChannelState("sharedVideoIndex");

		private static readonly FieldInfo StreamUrlField = ChannelState("activeStreamUrl");

		private static readonly FieldInfo StreamTitleField = ChannelState("activeStreamTitle");

		private static readonly FieldInfo PlaylistUrl = ChannelState("activePlaylistUrl");

		private static readonly FieldInfo PlaylistIndex = ChannelState("activePlaylistIndex");

		private static readonly FieldInfo Live = ChannelState("isLiveStream");

		private static readonly FieldInfo Segmented = ChannelState("isSegmentedVod");

		private static readonly FieldInfo Playing = ChannelState("isPlayingStream");

		private static readonly FieldInfo Fetching = ChannelState("isFetchingUrl");

		private static readonly FieldInfo PausedField = ChannelState("isSharedPaused");

		private static readonly FieldInfo Powered = ChannelState("isPoweredOff");

		private static readonly FieldInfo ShuffleField = ChannelState("isShuffleMode");

		private static readonly FieldInfo LastTime = ChannelState("lastKnownMasterTime");

		private static readonly FieldInfo PendingUrlField = ChannelState("pendingYouTubeUrl");

		private static readonly FieldInfo VideoPlayerField = Field("m_VideoPlayer");

		private static readonly EventInfo VideoErrorReceived = VideoPlayerField?.FieldType.GetEvent("errorReceived", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

		private static readonly MethodInfo ChangeUrl = Method("ChangeToUrl", typeof(string), typeof(string));

		private static readonly MethodInfo PlayPlaylistItem = Method("PlayPlaylistItem", typeof(int));

		private static readonly MethodInfo Stream = Method("StreamYouTube", typeof(string));

		private static readonly MethodInfo QualityChoice = Method("OnQualityChoice", typeof(bool));

		private static readonly MethodInfo ChangeVideo = Method("ChangeVideo", typeof(int));

		private static readonly MethodInfo BroadcastChange = Method("BroadcastChange", typeof(int));

		private static readonly MethodInfo TogglePause = Method("ToggleGlobalPause");

		private static readonly MethodInfo RemotePower = Method("RemotePower");

		private static readonly MethodInfo RemotePlayPause = Method("RemotePlayPause");

		private static readonly MethodInfo RemoteNext = Method("RemoteNext");

		private static readonly MethodInfo RemotePrev = Method("RemotePrev");

		private static readonly MethodInfo RemoteShuffle = Method("RemoteShuffle");

		private static readonly MethodInfo SoundTv = SilentMethod("SoundTV");

		private static readonly FeatureAvailability AvailabilityState = ValidateSurface();

		private static bool _logged;

		private static bool _availabilityLogged;

		private static Component _master;

		private static Component _focus;

		private static int _focusDepth;

		private static readonly Dictionary<object, ChannelPlayback> Playbacks = new Dictionary<object, ChannelPlayback>();

		private static readonly Dictionary<Component, PlayerPosition> Positions = new Dictionary<Component, PlayerPosition>();

		private static readonly Dictionary<Component, ErrorBinding> ErrorBindings = new Dictionary<Component, ErrorBinding>();

		internal static bool ApplyingRemote;

		internal static Component CurrentController => Master();

		internal static Component ActionController => _master ?? Master();

		internal static string StreamUrl => Get<string>(StreamUrlField);

		internal static string StreamTitle => Get<string>(StreamTitleField);

		internal static string PlaylistUrlValue => Get<string>(PlaylistUrl);

		internal static bool IsPlayingStream => Get(Playing, fallback: false);

		internal static bool IsFetching => Get(Fetching, fallback: false);

		internal static bool IsLive => Get(Live, fallback: false);

		internal static bool IsSegmentedVod => Get(Segmented, fallback: false);

		internal static bool Paused => Get(PausedField, fallback: false);

		internal static bool PoweredOff => Get(Powered, fallback: false);

		internal static bool Shuffle => Get(ShuffleField, fallback: false);

		internal static int PlaylistIndexValue => Get(PlaylistIndex, 1);

		internal static double Position => GetDouble(LastTime, 0.0);

		internal static bool IsPlaylist => !string.IsNullOrEmpty(PlaylistUrlValue);

		internal static string SourceUrl => PlaybackFor(Master())?.RequestedSourceUrl;

		internal static string PendingSourceUrl => PlaybackFor(Master())?.PendingSourceUrl;

		internal static int EnrolledCount
		{
			get
			{
				object obj = ChannelOf(Master());
				if (obj != null)
				{
					return (Enrolled?.GetValue(obj) as IList)?.Count ?? 0;
				}
				return 0;
			}
		}

		internal static bool EnrollmentReady => EnrolledCount > 0;

		internal static Type OptionalControllerType => ControllerType;

		internal static FeatureAvailability Availability
		{
			get
			{
				LogAvailability();
				return AvailabilityState;
			}
		}

		internal static string UnavailableReason
		{
			get
			{
				if (AvailabilityState == FeatureAvailability.Absent)
				{
					return "RTCGO Custom TV is not installed";
				}
				if (AvailabilityState != FeatureAvailability.Drifted)
				{
					return null;
				}
				return "RTCGO Custom TV reflection surface changed";
			}
		}

		internal static bool Present
		{
			get
			{
				bool num = Availability == FeatureAvailability.Ready;
				if (num && !_logged)
				{
					_logged = true;
					CoopLog.Info("RTCGO Custom TV detected - shared playback is available");
				}
				return num;
			}
		}

		internal static string PendingUrl => Get<string>(PendingUrlField);

		internal static InteractableObject OwnerOf(Component controller)
		{
			if (!((Object)(object)controller == (Object)null) && !(ControllerType == null))
			{
				return controller.GetComponentInParent<InteractableObject>();
			}
			return null;
		}

		internal static Component ControllerFor(InteractableObject owner)
		{
			if ((Object)(object)owner == (Object)null || ControllerType == null)
			{
				return null;
			}
			Component componentInChildren = ((Component)owner).GetComponentInChildren(ControllerType, true);
			if (!((Object)(object)componentInChildren != (Object)null))
			{
				return ((Component)owner).GetComponentInParent(ControllerType, true);
			}
			return componentInChildren;
		}

		private static Component Master()
		{
			try
			{
				Component focus = _focus;
				if ((Object)(object)focus != (Object)null)
				{
					return EnrolledMaster(focus) ?? focus;
				}
				Component master = _master;
				if ((Object)(object)master != (Object)null)
				{
					Component val = EnrolledMaster(master);
					if ((Object)(object)val != (Object)null)
					{
						return val;
					}
				}
				Component val2 = SoundTvController();
				if ((Object)(object)val2 != (Object)null)
				{
					return EnrolledMaster(val2) ?? val2;
				}
				if ((Object)(object)master != (Object)null)
				{
					return master;
				}
				if (AllTvs?.GetValue(null) is IList list)
				{
					for (int i = 0; i < list.Count; i++)
					{
						object? obj = list[i];
						Component val3 = EnrolledMaster((Component)((obj is Component) ? obj : null));
						if ((Object)(object)val3 != (Object)null)
						{
							return val3;
						}
					}
				}
				return null;
			}
			catch (Exception ex)
			{
				CoopLog.Swallow(ex, "Master", "/_work/cardshopcoop-kig22Lfiw1V1E/CardShopCoop/CardShopCoop/src/CardShopCoop.CustomTv/TvInterop.Controllers.cs", 84);
				return null;
			}
		}

		private static Component SoundTvController()
		{
			if (SoundTv == null)
			{
				return null;
			}
			try
			{
				object? obj = SoundTv.Invoke(null, null);
				return (Component)((obj is Component) ? obj : null);
			}
			catch (Exception ex)
			{
				CoopLog.Swallow(ex, "SoundTvController", "/_work/cardshopcoop-kig22Lfiw1V1E/CardShopCoop/CardShopCoop/src/CardShopCoop.CustomTv/TvInterop.Controllers.cs", 102);
				return null;
			}
		}

		internal static Component ChannelMaster(Component controller)
		{
			object obj;
			if (!((Object)(object)controller == (Object)null))
			{
				obj = EnrolledMaster(controller);
				if (obj == null)
				{
					return controller;
				}
			}
			else
			{
				obj = null;
			}
			return (Component)obj;
		}

		internal static IEnumerable<Component> Controllers()
		{
			if (!(AllTvs?.GetValue(null) is IList all))
			{
				yield break;
			}
			for (int i = 0; i < all.Count; i++)
			{
				object? obj = all[i];
				Component val = (Component)((obj is Component) ? obj : null);
				if (val != null && (Object)(object)val != (Object)null)
				{
					yield return val;
				}
			}
		}

		internal static bool IsSoundController(Component controller)
		{
			if ((Object)(object)controller == (Object)null)
			{
				return false;
			}
			return ChannelMaster(SoundTvController() ?? controller) == controller;
		}

		private static Component EnrolledMaster(Component controller)
		{
			if ((Object)(object)controller == (Object)null)
			{
				return null;
			}
			object obj = ChannelOf(controller);
			IList list = ((obj == null) ? null : (Enrolled?.GetValue(obj) as IList));
			if (list == null)
			{
				return null;
			}
			for (int i = 0; i < list.Count; i++)
			{
				object? obj2 = list[i];
				Component val = (Component)((obj2 is Component) ? obj2 : null);
				if (val != null && (Object)(object)val != (Object)null)
				{
					return val;
				}
			}
			return null;
		}

		internal static object ChannelOf(Component controller)
		{
			if (!((Object)(object)controller == (Object)null) && !(ChannelField == null))
			{
				return ChannelField.GetValue(controller);
			}
			return null;
		}

		internal static void RegisterController(Component controller)
		{
			if ((Object)(object)controller != (Object)null && ControllerType.IsInstanceOfType(controller))
			{
				_master = controller;
			}
		}

		internal static void ForgetController(Component controller)
		{
			if (_master == controller)
			{
				_master = null;
			}
		}

		private static FieldInfo Field(string name)
		{
			return CoopReflection.OptionalField(ControllerType, name);
		}

		private static FieldInfo ChannelState(string name)
		{
			if (!(ChannelType == null))
			{
				return CoopReflection.OptionalField(ChannelType, name);
			}
			return null;
		}

		private static MethodInfo Method(string name, params Type[] arguments)
		{
			return CoopReflection.OptionalMethod(ControllerType, name, arguments);
		}

		private static MethodInfo SilentMethod(string name)
		{
			return ControllerType?.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		}

		private static FeatureAvailability ValidateSurface()
		{
			if (ControllerType == null)
			{
				return FeatureAvailability.Absent;
			}
			if (!typeof(MonoBehaviour).IsAssignableFrom(ControllerType))
			{
				return FeatureAvailability.Drifted;
			}
			if (ChannelType == null || ChannelField == null || !ChannelType.IsAssignableFrom(ChannelField.FieldType))
			{
				return FeatureAvailability.Drifted;
			}
			FieldInfo[] array = new FieldInfo[15]
			{
				Enrolled, SharedVideoIndex, StreamUrlField, StreamTitleField, PlaylistUrl, PlaylistIndex, Live, Segmented, Playing, Fetching,
				PausedField, Powered, ShuffleField, LastTime, PendingUrlField
			};
			for (int i = 0; i < array.Length; i++)
			{
				if (array[i] == null)
				{
					return FeatureAvailability.Drifted;
				}
			}
			MethodInfo[] array2 = new MethodInfo[12]
			{
				ChangeUrl, PlayPlaylistItem, Stream, QualityChoice, ChangeVideo, BroadcastChange, TogglePause, RemotePower, RemotePlayPause, RemoteNext,
				RemotePrev, RemoteShuffle
			};
			for (int j = 0; j < array2.Length; j++)
			{
				if (array2[j] == null)
				{
					return FeatureAvailability.Drifted;
				}
			}
			if (!typeof(IList).IsAssignableFrom(Enrolled.FieldType))
			{
				return FeatureAvailability.Drifted;
			}
			if (!typeof(IEnumerator).IsAssignableFrom(Stream.ReturnType))
			{
				return FeatureAvailability.Drifted;
			}
			if (VideoPlayerField == null || VideoErrorReceived == null)
			{
				return FeatureAvailability.Drifted;
			}
			Type fieldType = VideoPlayerField.FieldType;
			if (CoopReflection.OptionalProperty(fieldType, "isPrepared") == null || CoopReflection.OptionalProperty(fieldType, "time") == null || CoopReflection.OptionalProperty(fieldType, "length") == null)
			{
				return FeatureAvailability.Drifted;
			}
			return FeatureAvailability.Ready;
		}

		private static void LogAvailability()
		{
			if (!_availabilityLogged)
			{
				_availabilityLogged = true;
				if (AvailabilityState == FeatureAvailability.Drifted)
				{
					CoopLog.Error("TV integration disabled: " + UnavailableReason);
				}
				else if (AvailabilityState == FeatureAvailability.Absent)
				{
					CoopLog.Info("RTCGO Custom TV is not installed - shared TV disabled");
				}
			}
		}

		private static object Get(FieldInfo field)
		{
			if (field == null)
			{
				return null;
			}
			if (field.IsStatic)
			{
				return field.GetValue(null);
			}
			object obj = ChannelOf(Master());
			if (obj != null)
			{
				return field.GetValue(obj);
			}
			return null;
		}

		private static T Get<T>(FieldInfo field, T fallback = default(T))
		{
			try
			{
				object obj = Get(field);
				return (obj == null) ? fallback : ((T)obj);
			}
			catch (Exception ex)
			{
				CoopLog.Swallow(ex, "Get", "/_work/cardshopcoop-kig22Lfiw1V1E/CardShopCoop/CardShopCoop/src/CardShopCoop.CustomTv/TvInterop.cs", 274);
				return fallback;
			}
		}

		internal static void BeginFocus(Component controller)
		{
			if (_focusDepth++ == 0)
			{
				_focus = controller;
			}
		}

		internal static void EndFocus()
		{
			if (_focusDepth != 0 && --_focusDepth == 0)
			{
				_focus = null;
			}
		}

		internal static void ApplyOp(InteractableObject tv, TvOperation operation, string url, string title, double value)
		{
			Component val = ControllerFor(tv);
			if (!Present || (Object)(object)val == (Object)null)
			{
				throw new InvalidOperationException("The target TV is not available.");
			}
			BeginFocus(val);
			try
			{
				if (!ApplyOperation(operation, url, title, value))
				{
					throw new InvalidOperationException("The TV rejected the operation.");
				}
			}
			finally
			{
				EndFocus();
			}
		}

		internal static void UndoOp(InteractableObject tv, PlaybackUndoState previous)
		{
			Component val = ControllerFor(tv);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			BeginFocus(val);
			try
			{
				RestorePlaybackState(previous);
			}
			finally
			{
				EndFocus();
			}
		}

		internal static void UndoSeek(InteractableObject tv, double position)
		{
			Component val = ControllerFor(tv);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			BeginFocus(val);
			try
			{
				ApplySeek(position);
			}
			finally
			{
				EndFocus();
			}
		}

		internal static bool ApplyOperation(TvOperation operation, string url, string title, double value)
		{
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			if (!Present)
			{
				return false;
			}
			Component val = Master();
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			bool applyingRemote = ApplyingRemote;
			ApplyingRemote = true;
			try
			{
				switch (operation)
				{
				case TvOperation.Next:
					if (!IsPlaylist || PlayPlaylistItem == null)
					{
						return false;
					}
					PlayPlaylistItem.Invoke(val, new object[1] { PlaylistIndexValue + 1 });
					return true;
				case TvOperation.Previous:
					if (!IsPlaylist || PlayPlaylistItem == null)
					{
						return false;
					}
					PlayPlaylistItem.Invoke(val, new object[1] { Math.Max(1, PlaylistIndexValue - 1) });
					return true;
				case TvOperation.Pause:
					if (TogglePause == null)
					{
						return false;
					}
					TogglePause?.Invoke(val, null);
					return true;
				case TvOperation.Power:
					if (RemotePower != null)
					{
						RemotePower.Invoke(val, null);
						return true;
					}
					if (Powered == null)
					{
						return false;
					}
					SetField(Powered, !PoweredOff, val);
					return true;
				case TvOperation.Shuffle:
					if (ShuffleField == null)
					{
						return false;
					}
					if (ApplyRemoteShuffle())
					{
						return true;
					}
					SetField(ShuffleField, !Shuffle, val);
					return true;
				case TvOperation.Seek:
				{
					if (double.IsNaN(value) || double.IsInfinity(value) || Math.Abs(value) > 300.0)
					{
						return false;
					}
					object obj = VideoPlayer(val);
					if (obj == null || !GetProperty(obj, "isPrepared", fallback: false))
					{
						return false;
					}
					double num = GetPropertyDouble(obj, "time", Position);
					if (!IsValidPosition(num))
					{
						num = 0.0;
					}
					double position = num + value;
					if (!IsValidPosition(position))
					{
						return false;
					}
					double num2 = ClampPosition(obj, position);
					if (Math.Abs(num2 - num) <= 0.0001)
					{
						return false;
					}
					SetPlayerPosition(obj, num2);
					return true;
				}
				case TvOperation.Open:
					if (string.IsNullOrWhiteSpace(url))
					{
						return false;
					}
					SetField(PlaylistUrl, url.Contains("list=") ? url : null, val);
					if (Stream != null)
					{
						((MonoBehaviour)val).StartCoroutine((IEnumerator)Stream.Invoke(val, new object[1] { url }));
					}
					else
					{
						if (!(ChangeUrl != null))
						{
							return false;
						}
						ChangeUrl.Invoke(val, new object[2]
						{
							url,
							title ?? "Shared stream"
						});
					}
					return true;
				default:
					return false;
				}
			}
			finally
			{
				ApplyingRemote = applyingRemote;
			}
		}

		private static object VideoPlayer(Component master)
		{
			if (!((Object)(object)master == (Object)null) && !(VideoPlayerField == null))
			{
				return VideoPlayerField.GetValue(master);
			}
			return null;
		}

		private static void RequestPosition(Component master, double position)
		{
			ChannelPlayback channelPlayback = PlaybackFor(master);
			PlayerPosition playerPosition = PositionFor(master);
			if (channelPlayback != null && playerPosition != null)
			{
				playerPosition.Pending = position;
				playerPosition.HasPending = true;
				playerPosition.Generation = channelPlayback.PlaybackGeneration;
				if (ApplyPosition(master, position))
				{
					playerPosition.HasPending = false;
				}
			}
		}

		private static bool ApplyPosition(Component master, double position)
		{
			object obj = VideoPlayer(master);
			if (obj == null || !GetProperty(obj, "isPrepared", fallback: false))
			{
				return false;
			}
			SetPlayerPosition(obj, position);
			return true;
		}

		private static void SetPlayerPosition(object player, double position)
		{
			SetProperty(player, "time", position);
			SetLastTime(position);
		}

		private static void SetLastTime(double position)
		{
			if (!(LastTime == null))
			{
				object obj = (LastTime.IsStatic ? null : ChannelOf(Master()));
				if (LastTime.IsStatic || obj != null)
				{
					object value = Convert.ChangeType(position, LastTime.FieldType);
					LastTime.SetValue(obj, value);
				}
			}
		}

		private static bool IsValidPosition(double position)
		{
			if (!double.IsNaN(position) && !double.IsInfinity(position))
			{
				return position >= 0.0;
			}
			return false;
		}

		private static double ClampPosition(object player, double position)
		{
			if (!IsValidPosition(position))
			{
				return 0.0;
			}
			double propertyDouble = GetPropertyDouble(player, "length", double.NaN);
			double val = ((IsValidPosition(propertyDouble) && propertyDouble > 0.0) ? Math.Min(propertyDouble, 86400.0) : 86400.0);
			return Math.Min(position, val);
		}

		private static double GetDouble(FieldInfo field, double fallback)
		{
			try
			{
				object obj = Get(field);
				double num = ((obj == null) ? fallback : Convert.ToDouble(obj));
				return IsValidPosition(num) ? Math.Min(num, 86400.0) : fallback;
			}
			catch (Exception ex)
			{
				CoopLog.Swallow(ex, "GetDouble", "/_work/cardshopcoop-kig22Lfiw1V1E/CardShopCoop/CardShopCoop/src/CardShopCoop.CustomTv/TvInterop.Operations.cs", 297);
				return fallback;
			}
		}

		private static double GetPropertyDouble(object target, string name, double fallback)
		{
			try
			{
				object obj = CoopReflection.OptionalProperty(target.GetType(), name)?.GetValue(target, null);
				double num = ((obj == null) ? fallback : Convert.ToDouble(obj));
				return IsValidPosition(num) ? Math.Min(num, 86400.0) : fallback;
			}
			catch (Exception ex)
			{
				CoopLog.Swallow(ex, "GetPropertyDouble", "/_work/cardshopcoop-kig22Lfiw1V1E/CardShopCoop/CardShopCoop/src/CardShopCoop.CustomTv/TvInterop.Operations.cs", 313);
				return fallback;
			}
		}

		private static T GetProperty<T>(object target, string name, T fallback)
		{
			try
			{
				object obj = CoopReflection.OptionalProperty(target.GetType(), name)?.GetValue(target, null);
				return (obj == null) ? fallback : ((T)Convert.ChangeType(obj, typeof(T)));
			}
			catch (Exception ex)
			{
				CoopLog.Swallow(ex, "GetProperty", "/_work/cardshopcoop-kig22Lfiw1V1E/CardShopCoop/CardShopCoop/src/CardShopCoop.CustomTv/TvInterop.Operations.cs", 328);
				return fallback;
			}
		}

		private static void SetProperty(object target, string name, object value)
		{
			PropertyInfo propertyInfo = target?.GetType().GetProperty(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if (!(propertyInfo == null) && propertyInfo.CanWrite)
			{
				object value2 = value;
				if (value != null && propertyInfo.PropertyType != value.GetType())
				{
					value2 = Convert.ChangeType(value, propertyInfo.PropertyType);
				}
				propertyInfo.SetValue(target, value2, null);
			}
		}

		private static void SetField(FieldInfo field, object value, object instance)
		{
			if (field == null)
			{
				return;
			}
			object obj = (field.IsStatic ? null : ChannelOf((Component)((instance is Component) ? instance : null)));
			if (field.IsStatic || obj != null)
			{
				object value2 = value;
				if (value != null && field.FieldType != value.GetType())
				{
					value2 = Convert.ChangeType(value, field.FieldType);
				}
				field.SetValue(obj, value2);
			}
		}

		private static ChannelPlayback PlaybackFor(Component controller)
		{
			if ((Object)(object)controller == (Object)null)
			{
				controller = Master();
			}
			object obj = ChannelOf(controller);
			if (obj == null)
			{
				return null;
			}
			if (!Playbacks.TryGetValue(obj, out var value))
			{
				value = new ChannelPlayback();
				Playbacks.Add(obj, value);
			}
			return value;
		}

		private static PlayerPosition PositionFor(Component controller)
		{
			if ((Object)(object)controller == (Object)null)
			{
				return null;
			}
			if (!Positions.TryGetValue(controller, out var value))
			{
				value = new PlayerPosition();
				Positions.Add(controller, value);
			}
			return value;
		}

		internal static void RecordPendingSourceUrl(Component controller, string url)
		{
			ChannelPlayback channelPlayback = PlaybackFor(controller);
			if (channelPlayback != null && !string.IsNullOrWhiteSpace(url))
			{
				channelPlayback.RequestedSourceUrl = url;
				channelPlayback.PendingSourceUrl = url;
			}
		}

		internal static void RecordActiveSourceUrl(Component controller, string url)
		{
			ChannelPlayback channelPlayback = PlaybackFor(controller);
			if (channelPlayback != null && !string.IsNullOrWhiteSpace(url) && string.IsNullOrWhiteSpace(channelPlayback.RequestedSourceUrl))
			{
				channelPlayback.RequestedSourceUrl = url;
			}
		}

		internal static void ClearPendingSourceUrl()
		{
			ChannelPlayback channelPlayback = PlaybackFor(Master());
			if (channelPlayback != null)
			{
				channelPlayback.PendingSourceUrl = null;
			}
		}

		internal static void ClearSourceIdentity()
		{
			ChannelPlayback channelPlayback = PlaybackFor(Master());
			if (channelPlayback != null)
			{
				channelPlayback.PendingSourceUrl = null;
				channelPlayback.RequestedSourceUrl = null;
			}
		}

		internal static void ResetState()
		{
			DetachVideoErrorHandlers();
			_master = null;
			_focus = null;
			_focusDepth = 0;
			Playbacks.Clear();
			Positions.Clear();
			ApplyingRemote = false;
		}

		internal static void ApplyMediaState(TvState state)
		{
			if (!Present || state == null)
			{
				return;
			}
			string sourceUrl = state.SourceUrl;
			string streamTitle = state.StreamTitle;
			string playlistUrl = state.PlaylistUrl;
			bool isLive = state.IsLive;
			bool isSegmentedVod = state.IsSegmentedVod;
			int playlistIndex = state.PlaylistIndex;
			double position = state.Position;
			bool paused = state.Paused;
			bool poweredOff = state.PoweredOff;
			bool shuffle = state.Shuffle;
			bool barrier = state.Barrier;
			bool resume = state.Resume;
			int generation = state.Generation;
			Component val = Master();
			ChannelPlayback channelPlayback = PlaybackFor(val);
			if ((Object)(object)val == (Object)null || channelPlayback == null)
			{
				return;
			}
			PlayerPosition playerPosition = PositionFor(val);
			ApplyingRemote = true;
			try
			{
				string launchedSource = channelPlayback.LaunchedSource;
				if (!string.Equals(launchedSource, sourceUrl, StringComparison.Ordinal) || channelPlayback.LaunchedPlaylistIndex != playlistIndex)
				{
					channelPlayback.PlaybackGeneration = generation;
				}
				channelPlayback.Barrier = barrier;
				SetField(Live, isLive, val);
				SetField(Segmented, isSegmentedVod, val);
				SetField(StreamTitleField, streamTitle, val);
				SetField(PlaylistUrl, playlistUrl, val);
				SetField(PlaylistIndex, playlistIndex, val);
				SetField(Powered, poweredOff, val);
				SetField(ShuffleField, shuffle, val);
				if (string.IsNullOrEmpty(sourceUrl))
				{
					if (playerPosition != null)
					{
						playerPosition.HasPending = false;
					}
					ClearSourceIdentity();
				}
				else if (playerPosition != null)
				{
					playerPosition.Pending = position;
					playerPosition.HasPending = true;
					playerPosition.Generation = generation;
				}
				bool flag = !string.IsNullOrEmpty(playlistUrl) && string.Equals(launchedSource, sourceUrl, StringComparison.Ordinal) && channelPlayback.LaunchedPlaylistIndex != playlistIndex;
				if (!string.IsNullOrEmpty(sourceUrl) && (!string.Equals(launchedSource, sourceUrl, StringComparison.Ordinal) || flag || channelPlayback.StreamLaunchPending))
				{
					channelPlayback.LaunchedSource = sourceUrl;
					channelPlayback.LaunchedPlaylistIndex = playlistIndex;
					channelPlayback.StreamLaunchPending = true;
					CoopLog.Info("TV client injecting shared stream: " + sourceUrl);
					SetField(PendingUrlField, sourceUrl, val);
					QualityChoice.Invoke(val, new object[1] { false });
					channelPlayback.StreamLaunchPending = false;
				}
				else if (string.IsNullOrEmpty(sourceUrl) && string.IsNullOrEmpty(playlistUrl))
				{
					bool num = !string.IsNullOrEmpty(channelPlayback.LaunchedSource) || channelPlayback.LaunchedPlaylistIndex != 0;
					channelPlayback.LaunchedSource = null;
					channelPlayback.LaunchedPlaylistIndex = 0;
					channelPlayback.StreamLaunchPending = false;
					if (num)
					{
						BroadcastChange?.Invoke(val, new object[1] { Get(SharedVideoIndex, 0) });
					}
				}
				if (string.IsNullOrEmpty(sourceUrl))
				{
					if (playerPosition != null)
					{
						playerPosition.HasPending = false;
					}
				}
				else
				{
					RequestPosition(val, position);
				}
				SetSharedPaused(barrier || paused || poweredOff);
				if (resume && !poweredOff)
				{
					ResumePlayback();
				}
			}
			finally
			{
				ApplyingRemote = false;
			}
		}

		internal static void ApplyPaused(bool paused)
		{
			if (Present && !((Object)(object)Master() == (Object)null))
			{
				SetSharedPaused(paused);
			}
		}

		internal static void ApplyPowered(bool poweredOff)
		{
			if (!Present)
			{
				return;
			}
			Component val = Master();
			if ((Object)(object)val == (Object)null || PoweredOff == poweredOff)
			{
				return;
			}
			if (RemotePower != null)
			{
				bool applyingRemote = ApplyingRemote;
				ApplyingRemote = true;
				try
				{
					RemotePower.Invoke(val, null);
				}
				finally
				{
					ApplyingRemote = applyingRemote;
				}
			}
			SetField(Powered, poweredOff, val);
		}

		internal static void ApplyShuffle(bool shuffle)
		{
			if (!Present)
			{
				return;
			}
			Component val = Master();
			if (!((Object)(object)val == (Object)null) && Shuffle != shuffle)
			{
				if (!ApplyRemoteShuffle())
				{
					SetField(ShuffleField, shuffle, val);
				}
				else if (Shuffle != shuffle)
				{
					SetField(ShuffleField, shuffle, val);
				}
			}
		}

		internal static void ApplySeek(double position)
		{
			if (Present && IsValidPosition(position))
			{
				Component val = Master();
				if (!((Object)(object)val == (Object)null))
				{
					RequestPosition(val, Math.Min(position, 86400.0));
				}
			}
		}

		internal static void ApplyBarrier(bool barrier, bool resume)
		{
			if (Present && !((Object)(object)Master() == (Object)null))
			{
				ChannelPlayback channelPlayback = PlaybackFor(Master());
				if (channelPlayback != null)
				{
					channelPlayback.Barrier = barrier;
				}
				SetSharedPaused(barrier);
				if (resume && !PoweredOff)
				{
					ResumePlayback();
				}
			}
		}

		internal static void ApplyPlaybackError()
		{
			if (Present)
			{
				ChannelPlayback channelPlayback = PlaybackFor(Master());
				if (channelPlayback != null)
				{
					channelPlayback.Barrier = false;
				}
				AbortSharedPlayback();
			}
		}

		internal static PlaybackUndoState CapturePlaybackState()
		{
			ChannelPlayback channelPlayback = PlaybackFor(Master());
			return new PlaybackUndoState(SourceUrl, StreamUrl, StreamTitle, PlaylistUrlValue, IsLive, IsSegmentedVod, PlaylistIndexValue, Position, Paused, PoweredOff, Shuffle, channelPlayback?.Barrier ?? false, channelPlayback?.PlaybackGeneration ?? 0);
		}

		internal static void RestorePlaybackState(PlaybackUndoState state)
		{
			ApplyMediaState(new TvState
			{
				SourceUrl = state.SourceUrl,
				StreamUrl = state.StreamUrl,
				StreamTitle = state.StreamTitle,
				PlaylistUrl = state.PlaylistUrl,
				IsLive = state.IsLive,
				IsSegmentedVod = state.IsSegmentedVod,
				PlaylistIndex = state.PlaylistIndex,
				Position = state.Position,
				Paused = state.Paused,
				PoweredOff = state.PoweredOff,
				Shuffle = state.Shuffle,
				Barrier = state.Barrier,
				Resume = false,
				Generation = state.Generation
			});
		}

		internal static void SetSharedPaused(bool paused)
		{
			if (Paused != paused && TogglePause != null)
			{
				bool applyingRemote = ApplyingRemote;
				ApplyingRemote = true;
				try
				{
					TogglePause.Invoke(Master(), null);
				}
				finally
				{
					ApplyingRemote = applyingRemote;
				}
			}
			if (Paused != paused)
			{
				SetField(PausedField, paused, Master());
			}
		}

		internal static void SetSharedPausedForPrepare(bool paused)
		{
			SetField(PausedField, paused, Master());
		}

		internal static void ResumePlayback()
		{
			SetSharedPaused(paused: false);
		}

		internal static void AbortSharedPlayback()
		{
			Component val = Master();
			try
			{
				SetSharedPaused(paused: false);
				if ((Object)(object)val != (Object)null && !PoweredOff && RemotePower != null)
				{
					bool applyingRemote = ApplyingRemote;
					ApplyingRemote = true;
					try
					{
						RemotePower.Invoke(val, null);
						return;
					}
					finally
					{
						ApplyingRemote = applyingRemote;
					}
				}
			}
			finally
			{
				ClearSourceIdentity();
				ChannelPlayback channelPlayback = PlaybackFor(val);
				if (channelPlayback != null)
				{
					channelPlayback.LaunchedSource = null;
					channelPlayback.LaunchedPlaylistIndex = 0;
					channelPlayback.StreamLaunchPending = false;
				}
				PlayerPosition playerPosition = PositionFor(val);
				if (playerPosition != null)
				{
					playerPosition.HasPending = false;
				}
			}
		}

		internal static bool ApplyRemoteShuffle()
		{
			Component val = Master();
			if ((Object)(object)val == (Object)null || RemoteShuffle == null)
			{
				return false;
			}
			bool applyingRemote = ApplyingRemote;
			ApplyingRemote = true;
			try
			{
				RemoteShuffle.Invoke(val, null);
				return true;
			}
			finally
			{
				ApplyingRemote = applyingRemote;
			}
		}

		internal static bool IsMainPreparedPlayer(object instance, object source)
		{
			if (instance == null || !IsPlayingStream || Master() != instance)
			{
				return false;
			}
			return VideoPlayer((Component)((instance is Component) ? instance : null)) == source;
		}

		internal static void PausePreparedStream(object instance)
		{
			if (instance != null && Master() == instance)
			{
				SetSharedPaused(paused: true);
			}
		}

		internal static bool ApplyPreparedPosition(object instance)
		{
			Component val = (Component)((instance is Component) ? instance : null);
			ChannelPlayback channelPlayback = PlaybackFor(val);
			PlayerPosition playerPosition = PositionFor(val);
			if (playerPosition == null || !playerPosition.HasPending || (Object)(object)val == (Object)null || Master() != val || playerPosition.Generation != (channelPlayback?.PlaybackGeneration ?? 0))
			{
				return false;
			}
			object obj = VideoPlayer(val);
			if (obj == null || !GetProperty(obj, "isPrepared", fallback: false))
			{
				return false;
			}
			ApplyingRemote = true;
			try
			{
				SetPlayerPosition(obj, playerPosition.Pending);
				playerPosition.HasPending = false;
				return true;
			}
			finally
			{
				ApplyingRemote = false;
			}
		}

		internal static bool RequestClientEnrollment()
		{
			if (!Present)
			{
				return false;
			}
			if (EnrolledCount > 0)
			{
				return false;
			}
			Component val = Master();
			if ((Object)(object)val == (Object)null || ChangeVideo == null)
			{
				return false;
			}
			ChangeVideo.Invoke(val, new object[1] { Get(SharedVideoIndex, 0) });
			return true;
		}

		internal static void StreamYouTubePostfix(Component controller, string url)
		{
			RecordPendingSourceUrl(controller, url);
		}

		internal static void ChangeToUrlPostfix(Component controller, string url)
		{
			RecordActiveSourceUrl(controller, url);
		}

		internal static bool AttachVideoErrorHandler(Component controller, Action<Component, string> handler)
		{
			if ((Object)(object)controller == (Object)null || VideoErrorReceived == null)
			{
				return false;
			}
			object obj = VideoPlayer(controller);
			if (obj == null)
			{
				return false;
			}
			if (ErrorBindings.TryGetValue(controller, out var value) && value.Player == obj)
			{
				return true;
			}
			DetachVideoErrorHandler(controller);
			VideoErrorSink firstArgument = new VideoErrorSink
			{
				Controller = controller,
				Handler = handler
			};
			try
			{
				MethodInfo method = typeof(VideoErrorSink).GetMethod("OnError", BindingFlags.Instance | BindingFlags.NonPublic);
				Delegate handler2 = Delegate.CreateDelegate(VideoErrorReceived.EventHandlerType, firstArgument, method);
				VideoErrorReceived.AddEventHandler(obj, handler2);
				ErrorBindings[controller] = new ErrorBinding
				{
					Player = obj,
					Handler = handler2
				};
				return true;
			}
			catch (Exception ex)
			{
				CoopLog.Error("TV VideoPlayer error lifecycle hook failed: " + ex);
				return false;
			}
		}

		private static void DetachVideoErrorHandler(Component controller)
		{
			if (!((Object)(object)controller == (Object)null) && ErrorBindings.TryGetValue(controller, out var value))
			{
				if (VideoErrorReceived != null && value.Player != null)
				{
					VideoErrorReceived.RemoveEventHandler(value.Player, value.Handler);
				}
				ErrorBindings.Remove(controller);
			}
		}

		private static void DetachVideoErrorHandlers()
		{
			if (VideoErrorReceived != null)
			{
				foreach (ErrorBinding value in ErrorBindings.Values)
				{
					if (value.Player != null)
					{
						VideoErrorReceived.RemoveEventHandler(value.Player, value.Handler);
					}
				}
			}
			ErrorBindings.Clear();
		}
	}
	internal readonly struct PlaybackUndoState
	{
		internal readonly string SourceUrl;

		internal readonly string StreamUrl;

		internal readonly string StreamTitle;

		internal readonly string PlaylistUrl;

		internal readonly bool IsLive;

		internal readonly bool IsSegmentedVod;

		internal readonly int PlaylistIndex;

		internal readonly double Position;

		internal readonly bool Paused;

		internal readonly bool PoweredOff;

		internal readonly bool Shuffle;

		internal readonly bool Barrier;

		internal readonly int Generation;

		internal PlaybackUndoState(string sourceUrl, string url, string title, string playlistUrl, bool live, bool segmented, int playlistIndex, double position, bool paused, bool powered, bool shuffle, bool barrier, int generation)
		{
			SourceUrl = sourceUrl;
			StreamUrl = url;
			StreamTitle = title;
			PlaylistUrl = playlistUrl;
			IsLive = live;
			IsSegmentedVod = segmented;
			PlaylistIndex = playlistIndex;
			Position = position;
			Paused = paused;
			PoweredOff = powered;
			Shuffle = shuffle;
			Barrier = barrier;
			Generation = generation;
		}
	}
	public abstract class TvActionMessage : ActionMessage
	{
		public InteractableObject Tv;

		[NonSerialized]
		internal PlaybackUndoState Previous;

		[NonSerialized]
		internal double UndoSeek;

		[NonSerialized]
		internal bool Rejected;

		internal abstract TvOperation Operation { get; }

		internal bool IsMedia
		{
			get
			{
				if (Operation != TvOperation.Open && Operation != TvOperation.Next)
				{
					return Operation == TvOperation.Previous;
				}
				return true;
			}
		}

		internal abstract void Apply();

		public override void OnUndo(ActionResponseMessage response)
		{
			if (Operation == TvOperation.Seek)
			{
				TvInterop.UndoSeek(Tv, UndoSeek);
			}
			else
			{
				TvInterop.UndoOp(Tv, Previous);
			}
		}

		public override void OnMerge(ActionResponseMessage response)
		{
			Previous = default(PlaybackUndoState);
			UndoSeek = double.NaN;
		}
	}
	[NetworkMessage]
	public sealed class TvNextMessage : TvActionMessage
	{
		internal override TvOperation Operation => TvOperation.Next;

		internal override void Apply()
		{
			TvInterop.ApplyOp(Tv, TvOperation.Next, null, null, 0.0);
		}
	}
	[NetworkMessage]
	public sealed class TvPreviousMessage : TvActionMessage
	{
		internal override TvOperation Operation => TvOperation.Previous;

		internal override void Apply()
		{
			TvInterop.ApplyOp(Tv, TvOperation.Previous, null, null, 0.0);
		}
	}
	[NetworkMessage]
	public sealed class TvOpenMessage : TvActionMessage
	{
		public string Url;

		public string Title;

		internal override TvOperation Operation => TvOperation.Open;

		internal override void Apply()
		{
			TvInterop.ApplyOp(Tv, TvOperation.Open, Url, Title, 0.0);
		}
	}
	[NetworkMessage]
	public sealed class TvPauseMessage : TvActionMessage
	{
		internal override TvOperation Operation => TvOperation.Pause;

		internal override void Apply()
		{
			TvInterop.ApplyOp(Tv, TvOperation.Pause, null, null, 0.0);
		}
	}
	[NetworkMessage]
	public sealed class TvPowerMessage : TvActionMessage
	{
		internal override TvOperation Operation => TvOperation.Power;

		internal override void Apply()
		{
			TvInterop.ApplyOp(Tv, TvOperation.Power, null, null, 0.0);
		}
	}
	[NetworkMessage]
	public sealed class TvShuffleMessage : TvActionMessage
	{
		internal override TvOperation Operation => TvOperation.Shuffle;

		internal override void Apply()
		{
			TvInterop.ApplyOp(Tv, TvOperation.Shuffle, null, null, 0.0);
		}
	}
	[NetworkMessage]
	public sealed class TvSeekMessage : TvActionMessage
	{
		public double Delta;

		internal override TvOperation Operation => TvOperation.Seek;

		internal override void Apply()
		{
			TvInterop.ApplyOp(Tv, TvOperation.Seek, null, null, Delta);
		}
	}
	[BepInPlugin("dev.meepen.cardshopcoop.customtv", "CardShopCoopCommunity Custom TV", "2.3.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class TvPlugin : BaseUnityPlugin
	{
		public const string Guid = "dev.meepen.cardshopcoop.customtv";

		public const string Name = "CardShopCoopCommunity Custom TV";

		public const string Version = "2.3.1";
	}
	public enum TvOperation : byte
	{
		None,
		Open,
		Playlist,
		Next,
		Previous,
		Pause,
		Power,
		Shuffle,
		Seek,
		Barrier,
		Error
	}
	[HostOnlyInformation]
	public sealed class TvState : ExtendGameObjectInformation<InteractableObject>, IActionValue
	{
		public string SourceUrl;

		public string StreamUrl;

		public string StreamTitle;

		public string PlaylistUrl;

		public bool IsLive;

		public bool IsSegmentedVod;

		public int PlaylistIndex;

		public double Position;

		public bool Paused;

		public bool PoweredOff;

		public bool Shuffle;

		public bool Barrier;

		public bool Resume;

		public int Generation;

		public TvOperation Operation;

		public Guid ActionId { get; init; }

		public bool Rejected { get; init; }
	}
}
namespace System.Runtime.CompilerServices
{
	internal static class IsExternalInit
	{
	}
}

BepInEx/plugins/CardShopCoop.PurchaseOverhaul.dll

Decompiled 3 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using CardShopCoop.Api;
using CardShopCoop.Attributes;
using CardShopCoop.Net;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("Devin 'Meepen' Korb")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Purchase Overhaul order and licence co-op sync for CardShopCoopCommunity. Optional separate download.")]
[assembly: AssemblyFileVersion("2.3.1.0")]
[assembly: AssemblyInformationalVersion("2.3.1+8f2e09936fa0f37fdbe5e6fa509abb0b78e52e6e")]
[assembly: AssemblyProduct("CardShopCoopCommunity Purchase Overhaul")]
[assembly: AssemblyTitle("CardShopCoop.PurchaseOverhaul")]
[assembly: AssemblyVersion("2.3.1.0")]
namespace CardShopCoop.PurchaseOverhaul;

[ClientBehaviour]
public sealed class PurchaseOverhaulClientBehaviour : CoopBehaviour
{
	private static PurchaseOverhaulClientBehaviour _active;

	internal static PurchaseOverhaulClientBehaviour Active => _active;

	private void OnEnable()
	{
		if ((Object)(object)_active != (Object)null)
		{
			return;
		}
		try
		{
			_active = this;
			ApplyPatches();
		}
		catch
		{
			if (_active == this)
			{
				_active = null;
			}
			throw;
		}
	}

	internal void Shutdown()
	{
		if (_active == this)
		{
			_active = null;
		}
	}

	private void OnDestroy()
	{
		Shutdown();
	}

	private void ApplyPatches()
	{
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Expected O, but got Unknown
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Expected O, but got Unknown
		if (PurchaseOverhaulInterop.Available)
		{
			bool flag = ((CoopBehaviour)this).TryPatch(PurchaseOverhaulInterop.CheckoutSurface, "Place", new HarmonyMethod(typeof(PurchaseOverhaulClientBehaviour), "PlacePrefix", (Type[])null), (HarmonyMethod)null, new Type[1] { typeof(string).MakeByRefType() });
			bool flag2 = ((CoopBehaviour)this).TryPatch(PurchaseOverhaulInterop.CheckoutSurface, "BuyLicense", new HarmonyMethod(typeof(PurchaseOverhaulClientBehaviour), "BuyLicensePrefix", (Type[])null), (HarmonyMethod)null, new Type[2]
			{
				PurchaseOverhaulInterop.ProductSurface,
				typeof(string).MakeByRefType()
			});
			if (flag && flag2)
			{
				CoopLog.Info("Purchase Overhaul co-op bridge installed.");
				return;
			}
			CoopLog.Warn("Purchase Overhaul co-op bridge is incomplete (order=" + flag + ", licence=" + flag2 + "); some purchases may stay local.");
		}
	}

	private static bool PlacePrefix(out string message, ref bool __result)
	{
		PurchaseOverhaulClientBehaviour active = _active;
		if ((Object)(object)active == (Object)null || !PurchaseOverhaulInterop.ShouldRoute)
		{
			message = null;
			return true;
		}
		__result = active.TrySendOrder(out message);
		return false;
	}

	private static bool BuyLicensePrefix(object p, out string message, ref bool __result)
	{
		PurchaseOverhaulClientBehaviour active = _active;
		if ((Object)(object)active == (Object)null || !PurchaseOverhaulInterop.ShouldRoute)
		{
			message = null;
			return true;
		}
		__result = active.TrySendLicense(p, out message);
		return false;
	}

	private bool CanSend(out string message)
	{
		if (((CoopBehaviour)this).Context == null || !((CoopBehaviour)this).Context.InGame)
		{
			message = "Waiting for co-op to finish joining.";
			return false;
		}
		if (((CoopBehaviour)this).Context.Host == null)
		{
			message = "Not connected to the host.";
			return false;
		}
		message = null;
		return true;
	}

	private bool TrySendOrder(out string message)
	{
		if (!CanSend(out message))
		{
			return false;
		}
		if (!PurchaseOverhaulInterop.ReadOrder(out var productIds, out var boxes, out message))
		{
			return false;
		}
		PurchaseOrderRequest purchaseOrderRequest = new PurchaseOrderRequest
		{
			ProductIds = productIds,
			Boxes = boxes
		};
		try
		{
			((CoopBehaviour)this).Context.Send((INetMessage)(object)purchaseOrderRequest);
		}
		catch (Exception ex)
		{
			message = "The order could not be sent: " + ex.Message;
			CoopLog.Warn(message);
			return false;
		}
		message = "Order sent to the host.";
		return true;
	}

	private bool TrySendLicense(object product, out string message)
	{
		if (!CanSend(out message))
		{
			return false;
		}
		if (product == null)
		{
			message = "No item.";
			return false;
		}
		string text = PurchaseOverhaulInterop.ProductIdOf(product);
		if (string.IsNullOrEmpty(text))
		{
			message = PurchaseOverhaulInterop.NameOf(product) + " cannot be licensed in co-op.";
			return false;
		}
		PurchaseLicenseRequest purchaseLicenseRequest = new PurchaseLicenseRequest
		{
			ProductId = text
		};
		try
		{
			((CoopBehaviour)this).Context.Send((INetMessage)(object)purchaseLicenseRequest);
		}
		catch (Exception ex)
		{
			message = "The licence request could not be sent: " + ex.Message;
			CoopLog.Warn(message);
			return false;
		}
		message = "Licence request sent to the host.";
		return true;
	}

	internal void CompleteOrder(ActionResponseMessage response)
	{
		PurchaseOrderResult purchaseOrderResult = response as PurchaseOrderResult;
		if (purchaseOrderResult != null && purchaseOrderResult.Success && !((ActionResponseMessage)purchaseOrderResult).Rejected)
		{
			PurchaseOverhaulInterop.RemoveOrderedLines(purchaseOrderResult.ProductIds, purchaseOrderResult.Boxes);
			PurchaseOverhaulInterop.ShowToast(purchaseOrderResult.Message);
		}
		else
		{
			PurchaseOverhaulInterop.ShowToast(purchaseOrderResult?.Message ?? "The host rejected the order.");
		}
	}

	internal void CompleteLicense(ActionResponseMessage response)
	{
		PurchaseLicenseResult purchaseLicenseResult = response as PurchaseLicenseResult;
		if (purchaseLicenseResult != null && purchaseLicenseResult.Success && !((ActionResponseMessage)purchaseLicenseResult).Rejected)
		{
			PurchaseOverhaulInterop.RefreshCatalogue();
			PurchaseOverhaulInterop.ShowToast(purchaseLicenseResult.Message);
		}
		else
		{
			PurchaseOverhaulInterop.ShowToast(purchaseLicenseResult?.Message ?? "The host rejected the licence.");
		}
	}
}
[ServerBehaviour]
public sealed class PurchaseOverhaulHostBehaviour : CoopBehaviour
{
	[MessageHandler]
	private ActionOutcome HandleOrder(CoopMessageContext context, PurchaseOrderRequest message)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		if (message == null)
		{
			return ActionOutcome.Reject("order is missing", (ActionResponseMessage)null);
		}
		if (!PurchaseOverhaulInterop.Available)
		{
			return ActionOutcome.Reject("Purchase Overhaul is not installed on the host.", (ActionResponseMessage)(object)new PurchaseOrderResult
			{
				Success = false,
				Message = "Purchase Overhaul is not installed on the host."
			});
		}
		if (!PurchaseOverhaulInterop.TryPlaceOrder(message.ProductIds, message.Boxes, out var message2))
		{
			message2 = (string.IsNullOrEmpty(message2) ? "The host refused the order." : message2);
			return ActionOutcome.Reject(message2, (ActionResponseMessage)(object)new PurchaseOrderResult
			{
				Success = false,
				Message = message2
			});
		}
		message2 = (string.IsNullOrEmpty(message2) ? "Order placed." : message2);
		CoopLog.Info("[purchaseoverhaul] host placed order: " + message2);
		return ActionOutcome.Applied((ActionResponseMessage)(object)new PurchaseOrderResult
		{
			Success = true,
			Message = message2,
			ProductIds = message.ProductIds,
			Boxes = message.Boxes
		});
	}

	[MessageHandler]
	private ActionOutcome HandleLicense(CoopMessageContext context, PurchaseLicenseRequest message)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		if (message == null)
		{
			return ActionOutcome.Reject("licence request is missing", (ActionResponseMessage)null);
		}
		if (!PurchaseOverhaulInterop.Available)
		{
			return ActionOutcome.Reject("Purchase Overhaul is not installed on the host.", (ActionResponseMessage)(object)new PurchaseLicenseResult
			{
				Success = false,
				Message = "Purchase Overhaul is not installed on the host."
			});
		}
		if (!PurchaseOverhaulInterop.TryBuyLicense(message.ProductId, out var message2))
		{
			message2 = (string.IsNullOrEmpty(message2) ? "The host refused the licence." : message2);
			return ActionOutcome.Reject(message2, (ActionResponseMessage)(object)new PurchaseLicenseResult
			{
				Success = false,
				Message = message2
			});
		}
		message2 = (string.IsNullOrEmpty(message2) ? "Licence bought." : message2);
		CoopLog.Info("[purchaseoverhaul] host bought licence: " + message2);
		return ActionOutcome.Applied((ActionResponseMessage)(object)new PurchaseLicenseResult
		{
			Success = true,
			Message = message2
		});
	}
}
internal static class PurchaseOverhaulInterop
{
	private const string AssemblyName = "PurchaseOverhaul";

	private const BindingFlags StaticFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

	private static readonly Type CheckoutType = ResolveType("PurchaseOverhaul.Checkout");

	private static readonly Type CartType = ResolveType("PurchaseOverhaul.Cart");

	private static readonly Type CartLineType = CartType?.GetNestedType("Line", BindingFlags.Public);

	private static readonly Type ProductType = ResolveType("PurchaseOverhaul.Product");

	private static readonly Type CatalogueType = ResolveType("PurchaseOverhaul.Catalogue");

	private static readonly Type CoopBridgeType = ResolveType("PurchaseOverhaul.CoopBridge");

	private static readonly Type ToastType = ResolveType("PurchaseOverhaul.Toast");

	private static readonly PropertyInfo CartLines = CartType?.GetProperty("Lines", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

	private static readonly MethodInfo CartSet = ResolveMethod(CartType, "Set", typeof(int), ProductType, typeof(int));

	private static readonly MethodInfo CartBoxes = ResolveMethod(CartType, "Boxes", typeof(int), ProductType);

	private static readonly MethodInfo ValidateMethod = ResolveMethod(CheckoutType, "Validate", typeof(string));

	private static readonly MethodInfo PlaceRemoteMethod = ResolvePlaceRemote();

	private static readonly MethodInfo BuyLicenseMethod = ResolveMethod(CheckoutType, "BuyLicense", typeof(bool), ProductType, typeof(string).MakeByRefType());

	private static readonly PropertyInfo CoopBridgeLive = CoopBridgeType?.GetProperty("Live", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

	private static readonly MethodInfo ProductId = ResolveMethod(CoopBridgeType, "IdOf", typeof(string), ProductType);

	private static readonly MethodInfo FindProduct = ResolveMethod(CoopBridgeType, "Find", ProductType, typeof(string));

	private static readonly MethodInfo ToastShow = ResolveMethod(ToastType, "Show", typeof(void), typeof(string));

	private static readonly MethodInfo CatalogueRefresh = ResolveMethod(CatalogueType, "Refresh", typeof(void));

	private static readonly FieldInfo ProductName = ProductType?.GetField("Name", BindingFlags.Instance | BindingFlags.Public);

	private static bool _probed;

	private static bool _available;

	internal static bool Available
	{
		get
		{
			Probe();
			return _available;
		}
	}

	internal static Type CheckoutSurface => CheckoutType;

	internal static Type ProductSurface => ProductType;

	internal static bool ShouldRoute
	{
		get
		{
			if (!Available)
			{
				return false;
			}
			try
			{
				object obj = CoopBridgeLive?.GetValue(null);
				bool flag = default(bool);
				int num;
				if (obj is bool)
				{
					flag = (bool)obj;
					num = 1;
				}
				else
				{
					num = 0;
				}
				return ((uint)num & (flag ? 1u : 0u)) == 0;
			}
			catch (Exception ex)
			{
				CoopLog.Warn("Purchase Overhaul co-op state could not be read: " + ex.Message);
				return false;
			}
		}
	}

	internal static bool ReadOrder(out List<string> productIds, out List<int> boxes, out string message)
	{
		productIds = new List<string>();
		boxes = new List<int>();
		string text = ValidateMethod?.Invoke(null, null) as string;
		if (!string.IsNullOrEmpty(text))
		{
			message = text;
			return false;
		}
		if (!(CartLines?.GetValue(null) is IEnumerable enumerable))
		{
			message = "Purchase Overhaul's cart is unavailable.";
			return false;
		}
		foreach (object item in enumerable)
		{
			object field = GetField(item, "Product");
			int num = GetInt(item, "Boxes");
			if (field != null && num > 0)
			{
				string text2 = ProductId?.Invoke(null, new object[1] { field }) as string;
				if (string.IsNullOrEmpty(text2))
				{
					message = NameOf(field) + " cannot be ordered in co-op.";
					return false;
				}
				productIds.Add(text2);
				boxes.Add(num);
			}
		}
		if (productIds.Count == 0)
		{
			message = "Nothing in the cart.";
			return false;
		}
		message = null;
		return true;
	}

	internal static bool TryPlaceOrder(List<string> productIds, List<int> boxes, out string message)
	{
		message = null;
		if (productIds == null || boxes == null || productIds.Count != boxes.Count || productIds.Count == 0 || productIds.Count > 64)
		{
			message = "The order is invalid.";
			return false;
		}
		Type cartLineType = CartLineType;
		MethodInfo placeRemoteMethod = PlaceRemoteMethod;
		if (cartLineType == null || placeRemoteMethod == null)
		{
			message = "Purchase Overhaul's host order path is unavailable.";
			return false;
		}
		IList list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(cartLineType));
		for (int i = 0; i < productIds.Count; i++)
		{
			int num = Math.Max(1, Math.Min(5000, boxes[i]));
			object obj = FindProduct?.Invoke(null, new object[1] { productIds[i] });
			if (obj == null)
			{
				message = "An item in the order is unknown to the host.";
				return false;
			}
			object obj2 = Activator.CreateInstance(cartLineType);
			SetField(obj2, "Product", obj);
			SetField(obj2, "Boxes", num);
			list.Add(obj2);
		}
		object[] array = new object[2] { list, null };
		try
		{
			object obj3 = PlaceRemoteMethod.Invoke(null, array);
			bool flag = default(bool);
			int num2;
			if (obj3 is bool)
			{
				flag = (bool)obj3;
				num2 = 1;
			}
			else
			{
				num2 = 0;
			}
			int result = num2 & (flag ? 1 : 0);
			message = array[1] as string;
			return (byte)result != 0;
		}
		catch (Exception ex)
		{
			message = "The host could not complete the order: " + ex.Message;
			return false;
		}
	}

	internal static bool TryBuyLicense(string productId, out string message)
	{
		message = null;
		MethodInfo buyLicenseMethod = BuyLicenseMethod;
		if (buyLicenseMethod == null || string.IsNullOrEmpty(productId))
		{
			message = "Purchase Overhaul's licence path is unavailable.";
			return false;
		}
		object obj = FindProduct?.Invoke(null, new object[1] { productId });
		if (obj == null)
		{
			message = "The licence is unknown to the host.";
			return false;
		}
		object[] array = new object[2] { obj, null };
		try
		{
			object obj2 = buyLicenseMethod.Invoke(null, array);
			bool flag = default(bool);
			int num;
			if (obj2 is bool)
			{
				flag = (bool)obj2;
				num = 1;
			}
			else
			{
				num = 0;
			}
			int result = num & (flag ? 1 : 0);
			message = array[1] as string;
			return (byte)result != 0;
		}
		catch (Exception ex)
		{
			message = "The host could not complete the licence purchase: " + ex.Message;
			return false;
		}
	}

	internal static void RemoveOrderedLines(IReadOnlyList<string> productIds, IReadOnlyList<int> boxes)
	{
		if (productIds == null || boxes == null || CartBoxes == null || CartSet == null)
		{
			return;
		}
		for (int i = 0; i < productIds.Count && i < boxes.Count; i++)
		{
			object obj = FindProduct?.Invoke(null, new object[1] { productIds[i] });
			if (obj != null)
			{
				int num = ((CartBoxes.Invoke(null, new object[1] { obj }) is int num2) ? num2 : 0);
				int num3 = Math.Max(0, num - boxes[i]);
				CartSet.Invoke(null, new object[2] { obj, num3 });
			}
		}
	}

	internal static string NameOf(object product)
	{
		return (ProductName?.GetValue(product) as string) ?? "An item";
	}

	internal static string ProductIdOf(object product)
	{
		return ProductId?.Invoke(null, new object[1] { product }) as string;
	}

	internal static void ShowToast(string text)
	{
		if (string.IsNullOrEmpty(text))
		{
			return;
		}
		try
		{
			ToastShow?.Invoke(null, new object[1] { text });
		}
		catch (Exception ex)
		{
			CoopLog.Warn("Purchase Overhaul toast failed: " + ex.Message);
		}
	}

	internal static void RefreshCatalogue()
	{
		try
		{
			CatalogueRefresh?.Invoke(null, null);
		}
		catch (Exception ex)
		{
			CoopLog.Warn("Purchase Overhaul catalogue refresh failed: " + ex.Message);
		}
	}

	private static void Probe()
	{
		if (_probed)
		{
			return;
		}
		_probed = true;
		if (!(CheckoutType == null))
		{
			_available = CheckoutType != null && CartType != null && CartLineType != null && ProductType != null && ValidateMethod != null && PlaceRemoteMethod != null && BuyLicenseMethod != null && CartLines != null && CartSet != null && CartBoxes != null && ProductId != null && FindProduct != null;
			if (!_available)
			{
				CoopLog.Warn("Purchase Overhaul is installed but its order surface could not be read; its co-op bridge is disabled.");
			}
		}
	}

	private static Type ResolveType(string typeName)
	{
		try
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				if (assembly.GetName().Name == "PurchaseOverhaul")
				{
					return assembly.GetType(typeName, throwOnError: false);
				}
			}
		}
		catch (Exception ex)
		{
			CoopLog.Warn("Purchase Overhaul type probe failed for " + typeName + ": " + ex.Message);
		}
		return null;
	}

	private static MethodInfo ResolveMethod(Type type, string name, Type returnType, params Type[] parameters)
	{
		if (type == null)
		{
			return null;
		}
		MethodInfo method = type.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, parameters, null);
		if (!(method != null) || !(method.ReturnType == returnType))
		{
			return null;
		}
		return method;
	}

	private static MethodInfo ResolvePlaceRemote()
	{
		if (CheckoutType == null || CartLineType == null)
		{
			return null;
		}
		Type type = typeof(List<>).MakeGenericType(CartLineType);
		return ResolveMethod(CheckoutType, "PlaceRemote", typeof(bool), type, typeof(string).MakeByRefType());
	}

	private static object GetField(object instance, string name)
	{
		return instance?.GetType().GetField(name, BindingFlags.Instance | BindingFlags.Public)?.GetValue(instance);
	}

	private static int GetInt(object instance, string name)
	{
		object field = GetField(instance, name);
		if (field is int)
		{
			return (int)field;
		}
		return 0;
	}

	private static void SetField(object instance, string name, object value)
	{
		instance?.GetType().GetField(name, BindingFlags.Instance | BindingFlags.Public)?.SetValue(instance, value);
	}
}
[NetworkMessage]
public sealed class PurchaseOrderRequest : ActionMessage
{
	public List<string> ProductIds = new List<string>();

	public List<int> Boxes = new List<int>();

	public override void OnMerge(ActionResponseMessage response)
	{
		PurchaseOverhaulClientBehaviour.Active?.CompleteOrder(response);
	}
}
[NetworkMessage]
public sealed class PurchaseOrderResult : ActionResponseMessage
{
	public bool Success;

	public string Message = "";

	public List<string> ProductIds = new List<string>();

	public List<int> Boxes = new List<int>();
}
[NetworkMessage]
public sealed class PurchaseLicenseRequest : ActionMessage
{
	public string ProductId = "";

	public override void OnMerge(ActionResponseMessage response)
	{
		PurchaseOverhaulClientBehaviour.Active?.CompleteLicense(response);
	}
}
[NetworkMessage]
public sealed class PurchaseLicenseResult : ActionResponseMessage
{
	public bool Success;

	public string Message = "";
}
[BepInPlugin("dev.meepen.cardshopcoop.purchaseoverhaul", "CardShopCoopCommunity Purchase Overhaul", "2.3.1")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class PurchaseOverhaulPlugin : BaseUnityPlugin
{
	public const string Guid = "dev.meepen.cardshopcoop.purchaseoverhaul";

	public const string Name = "CardShopCoopCommunity Purchase Overhaul";

	public const string Version = "2.3.1";
}