Please disclose if your mod was created primarily 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 Polyhydra Games Valheim Restful Service v1.0.8
PolyhydraGames.Valheim.RestServer.dll
Decompiled 5 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using BepInEx; using HarmonyLib; using Jotunn; using Jotunn.Managers; using Jotunn.Utils; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using PolyhydraGames.Valheim.Core; using PolyhydraGames.Valheim.Core.Fascade; using PolyhydraGames.Valheim.Core.Models; using PolyhydraGames.Valheim.Core.Requests; using PolyhydraGames.Valheim.Core.Transport; using PolyhydraGames.Valheim.RestServer.Commands.Abstract; using PolyhydraGames.Valheim.RestServer.Converters; using PolyhydraGames.Valheim.RestServer.Extensions; using PolyhydraGames.Valheim.RestServer.Models; using PolyhydraGames.Valheim.RestServer.WebServer; using Splatform; using UnityEngine; using UnityEngine.Networking; using UnityEngine.Profiling; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("PolyhydraGames.RestServer.UnitTests")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("PolyhydraGames.Valheim.RestServer")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+1ca51c0ede977c7fe861d590f3c8ff37211621cb")] [assembly: AssemblyProduct("PolyhydraGames.Valheim.RestServer")] [assembly: AssemblyTitle("PolyhydraGames.Valheim.RestServer")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace PolyhydraGames.Valheim.RestServer { public class AudioHelper : MonoBehaviour { [CompilerGenerated] private sealed class <PlayAudioFromUrl>d__0 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public string url; public Vector3 position; private UnityWebRequest <www>5__2; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <PlayAudioFromUrl>d__0(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <www>5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Invalid comparison between Unknown and I4 //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: 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_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Expected O, but got Unknown try { switch (<>1__state) { default: return false; case 0: { <>1__state = -1; AudioType val2 = (AudioType)(url.Contains(".mp3") ? 13 : 20); <www>5__2 = UnityWebRequestMultimedia.GetAudioClip(url, val2); <>1__state = -3; <>2__current = <www>5__2.SendWebRequest(); <>1__state = 1; return true; } case 1: <>1__state = -3; if ((int)<www>5__2.result != 1) { Debug.LogWarning((object)("Failed to download audio: " + <www>5__2.error)); } else { AudioClip content = DownloadHandlerAudioClip.GetContent(<www>5__2); GameObject val = new GameObject("TempAudio"); val.transform.position = position; AudioSource obj = val.AddComponent<AudioSource>(); obj.clip = content; obj.spatialBlend = 1f; obj.Play(); Object.Destroy((Object)val, content.length); } <>m__Finally1(); <www>5__2 = null; return false; } } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<www>5__2 != null) { ((IDisposable)<www>5__2).Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [IteratorStateMachine(typeof(<PlayAudioFromUrl>d__0))] public IEnumerator PlayAudioFromUrl(string url, Vector3 position) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <PlayAudioFromUrl>d__0(0) { url = url, position = position }; } } public class CoroutineRunner : MonoBehaviour { private static CoroutineRunner _instance; public static CoroutineRunner Instance { get { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown if ((Object)(object)_instance == (Object)null) { GameObject val = new GameObject("CoroutineRunner"); Object.DontDestroyOnLoad((Object)val); _instance = val.AddComponent<CoroutineRunner>(); } return _instance; } } public void Run(IEnumerator routine) { ((MonoBehaviour)this).StartCoroutine(routine); } } public class IsExternalInit { } public class JotunnLogger : IPolyLogger { public void LogInfo(string message) { Logger.LogInfo((object)("[PolyValheimRest]" + message)); } public void LogWarning(string message) { Logger.LogWarning((object)("[PolyValheimRest]" + message)); } public void LogError(string exMessage) { Logger.LogWarning((object)("[PolyValheimRest]" + exMessage)); } } public record PlayerWrapperType(ZNetPeer Peer) { public ZRpc RPC => Peer.m_rpc; public long ZDOID => Peer.m_uid; public string Name => Peer.m_playerName; public ZDOID PlayerId => Peer.m_characterID; public Vector3 RefPosition => Peer.GetRefPos(); public string SocketEndpoint { get { ISocket socket = Peer.m_socket; if (socket == null) { return null; } return socket.GetEndPointString(); } } public ZDO? GetZDO => ZDOMan.instance.GetZDO(Peer.m_characterID); public ZDOID? ZdoUid => GetZDO?.m_uid; public Vector3? WorldPosition { get { //IL_0014: Unknown result type (might be due to invalid IL or missing references) ZDO? getZDO = GetZDO; if (getZDO == null) { return null; } return getZDO.GetPosition(); } } public Quaternion? Rotation { get { //IL_0014: Unknown result type (might be due to invalid IL or missing references) ZDO? getZDO = GetZDO; if (getZDO == null) { return null; } return getZDO.GetRotation(); } } public long? UnderlyingUid { get { ZDO? getZDO = GetZDO; if (getZDO == null) { return null; } return getZDO.GetLong(ZDOVars.s_playerID, 0L); } } public long? Owner { get { ZDO? getZDO = GetZDO; if (getZDO == null) { return null; } return getZDO.GetOwner(); } } public void PeerInvoke(string method, params object[] args) { RPC.Invoke(method, args); } public override string ToString() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) return $"{Name} [{ZDOID}] at {RefPosition}"; } [CompilerGenerated] protected virtual bool PrintMembers(StringBuilder builder) { //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) RuntimeHelpers.EnsureSufficientExecutionStack(); builder.Append("Peer = "); builder.Append(Peer); builder.Append(", RPC = "); builder.Append(RPC); builder.Append(", ZDOID = "); builder.Append(ZDOID.ToString()); builder.Append(", Name = "); builder.Append((object?)Name); builder.Append(", PlayerId = "); ZDOID playerId = PlayerId; builder.Append(((object)(ZDOID)(ref playerId)).ToString()); builder.Append(", RefPosition = "); Vector3 refPosition = RefPosition; builder.Append(((object)(Vector3)(ref refPosition)).ToString()); builder.Append(", SocketEndpoint = "); builder.Append((object?)SocketEndpoint); builder.Append(", GetZDO = "); builder.Append(GetZDO); builder.Append(", ZdoUid = "); builder.Append(ZdoUid.ToString()); builder.Append(", WorldPosition = "); builder.Append(WorldPosition.ToString()); builder.Append(", Rotation = "); builder.Append(Rotation.ToString()); builder.Append(", UnderlyingUid = "); builder.Append(UnderlyingUid.ToString()); builder.Append(", Owner = "); builder.Append(Owner.ToString()); return true; } } [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("com.polyhydragames.rest", "Polyhydra Games Rest Server", "1.0.1")] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { private readonly Harmony _harmony = new Harmony("com.polyhydragames.rest"); public const string Guid = "com.polyhydragames.rest"; public const string Name = "Polyhydra Games Rest Server"; public const string Version = "1.0.1"; public const string LogHeader = "[PolyValheimRest]"; private void Awake() { Logger.SetLogger((IPolyLogger)(object)new JotunnLogger()); _harmony.PatchAll(); RegisterHttpCalls(); try { RegistrationHelpers.RegisterAllCommands(Assembly.GetAssembly(typeof(Plugin))); Audit(); } catch (Exception ex) { Logger.LogWarning((object)("[PolyValheimRcon] Loading failed, hopefully this isn't the server!\n" + ex.Message)); } } private void Audit() { try { DatabaseHelpers.ListPrefabs(); DatabaseHelpers.GetEnvironmentNames(); DatabaseHelpers.GetStatusEffects(); } catch (Exception ex) { Logger.LogWarning((object)ex.Message); } } private void RegisterHttpCalls() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown GameObject val = new GameObject("HttpCommandServer"); Object.DontDestroyOnLoad((Object)val); val.AddComponent<HttpCommandServer>(); } } } namespace PolyhydraGames.Valheim.RestServer.WebServer { public class ActionManager { private static ActionManager _instance; public Dictionary<string, IRestAction> Actions { get; } = new Dictionary<string, IRestAction>(); public static ActionManager Instance => _instance ?? (_instance = new ActionManager()); public string Audit() { string text = string.Join(" ", Actions.Keys); Logger.LogInfo("Actions:" + text); return text; } public PostResponse ProcessCommand(CommandRequestType request) { IRestAction action = GetAction(request.Command); if (action == null) { return Response.Fail("Command " + request.Command + " was not found. Legal options are: " + string.Join(" ", Actions.Keys)); } return action.OnHandle(request); } public IRestAction? GetAction(string commandName) { if (!Actions.ContainsKey(commandName)) { return null; } return Actions[commandName]; } public bool AddAction(IRestAction action) { if (Actions.ContainsKey(action.Method)) { return false; } Actions[action.Method] = action; return true; } private ActionManager() { } public void RegisterCommand(Type type) { try { IRestAction action = Activator.CreateInstance(type) as IRestAction; AddAction(action); Logger.LogWarning("RegisteredCommand: " + type.Name); } catch (Exception ex) { Logger.LogWarning("RegisterCommand failed!" + ex.Message + type.Name); } } } public static class ActionProcessor { } public class HttpCommandServer : MonoBehaviour { private HttpListener _listener; private Thread _listenerThread; private void Start() { _listener = new HttpListener(); _listener.Prefixes.Add("http://*:8080/"); _listener.Start(); _listenerThread = new Thread(ListenLoop); _listenerThread.Start(); Logger.LogInfo("[MyMod] HTTP command server started on port 8080"); } private void OnDestroy() { _listener.Stop(); _listener.Close(); _listenerThread.Abort(); } private void ListenLoop() { while (_listener.IsListening) { try { HttpListenerContext context = _listener.GetContext(); string s = HandleRequest(context.Request); byte[] bytes = Encoding.UTF8.GetBytes(s); context.Response.ContentType = "application/json"; context.Response.OutputStream.Write(bytes, 0, bytes.Length); context.Response.Close(); } catch (Exception ex) { Debug.LogError((object)("[MyMod] HTTP listener error: " + ex)); } } } private string HandleRequest(HttpListenerRequest request) { if (request.HttpMethod != "POST") { return "{\"status\":\"unknown command\"}"; } using StreamReader streamReader = new StreamReader(request.InputStream, request.ContentEncoding); string command = request.GetCommand(); string text = streamReader.ReadToEnd(); CommandRequestType request2 = CommandRequest.Create(command, text); return ActionManager.Instance.ProcessCommand(request2).ToJson(); } } public static class Response { public static PostResponse Fail(this CommandRequestType request, string errorMessage) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown return new PostResponse { Success = false, Message = errorMessage, Command = request.Command }; } public static PostResponse Fail(this Exception ex, string errorMessage) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown return new PostResponse { Success = false, Message = ex.Message + " / " + errorMessage }; } public static PostResponse Fail(string errorMessage, string command = "") { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown return new PostResponse { Success = false, Message = errorMessage, Command = command }; } public static PostResponse Pass(string message, string command) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown return new PostResponse { Success = true, Message = message, Command = command }; } public static PostResponse Pass(this CommandRequestType command, string message) { return Pass(message, command.Command); } public static PostResponse Pass<T>(this T data, string command) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown return new PostResponse { Success = true, Command = command, Data = JsonHelpers.ToJson<T>(data), DataType = typeof(T).Name }; } } public static class ResponseHelpers { private static JsonSerializer? _serializer; private static JsonSerializer GetSerializer => _serializer ?? JsonSerializer.Create(); public static string GetCommand(this string value) { return value.Split(new char[1] { '/' }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault() ?? string.Empty; } public static string GetCommand(this HttpListenerRequest request) { return request.Url.AbsolutePath.GetCommand(); } public static string ToJson(this PostResponse response) { return JsonConvert.SerializeObject((object)response); } } } namespace PolyhydraGames.Valheim.RestServer.Models { public interface IRestAction<T> : IRestAction { string OnHandle(T request); } public readonly struct ObjectId { public readonly uint Id; public readonly long UserId; public ObjectId(uint id, long userId) { Id = id; UserId = userId; } } public interface IRestAction { string Method { get; } string Description { get; } PostResponse OnHandle(CommandRequestType request); } public abstract class RestRequest : IRestAction { public abstract string Method { get; } public abstract string Description { get; } public abstract PostResponse OnHandle(CommandRequestType request); } internal static class ServerConsole { public static string Execute(string command) { try { if ((Object)(object)Console.instance != (Object)null) { ((Terminal)Console.instance).TryRunCommand(command, false, false); return "ok: " + command; } return "dispatched: " + command; } catch (Exception ex) { Debug.LogError((object)$"[Rest] console error running '{command}': {ex}"); return "error: " + ex.Message; } } } } namespace PolyhydraGames.Valheim.RestServer.Extensions { public static class DatabaseHelpers { public static StatusEffect? GetEffect(string statusName) { string statusName2 = statusName; int stableHashCode = statusName2.GetStableHashCode(); StatusEffect val = ObjectDB.instance.GetStatusEffect(stableHashCode); if ((Object)(object)val == (Object)null) { val = ((IEnumerable<StatusEffect>)ObjectDB.instance.m_StatusEffects).FirstOrDefault((Func<StatusEffect, bool>)((StatusEffect se) => ((Object)se).name.Equals(statusName2, StringComparison.OrdinalIgnoreCase))); if ((Object)(object)val == (Object)null) { Logger.LogWarning((object)("No effect found for " + statusName2 + "Effects: " + string.Join(", ", ObjectDB.instance.m_StatusEffects.Select((StatusEffect x) => ((Object)x).name)))); } } return val; } public static List<string> GetItems() { return (from x in ObjectDB.instance.m_items orderby x select ((Object)x).name).ToList(); } public static List<string> GetStatusEffects() { return (from x in ObjectDB.instance.m_StatusEffects orderby x select ((Object)x).name).ToList(); } public static List<string> GetPrefabNames() { return ZNetScene.instance.GetPrefabNames(); } public static List<string> GetAllPlayerNames() { return (from x in Player.GetAllPlayers() select x.GetPlayerName()).ToList(); } public static string FormatStatusEffects() { LoggingHelpers.PrintItems(GetStatusEffects(), "StatusEffects"); return ""; } public static void ListPrefabs() { if ((Object)(object)ZNetScene.instance == (Object)null) { ZLog.Log((object)"ZNetScene not ready yet."); } else { LoggingHelpers.PrintItems(GetPrefabNames(), "Prefab"); } } public static List<string> GetEnvironmentNames() { List<string> result = null; if ((Object)(object)EnvMan.instance == (Object)null) { ZLog.Log((object)"ZNetScene not ready yet."); return result; } List<string> list = EnvMan.instance.m_environments.Select((EnvSetup e) => e.m_name).ToList(); LoggingHelpers.PrintItems(list, "Environment"); return list; } } public static class LoggingHelpers { public static void PrintItems(IList<string> items, string name) { string.Join(", ", items.Select((string x) => "\"" + x + "\"")); ZLog.Log((object)$"name ({items.Count}): result"); ZLog.Log((object)("Total " + name + "s: ")); } } public static class MoreExtensions { public static Vector3? GetVector3(this string[] items) { if (items.Length < 3) { return null; } try { return items.Select(float.Parse).GetVector3(); } catch (Exception) { return null; } } public static Vector3? GetVector3(this IEnumerable<float> items) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) float[] array = items.ToArray(); if (array.Length < 3) { return null; } try { return new Vector3(array[0], array[1], array[2]); } catch (Exception) { return null; } } } public static class PlayerWrapper { public static Vector3Dto ToFacade(this Vector3 vector3) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown return new Vector3Dto(vector3.x, vector3.y, vector3.z, (int?)null, (int?)null); } public static Quaterion ToFacade(this Quaternion vector3) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown return new Quaterion(vector3.x, vector3.y, vector3.z, vector3.w); } public static Vector2iDto ToFacade(this Vector2i vector3) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown return new Vector2iDto(vector3.x, vector3.y); } public static Vector3 GetPosition(this Player player) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return ((Component)player).transform.position; } public static bool InvokeRoutedRpcOnWorld(this PlayerWrapperType player, RpcCommand rpc, params object[] args) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (!player.Owner.HasValue) { return false; } ZRoutedRpc.instance.InvokeRoutedRPC(player.Owner.Value, rpc.GetRpcCommandName(), args); return true; } public static bool InvokeRoutedRpc(this PlayerWrapperType player, ZDOID target, RpcCommand rpc, params object[] args) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) if (!player.Owner.HasValue) { return false; } ZRoutedRpc.instance.InvokeRoutedRPC(player.Owner.Value, target, rpc.GetRpcCommandName(), args); return true; } public static void InvokeRoutedRpcOnSelf(this PlayerWrapperType player, RpcCommand rpc, params object[] args) { //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) player.InvokeRoutedRpc(player.PlayerId, rpc, args); } public static ZDO GetZDO(this PlayerWrapperType player) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return ZDOMan.instance.GetZDO(player.PlayerId); } public static string GetSteamId(this PlayerWrapperType player) { return player.RPC.GetSocket().GetHostName(); } public static PlayerWrapperType Create(ZNetPeer peer) { return new PlayerWrapperType(peer); } } public static class PrefabUtils { public static GameObject? FindPrefab(string name) { if (string.IsNullOrWhiteSpace(name)) { return null; } return ZNetScene.instance.GetPrefab(name); } } public static class RegistrationHelpers { public static void RegisterAllCommands(Assembly assembly) { if (ActionManager.Instance == null) { Logger.LogError("RconProxy not initialized"); return; } Logger.LogInfo("Registering rcon commands..."); Type commandInterfaceType = typeof(IRestAction); IEnumerable<Type> enumerable = from t in assembly.GetTypes() where t != null where !t.IsAbstract && t.IsClass where t.GetInterfaces().Contains(commandInterfaceType) select t; Logger.LogInfo(""); foreach (Type item in enumerable) { Logger.LogInfo("[PolyRest] REGISTERING type"); ActionManager.Instance.RegisterCommand(item); Logger.LogInfo("[PolyRest] DONE REGISTERING type"); } ActionManager.Instance.Audit(); throw new Exception(); } } public static class StringUtils { public static GlobalKeys? GetGlobalKey(this CommandRequestType request, int index) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) if (Enum.TryParse<GlobalKeys>(CommandRequest.Messages(request)[index], out GlobalKeys result)) { return result; } return null; } public static bool IsDedicatedServer() { bool result = Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsDedicated(); Logger.LogInfo((object)("[IsDedicated] " + result)); return result; } public static string GetRpcCommandName(this RpcCommand command) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) if (!RpcCommandMap.Names.TryGetValue(command, out var value)) { return "RPC_Unknown"; } return value; } public static int GetStableHashCode(this string str) { int num = 5381; foreach (char c in str) { num = (num * 33) ^ c; } return num; } } public static class UIHelpers { public static void ShowPopup(MessageType msgType, string message) { MessageHud.instance.ShowMessage((MessageType)1, message, 0, (Sprite)null, false); } } public static class ZNetPeerExtensions { public static ZDO? GetZDO(this ZNetPeer peer) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return ZDOMan.instance.GetZDO(peer.m_characterID); } public static string GetSteamId(this ZNetPeer peer) { return peer.m_rpc.GetSocket().GetHostName(); } } public static class WorldHelpers { public static string GetPlayerInfo() { string[] value = (from x in Player.GetAllPlayers() select x.GetPlayerID() + " - " + x.GetPlayerName()).ToArray(); return string.Join("\n", value); } } public static class ZdoUtils { public static string GetPrefabName(this ZDO zdo) { int prefab = zdo.GetPrefab(); GameObject prefab2 = ZNetScene.instance.GetPrefab(prefab); return ((prefab2 != null) ? ((Object)prefab2).name : null) ?? $"Unknown({prefab})"; } public static ZdoSummary? GetSummary(this ZDO zdo) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown return new ZdoSummary(zdo.GetPrefabName(), zdo.GetPosition().ToFacade(), zdo.GetRotation().ToFacade(), zdo.GetBool(ZDOVars.s_tamed, false), zdo.GetString("tag", "")); } public static ZDO SafeSet(this ZDO zdo, string key, string value) { if (!string.IsNullOrEmpty(value)) { zdo.Set(key, value); } return zdo; } public static ZDO SafeSet(this ZDO zdo, string key, int value) { if (value != 0) { zdo.Set(key, value); } return zdo; } public static ZDO SafeSet(this ZDO zdo, string key, bool value) { if (value) { zdo.Set(key, value); } return zdo; } public static ZDO SafeSet(this ZDO zdo, int key, bool value) { if (value) { zdo.Set(key, value); } return zdo; } } public static class ZHelpers { public static PlayerResponse Create(this ZNetPeer player) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown return new PlayerResponse(player.GetSteamId(), player.m_playerName, player.GetRefPos().ToFacade(), ZoneSystem.GetZone(player.GetRefPos()).ToFacade()); } } public static class ZPackageExtensions { public static void WriteObject<T>(this ZPackage pkg, T obj) { string text = JsonConvert.SerializeObject((object)obj); pkg.Write(text); } public static ZPackage ToZPackage<T>(this T obj) { //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 string text = JsonConvert.SerializeObject((object)obj); ZPackage val = new ZPackage(); val.Write(text); return val; } } } namespace PolyhydraGames.Valheim.RestServer.Converters { public static class DtoConverters { public static Type ToLocal(this Type val) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return (Type)val; } public static Vector3 ToLocal(this Vector3Dto? val) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) if (!(val == (Vector3Dto)null)) { return new Vector3(val.X, val.Y, val.Z); } return Vector3.zero; } public static Quaternion ToQuaternion(this Vector3Dto? val) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) if (!(val == (Vector3Dto)null)) { return new Quaternion(val.X, val.Y, val.Z, 0f); } return default(Quaternion); } public static Vector2i ToLocal(this Vector2iDto? val) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) if (!(val == (Vector2iDto)null)) { return new Vector2i(val.X, val.Y); } return Vector2i.zero; } } } namespace PolyhydraGames.Valheim.RestServer.Commands { public sealed class CustomCommand : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "command"; public override string Description => "Execute a custom server command"; protected override PostResponse OnHandleInternal(CommandRequestType args) { return Response.Pass(ServerConsole.Execute(args.Raw), Method); } } internal class FindPlayer : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "findPlayer"; public override string Description => "Find a player and show their details. Usage: findPlayer <playername or steamid>"; protected override PostResponse OnHandleInternal(CommandRequestType args) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Expected O, but got Unknown string @string = CommandRequest.GetString(args, 0); ZNetPeer val = ZNet.instance.GetPeerByPlayerName(@string) ?? ZNet.instance.GetPeerByHostName(@string); if (val == null) { return Fail("Player {user} not found"); } ZDO zDO = val.GetZDO(); bool flag = zDO == null; return Response.Pass<PlayerInfoResponse>(new PlayerInfoResponse(@string, val.GetSteamId(), val.m_playerName, flag, flag ? null : val.GetRefPos().ToFacade(), flag ? null : ZoneSystem.GetZone(val.GetRefPos()).ToFacade(), flag ? null : new float?(zDO.GetFloat(ZDOVars.s_health, 0f)), flag ? null : new float?(zDO.GetFloat(ZDOVars.s_maxHealth, 0f))), Method); } } internal class GetServerStats : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "serverstats"; public override string Description => "Prints server statistics including player count, FPS, memory usage, and world information."; protected override PostResponse OnHandleInternal(CommandRequestType args) { //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Expected O, but got Unknown try { string obj = ZNet.World?.m_name ?? "INVALID WORLD"; ZNet instance = ZNet.instance; int num = ((instance != null) ? instance.GetPeers().Count : (-1)); float num2 = 1f / Time.deltaTime; ZDOMan instance2 = ZDOMan.instance; int num3 = ((instance2 != null) ? instance2.NrOfObjects() : (-1)); EnvMan instance3 = EnvMan.instance; int num4; if (instance3 == null) { num4 = -1; } else { ZNet instance4 = ZNet.instance; num4 = instance3.GetDay((instance4 != null) ? instance4.GetTimeSeconds() : 0.0); } int num5 = num4; int num6 = ToMegabytes(Profiler.GetMonoUsedSizeLong()); int num7 = ToMegabytes(Profiler.GetMonoHeapSizeLong()); return Response.Pass<ServerStats>(new ServerStats(obj, num, Math.Round(num2, 1), (long)num6, (long)num7, num5, num3, 0), Method); } catch (Exception ex) { Logger.LogError(ex, "Get Server Stats failed"); return ex.Fail(Method); } } private int ToMegabytes(long bytes) { return Mathf.FloorToInt((float)bytes / 1048576f); } } public sealed class InfoCommand : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "info"; public override string Description => "Print system info / memory."; protected override PostResponse OnHandleInternal(CommandRequestType args) { return Pass(ServerConsole.Execute("info")); } } internal class InvokeConsoleCommand : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "consoleCommand"; public override string Description => "Executes a console command on the server."; protected override PostResponse OnHandleInternal(CommandRequestType args) { ((Terminal)Console.instance).TryRunCommand(args.Command + " " + args.Raw, false, true); return Pass("Command '" + args.Command + "' executed."); } } internal class Ping : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "ping"; public override string Description => "Sends a ping message to all players at the specified coordinates. "; protected override PostResponse OnHandleInternal(CommandRequestType args) { string vector = CommandRequest.GetVector3(args, 0); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "ChatMessage", new object[4] { vector, 3, "", "" }); return Pass("Ping sent to " + vector); } } internal class StopRaid : IRestAction { public string Method => "stopraid"; public string Description => "Stop the current raid/event."; public PostResponse OnHandle(CommandRequestType args) { RandEventSystem.instance.ConsoleResetRandomEvent(); return Response.Pass("Raid/event stopped.", Method); } } internal class SayChat : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "say"; public override string Description => "Sends a message to the chat as a shout."; protected override PostResponse OnHandleInternal(CommandRequestType args) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) string raw = args.Raw; Vector3 val = default(Vector3); if (!ZoneSystem.instance.GetLocationIcon(Game.instance.m_StartLocation, ref val)) { ((Vector3)(ref val))..ctor(0f, 30f, 0f); } ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "ChatMessage", new object[4] { val, 2, "Server:", raw }); return Pass("Sent to chat - " + raw); } } internal static class ServerConsole { public static string Execute(string command) { try { if ((Object)(object)Console.instance != (Object)null) { ((Terminal)Console.instance).TryRunCommand(command, false, false); return "ok: " + command; } return "dispatched: " + command; } catch (Exception ex) { Debug.LogError((object)$"[Rest] console error running '{command}': {ex}"); return "error: " + ex.Message; } } } internal class ServerTimeCommand : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "time"; public override string Description => "Get the current server time and day."; protected override PostResponse OnHandleInternal(CommandRequestType args) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown double timeSeconds = ZNet.instance.GetTimeSeconds(); return Response.Pass<TimeResponse>(new TimeResponse(EnvMan.instance.GetDay(), timeSeconds), Method); } } public class ShoutAction : IRestAction { public Func<CommandRequestType, PostResponse> OnRequest { get; init; } public string Method => "shout"; public string Description => "Shouts to everyone"; public PostResponse OnHandle(CommandRequestType request) { return OnRequest(request); } } internal class ShowMessage : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "showMessage"; public override string Description => "Displays a message in the center of the screen for all players. Usage: showMessage <message>"; protected override PostResponse OnHandleInternal(CommandRequestType args) { ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "ShowMessage", new object[2] { 2, args.Raw }); return Pass("Message sent - " + args.Raw); } } internal class SpawnNPC : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "spawnnpc"; public override string Description => "Creates NPCs or objects in the world."; protected override PostResponse OnHandleInternal(CommandRequestType request) { SpawnRequest val = CommandRequest.Get<SpawnRequest>(request); if (val == (SpawnRequest)null) { return Fail("Spawn args were null."); } GameObject prefab = PrefabManager.Instance.GetPrefab(val.PrefabName); if ((Object)(object)prefab == (Object)null) { return Fail("Prefab '" + val.PrefabName + "' not found."); } return SpawnPrefabs(prefab, val); } protected PostResponse SpawnPrefabs(GameObject go, SpawnRequest args) { //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) GameObject prefab = ZNetScene.instance.GetPrefab(args.PrefabName); if ((Object)(object)prefab == (Object)null) { return Response.Fail("Prefab " + args.PrefabName + " not found"); } if (args.Count <= 0) { return Response.Fail("Nothing to spawn"); } List<ZDO> list = new List<ZDO>(args.Count); Character val3 = default(Character); ItemDrop val4 = default(ItemDrop); for (int i = 0; i < args.Count; i++) { ZNetView.StartGhostInit(); Vector3 onUnitSphere = Random.onUnitSphere; Vector3 val = ((Vector3)(ref onUnitSphere)).magnitude * args.Rotation.ToLocal(); val.y = 0f; Vector3 val2 = args.Position.ToLocal() + val; GameObject obj = Object.Instantiate<GameObject>(prefab, val2, args.Rotation.ToQuaternion()); if (obj.TryGetComponent<Character>(ref val3)) { val3.SetLevel(args.Level); } if (obj.TryGetComponent<ItemDrop>(ref val4)) { val4.SetQuality(args.Level); } ZDO zDO = obj.GetComponent<ZNetView>().GetZDO(); list.Add(zDO); if (!string.IsNullOrEmpty(args.Tag)) { zDO.Set(args.Tag, true); } if (args.Tamed) { zDO.Set(ZDOVars.s_tamed, true); } ZNetView.FinishGhostInit(); Object.Destroy((Object)(object)obj); } List<ZdoSummary> list2 = new List<ZdoSummary>(); foreach (ZDO item in list) { list2.Add(item.GetSummary()); } return list2.Pass(Method); } private static void ApplySpawnProperties(GameObject go, SpawnRequest args) { ZNetView component = go.GetComponent<ZNetView>(); ((component != null) ? component.GetZDO() : null)?.SafeSet("tag", args.Tag).SafeSet("level", args.Level).SafeSet(ZDOVars.s_tamed, args.Tamed); } private static Vector3 GetSpawnPosition(Vector3 center, float? radius) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0038: 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 (!radius.HasValue || radius.Value <= 0f) { return center; } Vector3 val = Random.insideUnitSphere * radius.Value; val.y = 0f; return center + val; } } internal class TeleportPlayer : PlayerRestRequest<TeleportRequest> { public override string Command => "RPC_TeleportTo"; public override string Method => "teleport"; public override string Description => "Teleports the player to a specified position."; protected override PostResponse OnHandle(PlayerWrapperType player, TeleportRequest args) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) InvokeRoutedAtTarget(player, args.Position.ToLocal(), Quaternion.identity, true); return Response.Pass($"Player {player.Name} teleported to {args.Position.ToLocal()}", Method); } } internal class WorldSave : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "save"; public override string Description => "Save the current world state."; protected override PostResponse OnHandleInternal(CommandRequestType args) { ZNet.instance.Save(false, false, false); return Response.Pass("World save started", Method); } } } namespace PolyhydraGames.Valheim.RestServer.Commands.Whisper { public static class Metadata { public const string TestString = "whisper 76561197962914477 Dan Howdy ho"; public const string RCPCall = "Whisper"; public const string Command = "whisper"; public const string Description = "Whisper a player."; public const string Usage = "Usage: whisper <player> <name> <message> "; public const int MinimumParameters = 3; } internal class Whisper : PlayerRestRequest<MessageRequest> { public override string Command => "Whisper"; public override string Method => "whisper"; public override string Description => "Whisper a player."; private PostResponse ProcessCommand(PlayerWrapperType player, MessageRequest args) { InvokeJsonRouted<MessageRequest>(player, args); return Response.Pass("Applied Whisper to " + player.Name, Method); } protected override PostResponse OnHandle(PlayerWrapperType player, MessageRequest args) { return ProcessCommand(player, args); } } [HarmonyPatch(typeof(Game))] public static class WhisperRpc { [HarmonyPostfix] [HarmonyPatch("Start")] private static void Register() { ZRoutedRpc.instance.Register<string>("Whisper", (Action<long, string>)Whisper); } private static void Whisper(long sender, string args) { MessageRequest obj = JsonHelpers.FromJson<MessageRequest>(args); string message = obj.Message; string senderName = obj.SenderName; Logger.LogInfo("Received Whisper, name: " + senderName + " message: " + message); if ((Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)GameCamera.instance == (Object)null) { return; } try { ((Terminal)Chat.instance).AddString(senderName, message, (Type)1, false); UIHelpers.ShowPopup((MessageType)1, senderName + ": " + message); Logger.LogInfo("Whisper shake triggered with amount "); } catch (Exception ex) { Logger.LogInfo("Screen shake failed. " + ex.Message); } } } } namespace PolyhydraGames.Valheim.RestServer.Commands.SetWeather { public static class Metadata { public const string RCPCall = "SetWeather"; public const string Command = "setweather"; public const string Description = "set weather a player."; } internal class SetWeather : PlayerRestRequest<PlayerRequest> { public override string Command => "SetWeather"; public override string Method => "setweather"; public override string Description => "set weather a player."; protected override PostResponse OnHandle(PlayerWrapperType player, PlayerRequest args) { InvokeJsonRouted<PlayerRequest>(player, args); return Response.Pass("Weather set '" + args.TargetPlayer + "'", Method); } } [HarmonyPatch(typeof(Game))] public static class SetWeatherRPC { [HarmonyPostfix] [HarmonyPatch("Start")] private static void RegisterRpc() { Logger.LogInfo("Registered RCPCall"); ZRoutedRpc.instance.Register("SetWeather", (Action<long>)SmiteAction); } private static void SmiteAction(long _) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) Logger.LogInfo("Received request to SetWeather"); ZNetScene instance = ZNetScene.instance; if ((Object)(object)instance == (Object)null) { Logger.LogWarning("No ZNetScene available yet!"); return; } Vector3 position = ((Component)Player.m_localPlayer).transform.position; string[] names = new string[3] { "lightningAOE", "vfx_lightning_hit", "fx_thunder" }; var (flag, text, text2) = TrySpawnFirstNetworked(instance, position, Quaternion.identity, names); if (flag) { Logger.LogInfo("Smite spawned prefab " + text); } else { Logger.LogWarning("Smite failed: " + text2); } } private static (bool ok, string used, string reason) TrySpawnFirstNetworked(ZNetScene zns, Vector3 pos, Quaternion rot, string[] names) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) foreach (string text in names) { GameObject prefab = zns.GetPrefab(text); if (!((Object)(object)prefab == (Object)null) && !((Object)(object)prefab.GetComponent<ZNetView>() == (Object)null)) { GameObject val = Object.Instantiate<GameObject>(prefab, pos, rot); if ((Object)(object)val.GetComponent<TimedDestruction>() == (Object)null) { Object.Destroy((Object)(object)val, 5f); } return (true, text, ""); } } return (false, "", "no networked prefabs among: " + string.Join(", ", names)); } } } namespace PolyhydraGames.Valheim.RestServer.Commands.Raids { internal class StartRaidCommand : RestRequest<RaidRequest> { public override string Method => "startraid"; public override string Description => "Start a raid at player location."; public override PostResponse OnHandle(RaidRequest args) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) if (!RandEventSystem.instance.HaveEvent(args.Name)) { return Response.Fail("No such event: " + args.Name); } Vector3 val = args.Position.ToLocal(); RandEventSystem.instance.SetRandomEventByName(args.Name, val); return args.Pass<RaidRequest>("Raid started: " + args.Name + " " + ((val != Vector3.zero) ? "at player" : "globally")); } } internal class StartRandomRaid : IRestAction { public string Method => "randomraid"; public string Description => "Start a random raid from eligible events."; public PostResponse OnHandle(CommandRequestType args) { RandEventSystem.instance.ConsoleStartRandomEvent(); return Response.Pass("Random raid triggered.", Method); } } } namespace PolyhydraGames.Valheim.RestServer.Commands.Players { internal class Damage : PlayerRestRequest<PlayerAmountRequest> { public override string Command => "RPC_Damage"; public override string Method => "damage"; public override string Description => "Damage a player by a specified amount."; protected override PostResponse OnHandle(PlayerWrapperType player, PlayerAmountRequest args) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown ZNetPeer peer = player.Peer; HitData val = new HitData { m_blockable = false, m_dodgeable = false, m_ignorePVP = true, m_hitType = (HitType)0, m_damage = new DamageTypes { m_damage = args.Amount } }; InvokeRoutedAtTarget(player, val); return Response.Pass($"{peer.m_playerName} damaged to {val.m_damage.m_damage}hp", Method); } } internal class SpawnItem : PlayerRestRequest<GiveRequest> { public override string Command { get; } public override string Method => "spawnobject"; public override string Description => "Spawns an item on the player."; protected override PostResponse OnHandle(PlayerWrapperType player, GiveRequest args) { //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Expected O, but got Unknown int num = 0; try { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(args.ItemName); if ((Object)(object)itemPrefab == (Object)null) { return Response.Fail("Cannot find prefab " + args.ItemName); } if (args.Count > Constants.GiveItem_MaxCount) { return Response.Fail($"Count Max: {Constants.GiveItem_MaxCount} Request:{args.Count}"); } ZNetView.StartGhostInit(); ZNetPeer peer = player.Peer; ItemData obj = itemPrefab.GetComponent<ItemDrop>().m_itemData.Clone(); num = 1; obj.m_dropPrefab = itemPrefab; obj.m_quality = args.Quality; ItemDrop obj2 = ItemDrop.DropItem(obj, args.Count, peer.GetRefPos(), Quaternion.identity); num = 2; ZNetView.FinishGhostInit(); num = 3; Object.Destroy((Object)(object)((Component)obj2).gameObject); num = 4; return Response.Pass<GiveResponse>(new GiveResponse(args.ItemName, args.Count, peer.m_playerName, peer.GetRefPos().ToFacade()), Method); } catch (Exception ex) { return ex.Fail($"GiveItem: OnHandle failed? {num}"); } } } internal class Heal : PlayerRestRequest<PlayerAmountRequest> { public override string Command => "RPC_Heal"; public override string Method => "heal"; public override string Description => "Heals the player's to a specified value. Usage: heal <steamid> <value>"; protected override PostResponse OnHandle(PlayerWrapperType player, PlayerAmountRequest args) { InvokeRoutedAtTarget(player, args.Amount, true); return Response.Pass($"{player.Peer.m_playerName} healed to {args.Amount} hp", Method); } } internal class Kick : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "kick"; public override string Description => "Kicks a player from the server. Usage: kick <playername or steamid>"; protected override PostResponse OnHandleInternal(CommandRequestType args) { string @string = CommandRequest.GetString(args, 0); ZNet.instance.Kick(@string); return Pass("Kicked " + @string); } } internal class ShowPlayers : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "players"; public override string Description => "Show all online players with their positions and zones"; protected override PostResponse OnHandleInternal(CommandRequestType args) { return (from x in ZNet.instance.GetPeers() select x.Create()).Pass(Method); } } } namespace PolyhydraGames.Valheim.RestServer.Commands.Players.Smite { public static class Metadata { public const string RCPCall = "Smite"; public const string Command = "smite"; public const string Description = "smite a player."; public const string Usage = "Usage: smite <player> <powerName> "; public const int MinimumParameters = 2; } internal class Smite : PlayerRestRequest<PlayerRequest> { public override string Command { get; } public override string Method => "smite"; public override string Description => "smite a player."; protected override PostResponse OnHandle(PlayerWrapperType player, PlayerRequest args) { InvokeJsonRouted<PlayerRequest>(player, args); return Response.Pass("Smote '" + player.Name + "'", Method); } } [HarmonyPatch(typeof(Game))] public static class SmiteRPC { [HarmonyPostfix] [HarmonyPatch("Start")] private static void RegisterRpc() { Logger.LogInfo("Registered SmiteRPC"); ZRoutedRpc.instance.Register("Smite", (Action<long>)SmiteAction); } private static void SmiteAction(long _) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) Logger.LogInfo("Received request to Smite"); ZNetScene instance = ZNetScene.instance; if ((Object)(object)instance == (Object)null) { Logger.LogWarning("No ZNetScene available yet!"); return; } Vector3 position = ((Component)Player.m_localPlayer).transform.position; string[] names = new string[3] { "lightningAOE", "vfx_lightning_hit", "fx_thunder" }; var (flag, text, text2) = TrySpawnFirstNetworked(instance, position, Quaternion.identity, names); if (flag) { Logger.LogInfo("Smite spawned prefab " + text); } else { Logger.LogWarning("Smite failed: " + text2); } } private static (bool ok, string used, string reason) TrySpawnFirstNetworked(ZNetScene zns, Vector3 pos, Quaternion rot, string[] names) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) foreach (string text in names) { GameObject prefab = zns.GetPrefab(text); if (!((Object)(object)prefab == (Object)null) && !((Object)(object)prefab.GetComponent<ZNetView>() == (Object)null)) { GameObject val = Object.Instantiate<GameObject>(prefab, pos, rot); if ((Object)(object)val.GetComponent<TimedDestruction>() == (Object)null) { Object.Destroy((Object)(object)val, 5f); } return (true, text, ""); } } return (false, "", "no networked prefabs among: " + string.Join(", ", names)); } } } namespace PolyhydraGames.Valheim.RestServer.Commands.Players.Shake { public static class Metadata { public const string TestString = "shake 76561197962914477 5"; public const string RCPCall = "Shake"; public const string Command = "shake"; public const string Description = "Shake a player."; public const string Usage = "Usage: shake <player> <amount> "; public const int MinimumParameters = 2; } internal class Shake : PlayerRestRequest<ShakeRequest> { public override string Command => "Shake"; public override string Method => "shake"; public override string Description => "Shake a player."; protected override PostResponse OnHandle(PlayerWrapperType player, ShakeRequest args) { InvokeJsonRouted<ShakeRequest>(player, args); return Response.Pass($"Applied shake {args.Intensity} to {player.Name}", Method); } } [HarmonyPatch(typeof(Game))] public static class ShakeRpc { [HarmonyPostfix] [HarmonyPatch("Start")] private static void Register() { ZRoutedRpc.instance.Register<string>("Shake", (Action<long, string>)OnCalled); } private static void OnCalled(long sender, string args) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) ShakeRequest val = JsonHelpers.FromJson<ShakeRequest>(args); Logger.LogInfo($"Received Screen Shake, amount: {val}"); if ((Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)GameCamera.instance == (Object)null) { return; } try { float num = 10f; Vector3 position = Player.m_localPlayer.GetPosition(); GameCamera.instance.AddShake(position, num, val.Intensity, false); Logger.LogInfo($"Screen shake triggered with amount {val}"); } catch (Exception ex) { Logger.LogInfo("Screen shake failed. " + ex.Message); } } } } namespace PolyhydraGames.Valheim.RestServer.Commands.Players.AddNoise { internal class AddNoise : PlayerRestRequest<AddNoiseRequest> { public override string Command => "AddNoise"; public override string Method => "addnoise"; public override string Description => "Plays a noise in the vicinity of the player."; protected override PostResponse OnHandle(PlayerWrapperType player, AddNoiseRequest args) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) Logger.LogInfo($"[Server] Received request to play audio at {player.Name} - {args.Noise} - {player.RefPosition}"); if (args.Position.X == 0f && args.Position.Y == 0f && args.Position.Z == 0f) { AddNoiseRequest obj = args.<Clone>$(); obj.set_Position(player.RefPosition.ToFacade()); args = obj; } InvokeJsonRouted<AddNoiseRequest>(player, args); return Response.Pass("Played noise '" + args.Noise + "' at " + player.Name, Method); } } [HarmonyPatch(typeof(Game))] public static class AddNoiseBootStrap { [HarmonyPostfix] [HarmonyPatch("Start")] private static void Register() { Logger.LogInfo("Registered AddNoiseBootStrap"); ZRoutedRpc.instance.Register<string>("AddNoise", (Action<long, string>)PlayNoise); } private static void PlayNoise(long sender, string package) { //IL_0034: 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) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) AddNoiseRequest val = JsonHelpers.FromJson<AddNoiseRequest>(package); Logger.LogInfo($"[Player] Received request to play audio at {val.TargetPlayer} - {val.Noise} - {val.Position}"); string noise = val.Noise; Vector3 position = Player.m_localPlayer.GetPosition(); if (noise.Contains("https:")) { Logger.LogInfo("Received URL request to playNoise " + noise); try { AudioHelper audioHelper = new AudioHelper(); ((MonoBehaviour)CoroutineRunner.Instance).StartCoroutine(audioHelper.PlayAudioFromUrl(noise, position)); return; } catch (Exception ex) { Logger.LogError(ex.Message); return; } } Logger.LogInfo("Received URL request to playNoise " + noise); GameObject prefab = PrefabManager.Instance.GetPrefab(noise); if ((Object)(object)prefab != (Object)null) { Object.Instantiate<GameObject>(prefab, position, Quaternion.identity); Logger.LogWarning($"Played {noise} at {position}"); } else { Logger.LogWarning("Effect prefab " + noise + " not found!"); } } } public static class Metadata { public const string TestString = "addnoise 76561197962914477 https://cdn.polyhydragames.com/audio/no.mp3 10 10 1"; public const string RCPCall = "AddNoise"; public const string Command = "addnoise"; public const string Description = "Plays a noise in the vicinity of the player."; public const string Usage = "Usage: addnoise <player> <noiseName> <position>"; public const int MinimumParameters = 2; } } namespace PolyhydraGames.Valheim.RestServer.Commands.Players.AddEffect { internal class AddEffect : PlayerRestRequest<AddEffectRequest> { public override string Command => "ApplyStatusEffect"; public override string Method => "addeffect"; public override string Description => "Adds a status to the player. Usage: addstatus <player> <statusName>"; protected override PostResponse OnHandle(PlayerWrapperType player, AddEffectRequest args) { if (string.IsNullOrEmpty(args.EffectName)) { Response.Fail(string.Join(", ", DatabaseHelpers.GetStatusEffects()), Method); } InvokeJsonRouted<AddEffectRequest>(player, args); return Response.Pass("Applied status '" + player.Name + "' to " + player.Name, Method); } } [HarmonyPatch(typeof(Game))] public static class AddEffectBootStrap { [HarmonyPostfix] [HarmonyPatch("Start")] public static void Register() { ZRoutedRpc.instance.Register<string>("ApplyStatusEffect", (Action<long, string>)OnApplyStatusEffect); } private static void OnApplyStatusEffect(long sender, string args) { AddEffectRequest val = JsonHelpers.FromJson<AddEffectRequest>(args); Logger.LogInfo("Client received request to apply " + val.EffectName); Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null)) { StatusEffect effect = DatabaseHelpers.GetEffect(val.EffectName); if ((Object)(object)effect != (Object)null) { ((Character)localPlayer).GetSEMan().AddStatusEffect(effect, true, 0, 0f); ((Terminal)Chat.instance).AddString("[Odin] You are blessed with " + effect.m_name + "!"); } else { Logger.LogWarning("StatusEffect " + val.EffectName + " not found in ObjectDB"); } } } } public static class Metadata { public const string Test = "addeffect 76561197962914477 SE_Rested"; public const string RCPCall = "ApplyStatusEffect"; public const string Command = "addeffect"; public const string Description = "Adds a status to the player. Usage: addstatus <player> <statusName>"; public const string Usage = "Usage: addstatus <player> <statusName>"; public const int MinimumParameters = 2; } } namespace PolyhydraGames.Valheim.RestServer.Commands.GlobalKeys { internal class AddGlobalKeyCommand : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "addglobalkey"; public override string Description => "Adds a global key to the server. "; protected override PostResponse OnHandleInternal(CommandRequestType args) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) if (Enum.TryParse<GlobalKeys>(args.Raw, out GlobalKeys result)) { ZoneSystem.instance.SetGlobalKey(result); return Response.Pass($"Added global key: {result}", Method); } return Response.Fail("Unable to parse " + args.Raw); } } internal class GetGlobalKeysCommand : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "globalkeys"; public override string Description => "Gets all global keys and their values."; protected override PostResponse OnHandleInternal(CommandRequestType args) { return ZoneSystem.instance.m_globalKeysValues.Select((KeyValuePair<string, string> x) => Converters.CreateGlobalKey(x)).Pass(Method); } } internal class RemoveGlobalKeyCommand : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "removeglobalkey"; public override string Description => "Removes a global key from the server. Usage: removeGlobalKey <key>"; protected override PostResponse OnHandleInternal(CommandRequestType args) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) GlobalKeys? globalKey = args.GetGlobalKey(0); if (!globalKey.HasValue) { return Response.Fail("No key found with value " + CommandRequest.GetString(args, 0)); } ZoneSystem.instance.RemoveGlobalKey(globalKey.Value); return Response.Pass($"Global key '{globalKey}' removed successfully.", Method); } } public class ResetKeysAction : IRestAction { public Func<CommandRequestType, PostResponse> OnRequest { get; init; } public string Method => "resetglobalkeys"; public string Description => "Delete old boss kill data"; public PostResponse OnHandle(CommandRequestType request) { ZoneSystem.instance.ResetGlobalKeys(); return Response.Pass("Global keys reset via REST", Method); } } } namespace PolyhydraGames.Valheim.RestServer.Commands.Events { internal class GetEvent : IRestAction { public string Method => "getevent"; public string Description => "Get current active/random raid event."; public PostResponse OnHandle(CommandRequestType args) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown RandomEvent activeEvent = RandEventSystem.instance.GetActiveEvent(); RandomEvent currentRandomEvent = RandEventSystem.instance.GetCurrentRandomEvent(); if (activeEvent == null && currentRandomEvent == null) { return args.Fail("No active raid."); } return Response.Pass<EventResponse>(new EventResponse(activeEvent?.m_name ?? "none", currentRandomEvent?.m_name ?? "none"), "getevent"); } } internal class ListEvents : IRestAction { public string Method => "listevents"; public string Description => "List all available random events."; public PostResponse OnHandle(CommandRequestType args) { return ((IEnumerable<RandomEvent>)RandEventSystem.instance.m_events).Select((Func<RandomEvent, EnabledState>)((RandomEvent x) => new EnabledState(x.m_name, x.m_enabled))).Pass(Method); } } } namespace PolyhydraGames.Valheim.RestServer.Commands.Communication { internal class Impersonate : IRestAction { private static readonly Dictionary<string, UserInfo> ImpersonatedUsers = new Dictionary<string, UserInfo>(); private static ulong NextId = 1uL; public string Method => "impersonate"; public string Description => "Sends a message to the chat as a shout. Usage: impersonate <name> <message>"; public UserInfo CreateUser(string name) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown return new UserInfo { Name = name, UserId = new PlatformUserID("Bot", NextId++, false) }; } private UserInfo GetUserInfo(string name) { if (ImpersonatedUsers.ContainsKey(name)) { return ImpersonatedUsers[name]; } return CreateUser(name); } public PostResponse OnHandle(CommandRequestType args) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) MessageRequest val = JsonHelpers.FromJson<MessageRequest>(args.Raw); try { Vector3 val2 = default(Vector3); if (!ZoneSystem.instance.GetLocationIcon(Game.instance.m_StartLocation, ref val2)) { ((Vector3)(ref val2))..ctor(0f, 30f, 0f); } ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "Whisper", new object[4] { val2, 2, GetUserInfo(val.SenderName), val.Message }); return args.Pass("Impersonated: " + val.SenderName + " - " + val.Message); } catch (Exception ex) { return ex.Fail(" FAILED !!! Impersonated: " + val.SenderName + " - " + val.Message); } } } } namespace PolyhydraGames.Valheim.RestServer.Commands.Bans { public sealed class Ban : PlayerRestRequest<PlayerRequest> { public override string Command { get; } public override string Method => "ban"; public override string Description => "Ban a player by name/host/id."; protected override PostResponse OnHandle(PlayerWrapperType player, PlayerRequest args) { string targetPlayer = args.TargetPlayer; ZNet.instance.Ban(targetPlayer); return Response.Pass("Banned " + targetPlayer, Method); } } internal class PrintBanlist : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "banlist"; public override string Description => "Prints the list of banned players"; protected override PostResponse OnHandleInternal(CommandRequestType args) { return ZNet.instance.Banned.Pass(Method); } } internal class Unban : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "unban"; public override string Description => "Unban a user from the server. Usage: unban <playername or steamid>"; protected override PostResponse OnHandleInternal(CommandRequestType args) { string @string = CommandRequest.GetString(args, 0); ZNet.instance.Unban(@string); return Response.Pass(@string + " unbanned", Method); } } } namespace PolyhydraGames.Valheim.RestServer.Commands.Admins { internal class AddAdmin : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "addadmin"; public override string Description => "Adds a player to the admin list. Usage: addAdmin <steamId>"; protected override PostResponse OnHandleInternal(CommandRequestType args) { ZNet.instance.GetAdminList().Add(args.Raw); return Pass(args.Raw + " is admin now"); } } internal class GetAdmins : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "adminlist"; public override string Description => "Prints the list of admins on the server."; protected override PostResponse OnHandleInternal(CommandRequestType args) { return ZNet.instance.GetAdminList().Pass(Method); } } internal class RemoveAdmin : PolyhydraGames.Valheim.RestServer.Commands.Abstract.RestRequest { public override string Method => "removeadmin"; public override string Description => "Removes a player from the admin list."; protected override PostResponse OnHandleInternal(CommandRequestType args) { string @string = CommandRequest.GetString(args, 0); ZNet.instance.GetAdminList().Remove(@string); return Response.Pass(@string + " removed from admins", Method); } } } namespace PolyhydraGames.Valheim.RestServer.Commands.Abstract { public abstract class PlayerRestRequest<T> : IRestAction where T : IPlayerRequest { public static readonly UserInfo ServerUserInfo = new UserInfo { Name = string.Empty, UserId = new PlatformUserID("Bot", 0uL, false) }; public abstract string Command { get; } public abstract string Method { get; } public abstract string Description { get; } public PostResponse OnHandle(CommandRequestType args) { T val = CommandRequest.Get<T>(args); ZNetPeer peer = GetPeer(val); return OnHandle(PlayerWrapper.Create(peer), val); } private ZNetPeer? GetPeer(T request) { string targetPlayer = ((IPlayerRequest)request).TargetPlayer; ZNetPeer val = ZNet.instance.GetPeerByHostName(targetPlayer) ?? ZNet.instance.GetPeerByPlayerName(targetPlayer); if (val == null) { return null; } return val; } protected abstract PostResponse OnHandle(PlayerWrapperType player, T args); protected void InvokeJsonRouted<T>(PlayerWrapperType player, T request) { string text = JsonHelpers.ToJson<T>(request); ZRoutedRpc.instance.InvokeRoutedRPC(player.ZDOID, Command, new object[1] { text }); } protected void InvokeRouted(PlayerWrapperType player, params object[] args) { ZRoutedRpc.instance.InvokeRoutedRPC(player.ZDOID, Command, args); } protected bool InvokeRoutedAtTarget(PlayerWrapperType player, params object[] args) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) if (player.GetZDO == null) { return false; } ZRoutedRpc.instance.InvokeRoutedRPC(player.Owner.Value, player.ZdoUid.Value, Command, args); return true; } protected void InvokeZPackageRouted(PlayerWrapperType player, HitData hitData) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown ZPackage val = new ZPackage(); hitData.Serialize(ref val); ZRoutedRpc.instance.InvokeRoutedRPC(player.ZDOID, Command, new object[1] { val }); } } public abstract class RestRequest : IRestAction { public abstract string Method { get; } public abstract string Description { get; } public PostResponse OnHandle(CommandRequestType request) { Logger.LogInfo(((object)request).ToString()); return OnHandleInternal(request); } protected abstract PostResponse OnHandleInternal(CommandRequestType args); protected PostResponse Pass(string value) { return Response.Pass(value, Method); } protected PostResponse Fail(string error) { return Response.Fail(error); } } public abstract class RestRequest<T> : IRestAction { public abstract string Method { get; } public abstract string Description { get; } public abstract PostResponse OnHandle(T request); public PostResponse OnHandle(CommandRequestType request) { Logger.LogInfo("Method: " + request.Command + " Received: " + request.Raw); T request2 = CommandRequest.Get<T>(request); return OnHandle(request2); } } }
PolyhydraGames.Valheim.Core.dll
Decompiled 5 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using PolyhydraGames.Valheim.Core.Fascade; using PolyhydraGames.Valheim.Core.Models; using PolyhydraGames.Valheim.Core.Requests; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("PolyhydraGames.Valheim.Core")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+1ca51c0ede977c7fe861d590f3c8ff37211621cb")] [assembly: AssemblyProduct("PolyhydraGames.Valheim.Core")] [assembly: AssemblyTitle("PolyhydraGames.Valheim.Core")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } public class IsExternalInit { } } namespace PolyhydraGames.Valheim.Core { public static class ApiMethods { public const string Shake = "shake"; public const string AddEffect = "addeffect"; public const string AddNoise = "addnoise"; public const string Heal = "heal"; public const string Damage = "damage"; public const string Stagger = "stagger"; public const string Smite = "smite"; public const string Teleport = "teleport"; public const string FindPlayer = "findPlayer"; public const string ShowMessage = "showMessage"; public const string Say = "say"; public const string Ping = "ping"; public const string Shout = "shout"; public const string Impersonate = "impersonate"; public const string Whisper = "whisper"; public const string AddAdmin = "addadmin"; public const string RemoveAdmin = "removeadmin"; public const string AddPermitted = "addpermitted"; public const string RemovePermitted = "removepermitted"; public const string Ban = "ban"; public const string BanSteamId = "bansteamId"; public const string Unban = "unban"; public const string AdminList = "adminlist"; public const string BanList = "banlist"; public const string PermittedList = "permitted"; public const string GlobalKeys = "globalkeys"; public const string Logs = "logs"; public const string List = "list"; public const string Players = "players"; public const string AddGlobalKey = "addglobalkey"; public const string RemoveGlobalKey = "removeglobalkey"; public const string ResetGlobalKeys = "resetglobalkeys"; public const string Kick = "kick"; public const string ServerStats = "serverstats"; public const string TimeRaw = "timeraw"; public const string Time = "time"; public const string Save = "save"; public const string ConsoleCommand = "consoleCommand"; public const string ResetWind = "resetwind"; public const string SetWind = "setwind"; public const string SetTime = "settime"; public const string SetWeather = "setweather"; public const string SkipMorning = "skipmorning"; public const string RandomRaid = "randomraid"; public const string StopRaid = "stopraid"; public const string Raid = "startraid"; public const string SpawnObject = "spawnobject"; public const string SpawnNPC = "spawnnpc"; public const string Command = "command"; public const string Info = "info"; public const string LodBias = "lodbias"; public const string Explode = "explode"; public const string GetEvent = "getevent"; public const string ListEvents = "listevents"; } public static class CommandRequest { public static T? Get<T>(this CommandRequestType type) { try { return JsonConvert.DeserializeObject<T>(type.Raw); } catch (Exception ex) { Logger.LogError(ex.Message); return default(T); } } public static string[] Messages(this CommandRequestType type) { return type.Raw.Split(new char[1] { ' ' }); } public static string GetMessagesFrom(this CommandRequestType type, int startIndex) { return string.Join(" ", type.Messages().Skip(startIndex)); } public static string GetVector3(this CommandRequestType type, int startIndex) { return string.Join(" ", type.Messages().Skip(startIndex)); } public static float GetFloat(this CommandRequestType type, int i) { try { return float.Parse(type.Messages()[i]); } catch (Exception ex) { Logger.LogError(ex.Message); return 0f; } } public static long GetLong(this CommandRequestType type, int i) { try { return long.Parse(type.Messages()[i]); } catch (Exception ex) { Logger.LogError(ex.Message); return 0L; } } public static int GetInt(this CommandRequestType type, int i) { try { return int.Parse(type.Messages()[i]); } catch (Exception ex) { Logger.LogError(ex.Message); return 0; } } public static CommandRequestType Create(string method, string message) { return new CommandRequestType { Raw = message, Command = method }; } public static bool Validate(this CommandRequestType request, int segments) { return request.Command.Length >= segments; } public static int Count(this CommandRequestType request) { return request.Messages().Count(); } public static string GetString(this CommandRequestType request, int index) { return request.Messages()[index]; } } public static class Constants { public static int GiveItem_MaxCount = 100; } public static class Converters { public static GlobalKeyRequest CreateGlobalKey(this KeyValuePair<string, string> key) { return new GlobalKeyRequest(key.Key, key.Value); } } public enum GlobalKey { PlayerDamage, EnemyDamage, WorldLevel, EventRate, ResourceRate, StaminaRate, AdrenalineRate, MoveStaminaRate, StaminaRegenRate, SkillGainRate, SkillReductionRate, EnemySpeedSize, EnemyLevelUpRate, PlayerEvents, Fire, DeathKeepEquip, DeathDeleteItems, DeathDeleteUnequipped, DeathSkillsReset, NoBuildCost, NoCraftCost, AllPiecesUnlocked, NoWorkbench, AllRecipesUnlocked, WorldLevelLockedTools, PassiveMobs, NoMap, NoPortals, NoBossPortals, DungeonBuild, TeleportAll, Preset, NonServerOption, defeated_eikthyr, defeated_dragon, defeated_goblinking, defeated_gdking, defeated_bonemass, activeBosses, KilledTroll, killed_surtling, KilledBat, AshlandsOcean, Count } public interface IPlayerRequest { string TargetPlayer { get; } } public interface IPolyLogger { void LogInfo(string message); void LogWarning(string message); void LogError(string exMessage); } public interface IValheimRestServerConfig { string ApiKey { get; } string BaseUrl { get; } } public static class JsonHelpers { public static string ToJson<T>(this T obj) { return JsonConvert.SerializeObject((object)obj); } public static T FromJson<T>(this string obj) { return JsonConvert.DeserializeObject<T>(obj); } } public class Logger { private static IPolyLogger _logger; public static IPolyLogger Instance => _logger; public static void SetLogger(IPolyLogger logger) { _logger = logger; } public static void LogError(string exMessage) { _logger.LogError(exMessage); } public static void LogError(Exception ex, string title = "") { _logger.LogError(title + ex.Message); } public static void LogInfo(string message) { _logger.LogInfo(message); } public static void LogWarning(string message) { _logger.LogWarning(message); } } public class PointsOfInterest { public Vector3Dto Start { get; set; } } public static class Position { private static readonly Regex PositionRegex = new Regex("^\\s*\\((-?\\d+(\\.\\d+)?),\\s*(-?\\d+(\\.\\d+)?),\\s*(-?\\d+(\\.\\d+)?)\\)\\s*(\\((-?\\d+),\\s*(-?\\d+)\\))?\\s*$", RegexOptions.Compiled); public static Vector3Dto Default() { return new Vector3Dto(0f, 0f, 0f); } public static Vector3Dto Create(double x, double y, double z) { return new Vector3Dto((float)x, (float)y, (float)z); } public static Vector3Dto Create(string value) { Match match = PositionRegex.Match(value); if (!match.Success) { throw new Exception("Invalid position format: " + value); } float x = float.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); float y = float.Parse(match.Groups[5].Value, CultureInfo.InvariantCulture); float z = float.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture); if (match.Groups[8].Success && match.Groups[9].Success) { int.Parse(match.Groups[8].Value, CultureInfo.InvariantCulture); int.Parse(match.Groups[9].Value, CultureInfo.InvariantCulture); } return new Vector3Dto(x, y, z); } } public enum RpcCommand { SetGuardianPower, UseGuardianPower, PeerInfo, NetTime, ServerHandshake, ClientHandshake, ServerSyncedPlayerData, Disconnect, Error, Kick, Kicked, Ban, Unban, AdminList, Save, SavePlayerProfile, PlayerList, PrintBanned, RemoteCommand, RemotePrint, SpawnObject, DestroyZDO, RequestZDO, ZDOData, RoutedRPC, SetTrigger, Heal, Damage, Stagger, UseStamina, OnDeath, OnTargeted, FlashShield, AddStatusEffect, Controls, ReleaseControl, RequestControl, RequestRespons, ChatMessage, TeleportPlayer, Say, DropItem, DropItemByName, RequestOwn, SetPose, SetVisualItem, OpenRespons, RequestStack, StackResponse, RequestOpen, RequestTakeAll, TakeAllRespons, AddFuel, AddItem, RemoveDoneItem, SetSlotVisual, AddFuelAmount, SetFuelAmount, ToggleOn, Pickup, RequestPickup, UseDoor, Repair, Remove, HealthChanged, UpdateMaterial, SetAreaHealth, SetEvent, BossSpawnInitiated, RemoveBossSpawnInventoryItems, SpawnBoss, SetTamed, ResetCloth, FreezeFrame, OnHit, Attach, TeleportTo, StaggerCreature, OnEat, TryEat, EatConfirmation, Nibble, Step, Wakeup, Grow, Shake, Command, UnSummon, SetName, Forward, Backward, Rudder, Stop, AddSaddle, RemoveSaddle, SetSaddle, RequestControlShip, ReleaseControlShip, SetGlobalKey, RemoveGlobalKey, GlobalKeys, LocationIcons, AddNoise } public static class RpcCommandMap { public static readonly Dictionary<RpcCommand, string> Names = new Dictionary<RpcCommand, string> { { RpcCommand.SetGuardianPower, "RPC_SetGuardianPower" }, { RpcCommand.UseGuardianPower, "RPC_UseGuardianPower" }, { RpcCommand.PeerInfo, "RPC_PeerInfo" }, { RpcCommand.NetTime, "RPC_NetTime" }, { RpcCommand.ServerHandshake, "RPC_ServerHandshake" }, { RpcCommand.ClientHandshake, "RPC_ClientHandshake" }, { RpcCommand.ServerSyncedPlayerData, "RPC_ServerSyncedPlayerData" }, { RpcCommand.Disconnect, "RPC_Disconnect" }, { RpcCommand.Error, "RPC_Error" }, { RpcCommand.Kick, "RPC_Kick" }, { RpcCommand.Kicked, "RPC_Kicked" }, { RpcCommand.Ban, "RPC_Ban" }, { RpcCommand.Unban, "RPC_Unban" }, { RpcCommand.AdminList, "RPC_AdminList" }, { RpcCommand.Save, "RPC_Save" }, { RpcCommand.SavePlayerProfile, "RPC_SavePlayerProfile" }, { RpcCommand.PlayerList, "RPC_PlayerList" }, { RpcCommand.PrintBanned, "RPC_PrintBanned" }, { RpcCommand.RemoteCommand, "RPC_RemoteCommand" }, { RpcCommand.RemotePrint, "RPC_RemotePrint" }, { RpcCommand.SpawnObject, "RPC_SpawnObject" }, { RpcCommand.DestroyZDO, "RPC_DestroyZDO" }, { RpcCommand.RequestZDO, "RPC_RequestZDO" }, { RpcCommand.ZDOData, "RPC_ZDOData" }, { RpcCommand.RoutedRPC, "RPC_RoutedRPC" }, { RpcCommand.SetTrigger, "RPC_SetTrigger" }, { RpcCommand.Heal, "RPC_Heal" }, { RpcCommand.Damage, "RPC_Damage" }, { RpcCommand.Stagger, "RPC_Stagger" }, { RpcCommand.UseStamina, "RPC_UseStamina" }, { RpcCommand.OnDeath, "RPC_OnDeath" }, { RpcCommand.OnTargeted, "RPC_OnTargeted" }, { RpcCommand.FlashShield, "RPC_FlashShield" }, { RpcCommand.AddStatusEffect, "RPC_AddStatusEffect" }, { RpcCommand.Controls, "RPC_Controls" }, { RpcCommand.ReleaseControl, "RPC_ReleaseControl" }, { RpcCommand.RequestControl, "RPC_RequestControl" }, { RpcCommand.RequestRespons, "RPC_RequestRespons" }, { RpcCommand.ChatMessage, "RPC_ChatMessage" }, { RpcCommand.TeleportPlayer, "RPC_TeleportPlayer" }, { RpcCommand.Say, "RPC_Say" }, { RpcCommand.DropItem, "RPC_DropItem" }, { RpcCommand.DropItemByName, "RPC_DropItemByName" }, { RpcCommand.RequestOwn, "RPC_RequestOwn" }, { RpcCommand.SetPose, "RPC_SetPose" }, { RpcCommand.SetVisualItem, "RPC_SetVisualItem" }, { RpcCommand.OpenRespons, "RPC_OpenRespons" }, { RpcCommand.RequestStack, "RPC_RequestStack" }, { RpcCommand.StackResponse, "RPC_StackResponse" }, { RpcCommand.RequestOpen, "RPC_RequestOpen" }, { RpcCommand.RequestTakeAll, "RPC_RequestTakeAll" }, { RpcCommand.TakeAllRespons, "RPC_TakeAllRespons" }, { RpcCommand.AddFuel, "RPC_AddFuel" }, { RpcCommand.AddItem, "RPC_AddItem" }, { RpcCommand.RemoveDoneItem, "RPC_RemoveDoneItem" }, { RpcCommand.SetSlotVisual, "RPC_SetSlotVisual" }, { RpcCommand.AddFuelAmount, "RPC_AddFuelAmount" }, { RpcCommand.SetFuelAmount, "RPC_SetFuelAmount" }, { RpcCommand.ToggleOn, "RPC_ToggleOn" }, { RpcCommand.Pickup, "RPC_Pickup" }, { RpcCommand.RequestPickup, "RPC_RequestPickup" }, { RpcCommand.UseDoor, "RPC_UseDoor" }, { RpcCommand.Repair, "RPC_Repair" }, { RpcCommand.Remove, "RPC_Remove" }, { RpcCommand.HealthChanged, "RPC_HealthChanged" }, { RpcCommand.UpdateMaterial, "RPC_UpdateMaterial" }, { RpcCommand.SetAreaHealth, "RPC_SetAreaHealth" }, { RpcCommand.SetEvent, "RPC_SetEvent" }, { RpcCommand.BossSpawnInitiated, "RPC_BossSpawnInitiated" }, { RpcCommand.RemoveBossSpawnInventoryItems, "RPC_RemoveBossSpawnInventoryItems" }, { RpcCommand.SpawnBoss, "RPC_SpawnBoss" }, { RpcCommand.SetTamed, "RPC_SetTamed" }, { RpcCommand.ResetCloth, "RPC_ResetCloth" }, { RpcCommand.FreezeFrame, "RPC_FreezeFrame" }, { RpcCommand.OnHit, "RPC_OnHit" }, { RpcCommand.Attach, "RPC_Attach" }, { RpcCommand.TeleportTo, "RPC_TeleportTo" }, { RpcCommand.StaggerCreature, "RPC_Stagger" }, { RpcCommand.OnEat, "RPC_OnEat" }, { RpcCommand.TryEat, "RPC_TryEat" }, { RpcCommand.EatConfirmation, "RPC_EatConfirmation" }, { RpcCommand.Nibble, "RPC_Nibble" }, { RpcCommand.Step, "RPC_Step" }, { RpcCommand.Wakeup, "RPC_Wakeup" }, { RpcCommand.Grow, "RPC_Grow" }, { RpcCommand.Shake, "RPC_Shake" }, { RpcCommand.Command, "RPC_Command" }, { RpcCommand.UnSummon, "RPC_UnSummon" }, { RpcCommand.SetName, "RPC_SetName" }, { RpcCommand.Forward, "RPC_Forward" }, { RpcCommand.Backward, "RPC_Backward" }, { RpcCommand.Rudder, "RPC_Rudder" }, { RpcCommand.Stop, "RPC_Stop" }, { RpcCommand.AddSaddle, "RPC_AddSaddle" }, { RpcCommand.RemoveSaddle, "RPC_RemoveSaddle" }, { RpcCommand.SetSaddle, "RPC_SetSaddle" }, { RpcCommand.RequestControlShip, "RPC_RequestControl" }, { RpcCommand.ReleaseControlShip, "RPC_ReleaseControl" }, { RpcCommand.SetGlobalKey, "RPC_SetGlobalKey" }, { RpcCommand.RemoveGlobalKey, "RPC_RemoveGlobalKey" }, { RpcCommand.GlobalKeys, "RPC_GlobalKeys" }, { RpcCommand.LocationIcons, "RPC_LocationIcons" }, { RpcCommand.AddNoise, "RPC_AddNoise" } }; } public static class Strings { public static string[] ItemSpawns = new string[240] { "Amber", "AmberPearl", "AncientSeed", "Acorn", "BlackMetal", "BowHuntsman", "FineWood", "Flint", "Haldor", "Obsidian", "Silver", "SledgeStagbreaker", "TrollHide", "CarrotSeeds", "Coins", "DeerHide", "Iron", "Wood", "Coal", "Stone", "Copper", "Tin", "Bronze", "LeatherScraps", "Feathers", "Raspberries", "Blueberries", "Mushroom", "Cloudberry", "Carrot", "Turnip", "Onion", "Honey", "Meat", "CookedMeat", "Fish", "CookedFish", "Egg", "CookedEgg", "NeckTail", "CookedNeckTail", "BoarMeat", "CookedBoarMeat", "SerpentMeat", "CookedSerpentMeat", "LoxMeat", "CookedLoxMeat", "WolfMeat", "CookedWolfMeat", "Bread", "Stew", "MeadBase", "MeadHealthMinor", "MeadHealthMedium", "MeadStaminaMinor", "MeadStaminaMedium", "MeadStaminaMajor", "MeadFrostResist", "MeadPoisonResist", "MeadEitrMinor", "MeadEitrMedium", "MeadEitrMajor", "MeadTasty", "MeadLingeringStamina", "MeadColdResist", "MeadSoftTissue", "MeadHasty", "MeadHealingOverTime", "AxeFlint", "AxeBronze", "AxeIron", "AxeBlackMetal", "PickaxeStone", "PickaxeBronze", "PickaxeIron", "PickaxeBlackMetal", "Hammer", "Cultivator", "Hoe", "Torch", "SpearFlint", "SpearBronze", "SpearIron", "SpearBlackMetal", "Bow", "BowHuntsman", "BowDraugrFang", "BowFineWood", "StaffFireball", "StaffIceShards", "StaffShield", "StaffSkeleton", "SledgeIron", "SledgeStagbreaker", "ShieldWood", "ShieldWoodTower", "ShieldBronzeBuckler", "ShieldBanded", "ShieldSilver", "ShieldSerpent", "ShieldBlackmetal", "ShieldCarapace", "ShieldAspid", "ShieldOdin", "HelmetBronze", "HelmetIron", "HelmetLeather", "HelmetPadded", "HelmetTrollLeather", "HelmetWolf", "HelmetDrake", "HelmetDverger", "HelmetOdin", "HelmetYule", "HelmetHood", "CapeDeerHide", "CapeLinen", "CapeLox", "CapeOdin", "CapeTest", "CapeTrollHide", "CapeWolf", "ArmorBronzeChest", "ArmorBronzeLegs", "ArmorIronChest", "ArmorIronLegs", "ArmorLeatherChest", "ArmorLeatherLegs", "ArmorPaddedCuirass", "ArmorPaddedGreaves", "ArmorRagsChest", "ArmorRagsLegs", "ArmorTrollLeatherChest", "ArmorTrollLeatherLegs", "ArmorWolfChest", "ArmorWolfLegs", "ArmorDrakeChest", "ArmorDrakeLegs", "ArmorDvergerChest", "ArmorDvergerLegs", "ArmorAshlandsMediumChest", "ArmorAshlandsMediumLegs", "ArmorAshlandsHeavyChest", "ArmorAshlandsHeavyLegs", "ArmorCarapaceChest", "ArmorCarapaceLegs", "ArmorMageChest", "ArmorMageLegs", "ArmorFenringChest", "ArmorFenringLegs", "ArmorRootChest", "ArmorRootLegs", "ArmorYuleChest", "ArmorYuleLegs", "ArmorHildirChest", "ArmorHildirLegs", "ArmorCultistChest", "ArmorCultistLegs", "ArmorHareChest", "ArmorHareLegs", "ArmorChickenChest", "ArmorChickenLegs", "ArmorSeekerChest", "ArmorSeekerLegs", "ArmorSeekerBroodChest", "ArmorSeekerBroodLegs", "ArmorSeekerQueenChest", "ArmorSeekerQueenLegs", "ArmorEikthyrChest", "ArmorEikthyrLegs", "ArmorTheElderChest", "ArmorTheElderLegs", "ArmorBonemassChest", "ArmorBonemassLegs", "ArmorDragonChest", "ArmorDragonLegs", "ArmorGoblinKingChest", "ArmorGoblinKingLegs", "ArmorFaderChest", "ArmorFaderLegs", "ArmorSeekerChest", "ArmorSeekerLegs", "ArmorSeekerBroodChest", "ArmorSeekerBroodLegs", "ArmorSeekerQueenChest", "ArmorSeekerQueenLegs", "ArmorEikthyrChest", "ArmorEikthyrLegs", "ArmorTheElderChest", "ArmorTheElderLegs", "ArmorBonemassChest", "ArmorBonemassLegs", "ArmorDragonChest", "ArmorDragonLegs", "ArmorGoblinKingChest", "ArmorGoblinKingLegs", "ArmorFaderChest", "ArmorFaderLegs", "TrophyBoar", "TrophyDeer", "TrophyGreydwarf", "TrophyGreydwarfShaman", "TrophyGreydwarfBrute", "TrophyTroll", "TrophyDraugr", "TrophyDraugrElite", "TrophyBlob", "TrophyLeech", "TrophyWraith", "TrophySkeleton", "TrophySurtling", "TrophyNeck", "TrophyLox", "TrophySerpent", "TrophyWolf", "TrophyFenring", "TrophyCultist", "TrophyHare", "TrophyChicken", "TrophySeeker", "TrophySeekerBrood", "TrophySeekerQueen", "TrophyEikthyr", "TrophyTheElder", "TrophyBonemass", "TrophyDragon", "TrophyGoblinKing", "TrophyFader", "GoblinKing", "SeekerQueen", "Fader", "gd_king", "Bonemass", "Dragon", "Eikthyr", "TheElder", "Yagluth", "SeekerBrood", "Seeker", "SeekerQueen" }; public static string[] Spawns = new string[99] { "Abomination", "Asksvin", "Bat", "Blob", "BlobElite", "BlobTar", "BlobLava", "Boar", "Boar_piggy", "Charred_Archer", "Charred_Twitcher", "Charred_Mage", "Charred_Melee", "Chicken", "Hen", "Crow", "Deathsquito", "Deer", "Hatchling", "Draugr", "Draugr_Elite", "Draugr_Ranged", "Dverger", "DvergerMage", "DvergerMageFire", "DvergerMageIce", "DvergerMageSupport", "DvergerAshlands", "FallenValkyrie", "Fenring", "Fenring_Cultist", "Fenring_Cultist_Hildir", "Fish1", "Fish2", "Fish3", "Fish4_cave", "Fish5", "Fish6", "Fish7", "Fish8", "Fish9", "Fish10", "Fish11", "Fish12", "Goblin", "GoblinArcher", "GoblinBrute", "GoblinShaman", "Ghost", "Gjall", "Greydwarf", "Greydwarf_Elite", "Greydwarf_Shaman", "Greyling", "Hare", "Haldor", "Hildir", "Leech", "Leech_cave", "Leviathan", "Charred_Melee_Dyrnwyn", "Lox", "Lox_Calf", "Morgen", "Neck", "odin", "Seagal", "Seeker", "SeekerBrute", "SeekerBrood", "Serpent", "BonemawSerpent", "Skeleton", "Skeleton_NoArcher", "Skeleton_Poison", "Skeleton_Hildir", "piece_Charred_Balista", "StoneGolem", "Surtling", "TentaRoot", "Tick", "TrainingDummy", "Troll", "Ulv", "Volture", "Wisp", "Wolf", "Wolf_cub", "Wraith", "GoblinBruteBros", "GoblinBrute_Hildir", "GoblinShaman_Hildir", "Eikthyr", "gd_king", "Bonemass", "Dragon", "GoblinKing", "SeekerQueen", "Fader" }; public static string Optional(this int? value, string prefix) { if (!value.HasValue) { return string.Empty; } int? num = value; return prefix + " " + num; } } public enum Type { Whisper, Normal, Shout, Ping } public enum ValheimEvent { ArmyEikthyr, ArmyTheElder, ArmyBonemass, ArmyModer, ArmyGoblin, ArmyGoblinKing, ArmyGjall, ArmyFenring, ArmyHildir, Blobs, Wolves, Surtlings, Skeletons, ForestTrolls, Deathsquito, Bats, ArmySeekers, Eikthyr, GdKing, Bonemass, Dragon, GoblinKing, Queen } public static class ValheimEventNames { public static readonly Dictionary<ValheimEvent, string> Map = new Dictionary<ValheimEvent, string> { { ValheimEvent.ArmyEikthyr, "army_eikthyr" }, { ValheimEvent.ArmyTheElder, "army_theelder" }, { ValheimEvent.ArmyBonemass, "army_bonemass" }, { ValheimEvent.ArmyModer, "army_moder" }, { ValheimEvent.ArmyGoblin, "army_goblin" }, { ValheimEvent.ArmyGoblinKing, "army_goblinKing" }, { ValheimEvent.ArmyGjall, "army_gjall" }, { ValheimEvent.ArmyFenring, "army_fenring" }, { ValheimEvent.ArmyHildir, "army_hildir" }, { ValheimEvent.Blobs, "blobs" }, { ValheimEvent.Wolves, "wolves" }, { ValheimEvent.Surtlings, "surtlings" }, { ValheimEvent.Skeletons, "skeletons" }, { ValheimEvent.ForestTrolls, "foresttrolls" }, { ValheimEvent.Deathsquito, "deathsquito" }, { ValheimEvent.Bats, "bats" }, { ValheimEvent.ArmySeekers, "army_seekers" }, { ValheimEvent.Eikthyr, "Eikthyr" }, { ValheimEvent.GdKing, "gd_king" }, { ValheimEvent.Bonemass, "Bonemass" }, { ValheimEvent.Dragon, "Dragon" }, { ValheimEvent.GoblinKing, "GoblinKing" }, { ValheimEvent.Queen, "Queen" } }; public static string GetTitle(this ValheimEvent namedevent) { return Map[namedevent]; } } public static class ValheimStrings { public static string[] Commands = new string[37] { "devcommands", "god", "debugmode", "nocost", "heal", "raiseskill [skill] [amount]", "resetcharacter", "addstatus [effect]", "spawn [item] [amount] [level]", "tame", "killall", "tod [time]", "exploremap", "resetmap", "location", "kick [player]", "ban [player]", "unban [player]", "banned", "save", "resetworld", "event [name]", "stopevent", "randomevent", "sleep", "/help", "/info", "/ping", "/lodbias [0-5]", "/nomap", "/noportals", "/clear", "/resetbinds", "/resetplayerprefs", "/resetspawn", "/resetworldkeys", "/resetsharedmap" }; public static string[] ItemSpawns = new string[240] { "Amber", "AmberPearl", "AncientSeed", "Acorn", "BlackMetal", "BowHuntsman", "FineWood", "Flint", "Haldor", "Obsidian", "Silver", "SledgeStagbreaker", "TrollHide", "CarrotSeeds", "Coins", "DeerHide", "Iron", "Wood", "Coal", "Stone", "Copper", "Tin", "Bronze", "LeatherScraps", "Feathers", "Raspberries", "Blueberries", "Mushroom", "Cloudberry", "Carrot", "Turnip", "Onion", "Honey", "Meat", "CookedMeat", "Fish", "CookedFish", "Egg", "CookedEgg", "NeckTail", "CookedNeckTail", "BoarMeat", "CookedBoarMeat", "SerpentMeat", "CookedSerpentMeat", "LoxMeat", "CookedLoxMeat", "WolfMeat", "CookedWolfMeat", "Bread", "Stew", "MeadBase", "MeadHealthMinor", "MeadHealthMedium", "MeadStaminaMinor", "MeadStaminaMedium", "MeadStaminaMajor", "MeadFrostResist", "MeadPoisonResist", "MeadEitrMinor", "MeadEitrMedium", "MeadEitrMajor", "MeadTasty", "MeadLingeringStamina", "MeadColdResist", "MeadSoftTissue", "MeadHasty", "MeadHealingOverTime", "AxeFlint", "AxeBronze", "AxeIron", "AxeBlackMetal", "PickaxeStone", "PickaxeBronze", "PickaxeIron", "PickaxeBlackMetal", "Hammer", "Cultivator", "Hoe", "Torch", "SpearFlint", "SpearBronze", "SpearIron", "SpearBlackMetal", "Bow", "BowHuntsman", "BowDraugrFang", "BowFineWood", "StaffFireball", "StaffIceShards", "StaffShield", "StaffSkeleton", "SledgeIron", "SledgeStagbreaker", "ShieldWood", "ShieldWoodTower", "ShieldBronzeBuckler", "ShieldBanded", "ShieldSilver", "ShieldSerpent", "ShieldBlackmetal", "ShieldCarapace", "ShieldAspid", "ShieldOdin", "HelmetBronze", "HelmetIron", "HelmetLeather", "HelmetPadded", "HelmetTrollLeather", "HelmetWolf", "HelmetDrake", "HelmetDverger", "HelmetOdin", "HelmetYule", "HelmetHood", "CapeDeerHide", "CapeLinen", "CapeLox", "CapeOdin", "CapeTest", "CapeTrollHide", "CapeWolf", "ArmorBronzeChest", "ArmorBronzeLegs", "ArmorIronChest", "ArmorIronLegs", "ArmorLeatherChest", "ArmorLeatherLegs", "ArmorPaddedCuirass", "ArmorPaddedGreaves", "ArmorRagsChest", "ArmorRagsLegs", "ArmorTrollLeatherChest", "ArmorTrollLeatherLegs", "ArmorWolfChest", "ArmorWolfLegs", "ArmorDrakeChest", "ArmorDrakeLegs", "ArmorDvergerChest", "ArmorDvergerLegs", "ArmorAshlandsMediumChest", "ArmorAshlandsMediumLegs", "ArmorAshlandsHeavyChest", "ArmorAshlandsHeavyLegs", "ArmorCarapaceChest", "ArmorCarapaceLegs", "ArmorMageChest", "ArmorMageLegs", "ArmorFenringChest", "ArmorFenringLegs", "ArmorRootChest", "ArmorRootLegs", "ArmorYuleChest", "ArmorYuleLegs", "ArmorHildirChest", "ArmorHildirLegs", "ArmorCultistChest", "ArmorCultistLegs", "ArmorHareChest", "ArmorHareLegs", "ArmorChickenChest", "ArmorChickenLegs", "ArmorSeekerChest", "ArmorSeekerLegs", "ArmorSeekerBroodChest", "ArmorSeekerBroodLegs", "ArmorSeekerQueenChest", "ArmorSeekerQueenLegs", "ArmorEikthyrChest", "ArmorEikthyrLegs", "ArmorTheElderChest", "ArmorTheElderLegs", "ArmorBonemassChest", "ArmorBonemassLegs", "ArmorDragonChest", "ArmorDragonLegs", "ArmorGoblinKingChest", "ArmorGoblinKingLegs", "ArmorFaderChest", "ArmorFaderLegs", "ArmorSeekerChest", "ArmorSeekerLegs", "ArmorSeekerBroodChest", "ArmorSeekerBroodLegs", "ArmorSeekerQueenChest", "ArmorSeekerQueenLegs", "ArmorEikthyrChest", "ArmorEikthyrLegs", "ArmorTheElderChest", "ArmorTheElderLegs", "ArmorBonemassChest", "ArmorBonemassLegs", "ArmorDragonChest", "ArmorDragonLegs", "ArmorGoblinKingChest", "ArmorGoblinKingLegs", "ArmorFaderChest", "ArmorFaderLegs", "TrophyBoar", "TrophyDeer", "TrophyGreydwarf", "TrophyGreydwarfShaman", "TrophyGreydwarfBrute", "TrophyTroll", "TrophyDraugr", "TrophyDraugrElite", "TrophyBlob", "TrophyLeech", "TrophyWraith", "TrophySkeleton", "TrophySurtling", "TrophyNeck", "TrophyLox", "TrophySerpent", "TrophyWolf", "TrophyFenring", "TrophyCultist", "TrophyHare", "TrophyChicken", "TrophySeeker", "TrophySeekerBrood", "TrophySeekerQueen", "TrophyEikthyr", "TrophyTheElder", "TrophyBonemass", "TrophyDragon", "TrophyGoblinKing", "TrophyFader", "GoblinKing", "SeekerQueen", "Fader", "gd_king", "Bonemass", "Dragon", "Eikthyr", "TheElder", "Yagluth", "SeekerBrood", "Seeker", "SeekerQueen" }; public static string[] Spawns = new string[99] { "Abomination", "Asksvin", "Bat", "Blob", "BlobElite", "BlobTar", "BlobLava", "Boar", "Boar_piggy", "Charred_Archer", "Charred_Twitcher", "Charred_Mage", "Charred_Melee", "Chicken", "Hen", "Crow", "Deathsquito", "Deer", "Hatchling", "Draugr", "Draugr_Elite", "Draugr_Ranged", "Dverger", "DvergerMage", "DvergerMageFire", "DvergerMageIce", "DvergerMageSupport", "DvergerAshlands", "FallenValkyrie", "Fenring", "Fenring_Cultist", "Fenring_Cultist_Hildir", "Fish1", "Fish2", "Fish3", "Fish4_cave", "Fish5", "Fish6", "Fish7", "Fish8", "Fish9", "Fish10", "Fish11", "Fish12", "Goblin", "GoblinArcher", "GoblinBrute", "GoblinShaman", "Ghost", "Gjall", "Greydwarf", "Greydwarf_Elite", "Greydwarf_Shaman", "Greyling", "Hare", "Haldor", "Hildir", "Leech", "Leech_cave", "Leviathan", "Charred_Melee_Dyrnwyn", "Lox", "Lox_Calf", "Morgen", "Neck", "odin", "Seagal", "Seeker", "SeekerBrute", "SeekerBrood", "Serpent", "BonemawSerpent", "Skeleton", "Skeleton_NoArcher", "Skeleton_Poison", "Skeleton_Hildir", "piece_Charred_Balista", "StoneGolem", "Surtling", "TentaRoot", "Tick", "TrainingDummy", "Troll", "Ulv", "Volture", "Wisp", "Wolf", "Wolf_cub", "Wraith", "GoblinBruteBros", "GoblinBrute_Hildir", "GoblinShaman_Hildir", "Eikthyr", "gd_king", "Bonemass", "Dragon", "GoblinKing", "SeekerQueen", "Fader" }; } } namespace PolyhydraGames.Valheim.Core.Transport { public class PostResponse { public bool Success { get; set; } public string Command { get; set; } public string Message { get; set; } public string Data { get; set; } public string DataType { get; set; } } public static class RestExtensions { public static RestResult ToResult(this PostResponse response) { return new RestResult(response.Success, response.Command, response.Message); } public static RestResult<T> ToResult<T>(this PostResponse response) { T result = response.Data.FromJson<T>(); return new RestResult<T>(response.Success, response.Command, response.Message, result); } public static RestResult<T> ToResult<T>(this Exception ex, string method) { return new RestResult<T>(Success: false, method, ex.Message); } public static RestResult ToResult(this Exception ex, string method) { return new RestResult(Success: false, method, ex.Message); } } public record RestResult<T> : RestResult { public T? Result { get; init; } public RestResult(bool Success, string Command, string Message, T? Result = default(T?)) { this.Result = Result; base..ctor(Success, Command, Message); } [CompilerGenerated] public void Deconstruct(out bool Success, out string Command, out string Message, out T? Result) { Success = base.Success; Command = base.Command; Message = base.Message; Result = this.Result; } } public record RestResult(bool Success, string Command, string Message); } namespace PolyhydraGames.Valheim.Core.Requests { public record AddEffectRequest(string TargetPlayer, string EffectName) : IPlayerRequest { public override string ToString() { return TargetPlayer + " " + EffectName; } } public record AddNoiseRequest(string TargetPlayer, string Noise, Vector3Dto Position) : IPlayerRequest; public record DamageRequest(string TargetPlayer, int Amount) : IPlayerRequest; public record FindRequest(Vector3Dto Position, float Radius, string Prefab = null, string CreatorId = null, string UserId = null, string Tag = null); public record GiveRequest(string TargetPlayer, string ItemName, int Quality, int Count) : IPlayerRequest; public record GlobalKeyRequest(string Name, string Value); public record MessageRequest(string TargetPlayer, string SenderName, string Message, Type Proximity) : IPlayerRequest; public static class Message { public static MessageRequest Say(string TargetPlayer, string SenderName, string Message) { return new MessageRequest(TargetPlayer, SenderName, Message, Type.Normal); } } public record PlayerAmountRequest(string TargetPlayer, int Amount) : IPlayerRequest; public record PlayerRequest(string TargetPlayer) : IPlayerRequest; public record RaidRequest(ValheimEvent Event, Vector3Dto Position) { public string Name { get; } = Event.GetTitle(); } public record SendCommandRequest(string Command); public record SetWindRequest(float Angle, float Intensity); public record ShakeRequest(string TargetPlayer, float Intensity) : IPlayerRequest; public record TimeResponse(int Day, double Seconds); public record SpawnRequest(string PrefabName, Vector3Dto Position, int Count = 1, float Radius = 0f, int Level = 1, Vector3Dto Rotation = null, string Tag = "", bool Tamed = false); public record TeleportRequest(string TargetPlayer, Vector3Dto Position) : IPlayerRequest; } namespace PolyhydraGames.Valheim.Core.Models { public sealed record CommandInfo(string Command, string Description, string Usage); public class CommandRequestType { public string Command { get; set; } public string Raw { get; set; } public override string ToString() { return Command + ": " + Raw; } } public record EnabledState(string Name, bool Enabled); public record EventResponse(string Active, string Random); public record GameTime(string Seconds, int Day); public record GiveResponse(string ItemName, int Count, string PlayerName, Vector3Dto Position); public record PlayerInfoResponse(string User, string SteamId, string Name, bool IsDead, Vector3Dto Position, Vector2iDto Zone, float? Health, float? MaxHealth); public record PlayerResponse(string PlayerId, string PlayerName, Vector3Dto Position, Vector2iDto RefPosition); public record ServerStats(string WorldName, int Players, double Fps, long MonoMemory, long HeapMemory, int Day, int Objects, int DeadObjects); public record WorldObject(string Prefab, double Distance, int Id, ulong UserId, Vector3Dto Position, Vector3Dto Rotation, ulong Creator, int Health, double Support); public record ZdoSummary(string Type, Vector3Dto Position, Quaterion Quaterion, bool Tamed, string Tag); } namespace PolyhydraGames.Valheim.Core.Fascade { public record Quaterion(float X, float Y, float Z, float W); public record Vector2iDto(int X, int Y); public record Vector3Dto(float X, float Y, float Z, int? a = null, int? b = null); }