Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of AfkDetector v1.0.11
Landoria.AfkDetector.dll
Decompiled 2 weeks agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; using Landoria.SharedLib; using Splatform; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Landoria.AfkDetector")] [assembly: AssemblyDescription("Disconnects inactive Valheim players with a clear reason.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Landoria")] [assembly: AssemblyProduct("Landoria.AfkDetector")] [assembly: AssemblyCopyright("Copyright © 2026 End3rbyte")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("7B88B753-913F-4936-88DF-173D3F373E9B")] [assembly: AssemblyFileVersion("1.0.11")] [assembly: AssemblyInformationalVersion("1.0.11")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = "")] [assembly: AssemblyVersion("1.0.11.23337")] namespace Landoria.AfkDetector { internal sealed class ActivityMonitor { private sealed class PlayerActivity { internal Vector3 Position; internal float LastActivityAt; internal bool DisconnectRequested; internal PlayerActivity(Vector3 position, float now) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) Position = position; LastActivityAt = now; } } private readonly Dictionary<long, PlayerActivity> _players = new Dictionary<long, PlayerActivity>(); private readonly Action<ZNetPeer> _disconnect; private float _timeoutSeconds; private float _movementToleranceSquared; internal ActivityMonitor(float timeoutSeconds, float movementTolerance, Action<ZNetPeer> disconnect) { _disconnect = disconnect; Configure(timeoutSeconds, movementTolerance); } internal void Configure(float timeoutSeconds, float movementTolerance) { _timeoutSeconds = timeoutSeconds; _movementToleranceSquared = movementTolerance * movementTolerance; } internal void Update(List<ZNetPeer> peers, float now) { HashSet<long> hashSet = new HashSet<long>(); foreach (ZNetPeer peer in peers) { if (peer.IsReady()) { hashSet.Add(peer.m_uid); UpdatePeer(peer, now); } } RemoveDisconnected(hashSet); } internal void RecordChat(long peerId, float now) { if (_players.TryGetValue(peerId, out var value)) { value.LastActivityAt = now; } } private void UpdatePeer(ZNetPeer peer, float now) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) if (!_players.TryGetValue(peer.m_uid, out var value)) { _players[peer.m_uid] = new PlayerActivity(peer.GetRefPos(), now); } else if (HasMoved(value.Position, peer.GetRefPos())) { value.Position = peer.GetRefPos(); value.LastActivityAt = now; } else if (!value.DisconnectRequested && now - value.LastActivityAt >= _timeoutSeconds) { value.DisconnectRequested = true; _disconnect(peer); } } private bool HasMoved(Vector3 previous, Vector3 current) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) Vector3 val = current - previous; return ((Vector3)(ref val)).sqrMagnitude >= _movementToleranceSquared; } private void RemoveDisconnected(HashSet<long> connected) { List<long> list = new List<long>(); foreach (long key in _players.Keys) { if (!connected.Contains(key)) { list.Add(key); } } foreach (long item in list) { _players.Remove(item); } } } [BepInPlugin("Landoria.AfkDetector", "Landoria.AfkDetector", "1.0.11")] public sealed class AfkDetectorPlugin : LandoriaPlugin { private const string PluginGuid = "Landoria.AfkDetector"; private const string PluginName = "Landoria.AfkDetector"; private const string PluginVersion = "1.0.11"; internal static ModLog Log { get; private set; } private void Awake() { Log = InitializePlugin("Landoria.AfkDetector"); AfkDetectorServer.Start(); Log.LogInfo("Landoria.AfkDetector 1.0.11 is loaded."); } private void Update() { AfkDetectorServer.Tick(); } private void OnDestroy() { Log?.LogInfo("Landoria.AfkDetector 1.0.11 is unloaded."); AfkDetectorServer.Stop(); ShutdownPlugin(); Log = null; } } internal static class AfkDetectorServer { private const int DefaultTimeoutMinutes = 30; private const string TimeoutArgument = "--afktimeout"; private const float MovementTolerance = 0.75f; private const float ScanIntervalSeconds = 2f; private static int? _timeoutMinutes; private static ActivityMonitor _monitor; private static float _nextScan; internal static bool IsReady => ServerRole.IsDedicatedServer; internal static void Start() { Stop(); } internal static void Tick() { if (IsReady) { InitializeTimeout(); if (_timeoutMinutes != -1 && !(Time.unscaledTime < _nextScan)) { _nextScan = Time.unscaledTime + 2f; EnsureMonitor().Update(ZNet.instance.GetPeers(), Time.unscaledTime); } } } internal static void RecordChat(long peerId) { if (IsReady) { InitializeTimeout(); if (_timeoutMinutes != -1) { EnsureMonitor().RecordChat(peerId, Time.unscaledTime); } } } internal static void Stop() { _timeoutMinutes = null; _monitor = null; _nextScan = 0f; } private static ActivityMonitor EnsureMonitor() { float timeoutSeconds = (float)_timeoutMinutes.Value * 60f; if (_monitor == null) { _monitor = new ActivityMonitor(timeoutSeconds, 0.75f, DisconnectPlayer); } else { _monitor.Configure(timeoutSeconds, 0.75f); } return _monitor; } private static void InitializeTimeout() { if (!_timeoutMinutes.HasValue) { _timeoutMinutes = ReadTimeout(); AfkDetectorPlugin.Log.LogInfo((_timeoutMinutes == -1) ? "AFK timeout is disabled." : $"AFK timeout is {_timeoutMinutes} minutes."); } } private static int ReadTimeout() { string[] commandLineArgs = Environment.GetCommandLineArgs(); for (int i = 0; i < commandLineArgs.Length; i++) { if (string.Equals(commandLineArgs[i], "--afktimeout", StringComparison.OrdinalIgnoreCase)) { return ParseTimeout(commandLineArgs, i); } } return 30; } private static int ParseTimeout(string[] arguments, int index) { if (index + 1 < arguments.Length && int.TryParse(arguments[index + 1], out var result) && (result == -1 || result >= 1)) { AfkDetectorPlugin.Log.LogInfo(string.Format("Received command-line switch: {0} {1}.", "--afktimeout", result)); return result; } AfkDetectorPlugin.Log.LogWarning(string.Format("Invalid {0} value; using {1} minutes.", "--afktimeout", 30)); return 30; } private static void DisconnectPlayer(ZNetPeer peer) { peer.m_rpc.Invoke("Landoria_AfkDisconnectReason", new object[1] { "Disconnected due to inactivity." }); ZNet.instance.Kick(peer.m_socket.GetHostName()); AfkDetectorPlugin.Log.LogInfo("Requested inactivity disconnect for " + peer.m_playerName + "."); } } [HarmonyPatch(typeof(ZRoutedRpc), "RPC_RoutedRPC")] internal static class ChatActivityPatch { private static readonly int ChatMessageHash = StringExtensionMethods.GetStableHashCode("ChatMessage"); private static readonly int SayHash = StringExtensionMethods.GetStableHashCode("Say"); private static void Prefix(ZPackage pkg) { if (!AfkDetectorServer.IsReady) { return; } try { RoutedRPCData val = ReadRoutedData(pkg); if (ContainsChatMessage(val)) { AfkDetectorServer.RecordChat(val.m_senderPeerID); } } catch (Exception arg) { AfkDetectorPlugin.Log.LogDebug($"Ignored unreadable chat activity: {arg}"); } } private static RoutedRPCData ReadRoutedData(ZPackage source) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown ZPackage val = new ZPackage(source.GetArray()); RoutedRPCData val2 = new RoutedRPCData(); val2.Deserialize(val); return val2; } private static bool ContainsChatMessage(RoutedRPCData data) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown ZPackage package = new ZPackage(data.m_parameters.GetArray()); if (data.m_methodHash == ChatMessageHash) { return ReadChatMessage(package, hasPosition: true); } if (data.m_methodHash == SayHash) { return ReadChatMessage(package, hasPosition: false); } return false; } private static bool ReadChatMessage(ZPackage package, bool hasPosition) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) if (hasPosition) { package.ReadVector3(); } package.ReadInt(); package.ReadString(); package.ReadString(); return !string.IsNullOrWhiteSpace(package.ReadString()); } } internal static class ClientDisconnectReason { internal const string RpcName = "Landoria_AfkDisconnectReason"; internal static void Receive(ZRpc rpc, string message) { ConnectionFailureMessages.Push("Landoria.AfkDetector", message); } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] internal static class ClientConnectionPatch { private static void Postfix(ZNet __instance, ZNetPeer peer) { if (!__instance.IsServer()) { peer.m_rpc.Register<string>("Landoria_AfkDisconnectReason", (Action<ZRpc, string>)ClientDisconnectReason.Receive); } } } } namespace Landoria.SharedLib { public abstract class LandoriaPlugin : BaseUnityPlugin { private Harmony _harmony; private bool _patchesApplied; protected ModLog InitializePlugin(string pluginGuid) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown ModLog modLog = new ModLog(((BaseUnityPlugin)this).Logger); Version version = ((object)this).GetType().Assembly.GetName().Version; modLog.LogInfo($"AssemblyVersion: {version}."); EnsureSharedPatches(modLog); _harmony = new Harmony(pluginGuid); PatchOwnNamespace(modLog); return modLog; } protected ModLog InitializePlugin(string pluginGuid, Type[] patchTypes) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown ModLog modLog = new ModLog(((BaseUnityPlugin)this).Logger); Version version = ((object)this).GetType().Assembly.GetName().Version; modLog.LogInfo($"AssemblyVersion: {version}."); EnsureSharedPatches(modLog); _harmony = new Harmony(pluginGuid); foreach (Type type in patchTypes) { _harmony.CreateClassProcessor(type).Patch(); modLog.LogInfo("Server patch: " + type.Name); } _patchesApplied = true; return modLog; } private static void EnsureSharedPatches(ModLog log) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) lock (AppDomain.CurrentDomain) { if (AppDomain.CurrentDomain.GetData("Landoria.SharedLib.ConnectionFailureMenuPatch.v1") == null) { new Harmony("Landoria.SharedLib").CreateClassProcessor(typeof(ConnectionFailureMenuPatch)).Patch(); AppDomain.CurrentDomain.SetData("Landoria.SharedLib.ConnectionFailureMenuPatch.v1", true); log.LogDebug("Shared connection failure menu patch was applied."); } } } 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 static class ConnectionFailureMessages { private const string StateKey = "Landoria.SharedLib.ConnectionFailureMessages.v1"; private static readonly ManualLogSource Log = Logger.CreateLogSource("Landoria.ConnectionFailureMessages"); public static void Push(string source, string message) { Push(source, message, (string)null); } public static void Push(string source, string userMessage, string systemMessage) { Push(source, userMessage, systemMessage, null); } public static void Push(string source, string userMessage, Exception exception) { Push(source, userMessage, exception?.Message, exception); } public static void Push(string source, string userMessage, string systemMessage, Exception exception) { string text = DisplayMessage(userMessage, systemMessage ?? exception?.Message); if (string.IsNullOrWhiteSpace(source) || text == null) { return; } bool flag = false; lock (AppDomain.CurrentDomain) { Stack<Tuple<string, string, string>> messages = GetMessages(); Tuple<string, string, string> item = Tuple.Create(source, text, systemMessage); if (!messages.Contains(item)) { messages.Push(item); flag = true; } } if (flag) { LogQueued(source, text, systemMessage, exception); } } public static void Clear(string source) { if (string.IsNullOrWhiteSpace(source)) { return; } lock (AppDomain.CurrentDomain) { Stack<Tuple<string, string, string>> messages = GetMessages(); Stack<Tuple<string, string, string>> stack = new Stack<Tuple<string, string, string>>(); while (messages.Count > 0) { Tuple<string, string, string> tuple = messages.Pop(); if (tuple.Item1 != source) { stack.Push(tuple); } } while (stack.Count > 0) { messages.Push(stack.Pop()); } } } internal static bool TryPopAll(out string message) { lock (AppDomain.CurrentDomain) { Stack<Tuple<string, string, string>> messages = GetMessages(); if (messages.Count > 0) { List<string> list = new List<string>(); while (messages.Count > 0) { list.Add(messages.Pop().Item2); } message = string.Join("\n", list); return true; } } message = null; return false; } private static Stack<Tuple<string, string, string>> GetMessages() { if (AppDomain.CurrentDomain.GetData("Landoria.SharedLib.ConnectionFailureMessages.v1") is Stack<Tuple<string, string, string>> result) { return result; } Stack<Tuple<string, string, string>> stack = new Stack<Tuple<string, string, string>>(); AppDomain.CurrentDomain.SetData("Landoria.SharedLib.ConnectionFailureMessages.v1", stack); return stack; } private static string DisplayMessage(string userMessage, string systemMessage) { if (!string.IsNullOrWhiteSpace(userMessage)) { return userMessage; } if (!string.IsNullOrWhiteSpace(systemMessage)) { return systemMessage; } return null; } private static void LogQueued(string source, string userMessage, string systemMessage, Exception exception) { string text = exception?.ToString() ?? Environment.StackTrace; if (string.IsNullOrWhiteSpace(systemMessage) || systemMessage == userMessage) { Log.LogWarning((object)("Queued connection failure message from " + source + ": " + userMessage + "\nDiagnostic stack:\n" + text)); } else { Log.LogWarning((object)("Queued connection failure message from " + source + ": userMessage=" + userMessage + "; systemMessage=" + systemMessage + "\nDiagnostic stack:\n" + text)); } } } [HarmonyPatch] internal static class ConnectionFailureMenuPatch { [HarmonyPostfix] [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] private static void ShowConnectError(TMP_Text ___m_connectionFailedError) { if (ConnectionFailureMessages.TryPopAll(out var message)) { ___m_connectionFailedError.text = message; } } [HarmonyPostfix] [HarmonyPatch(typeof(FejdStartup), "Start")] private static void Start(GameObject ___m_connectionFailedPanel, TMP_Text ___m_connectionFailedError) { ShowNext(___m_connectionFailedPanel, ___m_connectionFailedError); } [HarmonyPostfix] [HarmonyPatch(typeof(FejdStartup), "OnConnectionFailedOk")] private static void OnConnectionFailedOk(GameObject ___m_connectionFailedPanel, TMP_Text ___m_connectionFailedError) { ShowNext(___m_connectionFailedPanel, ___m_connectionFailedError); } private static void ShowNext(GameObject panel, TMP_Text text) { if (ConnectionFailureMessages.TryPopAll(out var message)) { text.text = message; panel.SetActive(true); } } } 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}"); } } public static class PlatformPlayerIdentity { public unsafe static string Resolve(PlayerInfo player) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) string text = ((object)(*(PlatformUserID*)(&player.m_userInfo.m_id))/*cast due to .constrained prefix*/).ToString(); if (!string.IsNullOrWhiteSpace(text)) { return text; } ZNetPeer obj = FindPeer(player); if (obj == null) { return null; } ISocket socket = obj.m_socket; if (socket == null) { return null; } return socket.GetHostName(); } public static ZNetPeer FindPeer(PlayerInfo player) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || ((ZDOID)(ref player.m_characterID)).IsNone()) { return null; } return ((IEnumerable<ZNetPeer>)ZNet.instance.GetPeers()).FirstOrDefault((Func<ZNetPeer, bool>)((ZNetPeer peer) => peer != null && ((ZDOID)(ref peer.m_characterID)).Equals(player.m_characterID))); } } public static class ServerRole { public static bool IsDedicatedServer { get { if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer()) { return ZNet.instance.IsDedicated(); } return false; } } } }