Decompiled source of FlyCommand v1.0.1

Landoria.FlyCommand.dll

Decompiled 18 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Landoria.SharedLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Landoria.FlyCommand")]
[assembly: AssemblyDescription("Allows server-authorized vanilla flight in configured worlds.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Landoria")]
[assembly: AssemblyProduct("Landoria.FlyCommand")]
[assembly: AssemblyCopyright("Copyright © 2026 End3rbyte")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("DDA10461-612F-42CD-A050-B2634758E942")]
[assembly: AssemblyFileVersion("1.0.1")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = "")]
[assembly: AssemblyVersion("1.0.1.40495")]
namespace Landoria.FlyCommand
{
	internal static class FlyAuthorization
	{
		private const string RequestRpc = "Landoria_FlyCommand_Request";

		private const string ResponseRpc = "Landoria_FlyCommand_Response";

		private const float RetrySeconds = 2f;

		private static ZRoutedRpc _registeredRpc;

		private static ZNetPeer _serverPeer;

		private static bool? _serverAllowed;

		private static float _nextRequestAt;

		internal static bool IsAuthorized { get; private set; }

		internal static void Update()
		{
			RegisterRpcs();
			if ((Object)(object)ZNet.instance == (Object)null || ZRoutedRpc.instance == null)
			{
				ResetConnection();
			}
			else if (ZNet.instance.IsServer())
			{
				UpdateServerAuthorization();
			}
			else
			{
				UpdateClientAuthorization();
			}
		}

		internal static void ResetSession()
		{
			_serverAllowed = null;
			ResetConnection();
		}

		private static void RegisterRpcs()
		{
			ZRoutedRpc instance = ZRoutedRpc.instance;
			if (instance != null && instance != _registeredRpc)
			{
				instance.Register("Landoria_FlyCommand_Request", (Action<long>)ReceiveRequest);
				instance.Register<bool>("Landoria_FlyCommand_Response", (Action<long, bool>)ReceiveResponse);
				_registeredRpc = instance;
			}
		}

		private static void UpdateServerAuthorization()
		{
			bool flag = RequiredModifiersAreActive();
			SetAuthorized(flag);
			if (_serverAllowed != flag)
			{
				_serverAllowed = flag;
				ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "Landoria_FlyCommand_Response", new object[1] { flag });
				FlyCommandPlugin.ModLogger.LogInfo($"Server flight authorization changed to {flag}.");
			}
		}

		private static void UpdateClientAuthorization()
		{
			if (!IsAuthorized)
			{
				FlyController.SetEnabled(enabled: false);
			}
			ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
			if (serverPeer != _serverPeer)
			{
				ResetConnection();
				_serverPeer = serverPeer;
			}
			if (_serverPeer != null && !IsAuthorized && Time.unscaledTime >= _nextRequestAt)
			{
				_nextRequestAt = Time.unscaledTime + 2f;
				ZRoutedRpc.instance.InvokeRoutedRPC(_serverPeer.m_uid, "Landoria_FlyCommand_Request", Array.Empty<object>());
			}
		}

		private static void ReceiveRequest(long sender)
		{
			if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && ZNet.instance.GetPeer(sender) != null && ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(sender, "Landoria_FlyCommand_Response", new object[1] { RequiredModifiersAreActive() });
			}
		}

		private static void ReceiveResponse(long sender, bool allowed)
		{
			if (!((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsServer() && _serverPeer != null && _serverPeer.m_uid == sender)
			{
				SetAuthorized(allowed);
			}
		}

		private static bool RequiredModifiersAreActive()
		{
			if (FlyCommandPlugin.ServerEnabled && (Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.GetGlobalKey((GlobalKeys)19))
			{
				return ZoneSystem.instance.GetGlobalKey((GlobalKeys)25);
			}
			return false;
		}

		private static void ResetConnection()
		{
			_serverPeer = null;
			_nextRequestAt = 0f;
			FlyController.SetEnabled(enabled: false);
			SetAuthorized(allowed: false);
		}

		private static void SetAuthorized(bool allowed)
		{
			if (IsAuthorized != allowed)
			{
				IsAuthorized = allowed;
				FlyController.OnAuthorizationChanged(allowed);
				FlyCommandPlugin.ModLogger?.LogInfo($"Flight authorization is now {allowed}.");
			}
		}
	}
	internal static class FlyCommand
	{
		private static ConsoleCommand _command;

		internal static void Register()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_002f: Expected O, but got Unknown
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			_command = new ConsoleCommand("fly", "[on|off] toggles server-authorized vanilla flight.", new ConsoleEventFailable(Run), false, false, false, false, false, new ConsoleOptionsFetcher(Options), false, false, false);
		}

		internal static bool IsCommand(ConsoleCommand command)
		{
			return command == _command;
		}

		private static object Run(ConsoleEventArgs args)
		{
			if (!FlyAuthorization.IsAuthorized)
			{
				return "Flight is not authorized by this server.";
			}
			if (args.Length == 1)
			{
				FlyController.Toggle();
				return true;
			}
			string text = args[1].ToLowerInvariant();
			if (text != "on" && text != "off")
			{
				return "Use fly, fly on, or fly off.";
			}
			FlyController.SetEnabled(text == "on");
			return true;
		}

		private static List<string> Options()
		{
			return new List<string> { "on", "off" };
		}
	}
	internal static class FlyController
	{
		internal static void Toggle()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null && FlyAuthorization.IsAuthorized)
			{
				SetEnabled(!((Character)localPlayer).IsDebugFlying());
			}
		}

		internal static void SetEnabled(bool enabled)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null) && (!enabled || FlyAuthorization.IsAuthorized) && ((Character)localPlayer).IsDebugFlying() != enabled)
			{
				localPlayer.ToggleDebugFly();
			}
		}

		internal static void OnAuthorizationChanged(bool allowed)
		{
			if (!allowed)
			{
				SetEnabled(enabled: false);
			}
		}
	}
	internal static class FlyInput
	{
		internal static bool IsAvailable()
		{
			if (FlyAuthorization.IsAuthorized && (Object)(object)Player.m_localPlayer != (Object)null && !Console.IsVisible() && !TextInput.IsVisible() && !InventoryGui.IsVisible() && !Menu.IsVisible())
			{
				if (!((Object)(object)Chat.instance == (Object)null))
				{
					return !Chat.instance.HasFocus();
				}
				return true;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Terminal), "InitTerminal")]
	internal static class FlyCommandRegistrationPatch
	{
		private static void Postfix()
		{
			FlyCommand.Register();
		}
	}
	[HarmonyPatch(typeof(ConsoleCommand), "IsValid")]
	internal static class FlyCommandValidationPatch
	{
		private static void Postfix(ConsoleCommand __instance, ref bool __result)
		{
			if (FlyCommand.IsCommand(__instance) && !FlyAuthorization.IsAuthorized)
			{
				__result = false;
			}
		}
	}
	[HarmonyPatch(typeof(ZNet), "OnDestroy")]
	internal static class FlyDisconnectPatch
	{
		private static void Prefix()
		{
			FlyAuthorization.ResetSession();
		}
	}
	[BepInPlugin("Landoria.FlyCommand", "Landoria.FlyCommand", "1.0.1")]
	public sealed class FlyCommandPlugin : LandoriaPlugin
	{
		internal const string PluginGuid = "Landoria.FlyCommand";

		internal const string PluginName = "Landoria.FlyCommand";

		internal const string PluginVersion = "1.0.1";

		private const string EnabledArgument = "--flycommand";

		private static readonly KeyboardShortcut ToggleShortcut = new KeyboardShortcut((KeyCode)122, Array.Empty<KeyCode>());

		internal static ModLog ModLogger { get; private set; }

		internal static bool ServerEnabled { get; private set; } = true;

		private void Awake()
		{
			ModLogger = InitializePlugin("Landoria.FlyCommand");
			ServerEnabled = ReadServerEnabled();
			FlyCommand.Register();
			ModLogger.LogInfo(string.Format("{0} {1} is loaded; server enabled={2}.", "Landoria.FlyCommand", "1.0.1", ServerEnabled));
		}

		private static bool ReadServerEnabled()
		{
			string[] commandLineArgs = Environment.GetCommandLineArgs();
			for (int i = 0; i < commandLineArgs.Length; i++)
			{
				if (string.Equals(commandLineArgs[i], "--flycommand", StringComparison.OrdinalIgnoreCase))
				{
					if (i + 1 < commandLineArgs.Length && bool.TryParse(commandLineArgs[i + 1], out var result))
					{
						return result;
					}
					ModLogger.LogWarning("Invalid --flycommand value; using true.");
					return true;
				}
			}
			return true;
		}

		private void Update()
		{
			FlyAuthorization.Update();
			HandleShortcuts();
		}

		private void HandleShortcuts()
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			if (FlyInput.IsAvailable())
			{
				KeyboardShortcut toggleShortcut = ToggleShortcut;
				if (((KeyboardShortcut)(ref toggleShortcut)).IsDown())
				{
					FlyController.Toggle();
				}
			}
		}

		private void OnDestroy()
		{
			FlyAuthorization.ResetSession();
			ModLogger?.LogInfo("Landoria.FlyCommand 1.0.1 is unloaded.");
			ShutdownPlugin();
			ModLogger = null;
		}
	}
}
namespace Landoria.SharedLib
{
	public abstract class LandoriaPlugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		private bool _patchesApplied;

		protected ModLog InitializePlugin(string pluginGuid)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			ModLog modLog = new ModLog(((BaseUnityPlugin)this).Logger);
			Version version = ((object)this).GetType().Assembly.GetName().Version;
			modLog.LogInfo($"AssemblyVersion: {version}.");
			_harmony = new Harmony(pluginGuid);
			PatchOwnNamespace(modLog);
			return modLog;
		}

		protected void PatchOwnNamespace(ModLog log)
		{
			if (_patchesApplied)
			{
				log.LogDebug("Harmony patches are already active; skipping registration.");
				return;
			}
			string text = ((object)this).GetType().Namespace;
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			foreach (Type type in types)
			{
				if (type.Namespace == text)
				{
					_harmony.CreateClassProcessor(type).Patch();
				}
			}
			_patchesApplied = true;
			log.LogDebug("Harmony patches were applied for the plugin namespace.");
		}

		protected void ShutdownPlugin()
		{
			if (_patchesApplied)
			{
				Harmony harmony = _harmony;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
				_patchesApplied = false;
			}
		}
	}
	public sealed class ModLog
	{
		private readonly ManualLogSource _logger;

		public ModLog(ManualLogSource logger)
		{
			_logger = logger;
		}

		public void LogFatal(object message)
		{
			Write((LogLevel)1, message);
		}

		public void LogError(object message)
		{
			Write((LogLevel)2, message);
		}

		public void LogWarning(object message)
		{
			Write((LogLevel)4, message);
		}

		public void LogMessage(object message)
		{
			Write((LogLevel)8, message);
		}

		public void LogInfo(object message)
		{
			Write((LogLevel)16, message);
		}

		public void LogDebug(object message)
		{
			Write((LogLevel)32, message);
		}

		public void Log(LogLevel level, object message)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			Write(level, message);
		}

		private void Write(LogLevel level, object message)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			string arg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
			_logger.Log(level, (object)$"[{arg}] {message}");
		}
	}
}