Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of ALIVE Admin v0.61.0
plugins/ALIVE.Client.Admin.dll
Decompiled 3 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Net.Sockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using ALIVE.Core; using ALIVE.Core.Abstractions; using ALIVE.Core.Assets; using ALIVE.Core.Client; using ALIVE.Core.Client.Editing; using ALIVE.Core.Content.Creatures; using ALIVE.Core.Content.Ids; using ALIVE.Core.Content.Mods; using ALIVE.Core.Content.Npcs; using ALIVE.Core.Diagnostics; using ALIVE.Core.Life; using ALIVE.Core.Places; using ALIVE.Core.Protocol; using ALIVE.Core.Protocol.Messages; using ALIVE.Core.Storage; using ALIVE.Core.Web; using ALIVE.Server.Util; using ALIVE.Server.World; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Managers; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.Rendering; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Valheim ALIVE")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.61.0.0")] [assembly: AssemblyInformationalVersion("0.61.0")] [assembly: AssemblyProduct("Valheim ALIVE")] [assembly: AssemblyTitle("ALIVE.Client.Admin")] [assembly: AssemblyVersion("0.61.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ALIVE.Server.Util { public sealed class PngWriter : IDisposable { private sealed class ChunkStream : Stream { private const int ChunkBytes = 65536; private readonly Stream _output; private readonly byte[] _buffer = new byte[65536]; private int _count; public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } internal ChunkStream(Stream output) { _output = output; } public override void Write(byte[] buffer, int offset, int count) { checked { while (count > 0) { int num = Math.Min(count, 65536 - _count); Array.Copy(buffer, offset, _buffer, _count, num); _count += num; offset += num; count -= num; if (_count == 65536) { Emit(); } } } } public override void WriteByte(byte value) { _buffer[checked(_count++)] = value; if (_count == 65536) { Emit(); } } public override void Flush() { if (_count > 0) { Emit(); } } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } private void Emit() { WriteChunk(_output, "IDAT", _buffer, _count); _count = 0; } } private static readonly byte[] Signature = new byte[8] { 137, 80, 78, 71, 13, 10, 26, 10 }; private static readonly uint[] CrcTable = MakeCrcTable(); private readonly Stream _output; private readonly int _width; private readonly int _height; private readonly ChunkStream _chunks; private readonly Stream _deflate; private readonly bool _stored; private readonly byte[] _line; private readonly byte[] _previous; private uint _adlerA = 1u; private uint _adlerB; private int _rows; private bool _finished; public bool Stored => _stored; public PngWriter(Stream output, int width, int height, bool compress = true) { if (width < 1 || height < 1 || width > 16384 || height > 16384) { throw new ArgumentOutOfRangeException("width", "A picture is 1 to 16,384 points on a side."); } _output = output ?? throw new ArgumentNullException("output"); _width = width; _height = height; checked { _line = new byte[1 + width * 3]; _previous = new byte[width * 3]; _output.Write(Signature, 0, Signature.Length); byte[] array = new byte[13]; BigEndian(array, 0, (uint)width); BigEndian(array, 4, (uint)height); array[8] = 8; array[9] = 2; array[10] = 0; array[11] = 0; array[12] = 0; WriteChunk(_output, "IHDR", array, array.Length); _chunks = new ChunkStream(_output); _chunks.WriteByte(120); _chunks.WriteByte(1); Stream stream = null; if (compress) { try { stream = new DeflateStream(_chunks, CompressionLevel.Fastest, leaveOpen: true); } catch (Exception ex) when (ex is DllNotFoundException || ex is TypeInitializationException || ex is EntryPointNotFoundException || ex is NotSupportedException || ex is PlatformNotSupportedException) { stream = null; } } _stored = stream == null; _deflate = stream ?? _chunks; } } public void WriteRow(byte[] rgb) { if (rgb == null) { throw new ArgumentNullException("rgb"); } checked { if (rgb.Length < _width * 3) { throw new ArgumentException("A row is three bytes for each point.", "rgb"); } if (_finished || _rows >= _height) { throw new InvalidOperationException("The picture already has all its rows."); } _line[0] = 2; for (int i = 0; i < _width * 3; i++) { _line[i + 1] = unchecked((byte)(rgb[i] - _previous[i])); _previous[i] = rgb[i]; } Adler(_line, _line.Length); if (_stored) { StoredBlock(_line, _rows == _height - 1); } else { _deflate.Write(_line, 0, _line.Length); } _rows++; } } public void Finish() { if (!_finished) { if (_rows != _height) { throw new InvalidOperationException("The picture has " + _rows + " of its " + _height + " rows."); } _finished = true; if (!_stored) { _deflate.Dispose(); } byte[] array = new byte[4]; BigEndian(array, 0, (_adlerB << 16) | _adlerA); _chunks.Write(array, 0, 4); _chunks.Flush(); WriteChunk(_output, "IEND", Array.Empty<byte>(), 0); _output.Flush(); } } public void Dispose() { if (!_stored && !_finished) { _deflate.Dispose(); } } public static uint Crc(byte[] data, int count) { uint num = uint.MaxValue; for (int i = 0; i < count; i = checked(i + 1)) { num = CrcTable[(num ^ data[i]) & 0xFF] ^ (num >> 8); } return num ^ 0xFFFFFFFFu; } private void StoredBlock(byte[] data, bool last) { checked { int num; for (int i = 0; i < data.Length; i += num) { num = Math.Min(65535, data.Length - i); bool flag = last && i + num == data.Length; _chunks.WriteByte(flag ? ((byte)1) : ((byte)0)); _chunks.WriteByte((byte)(num & 0xFF)); _chunks.WriteByte((byte)(num >> 8)); _chunks.WriteByte((byte)(~num & 0xFF)); _chunks.WriteByte((byte)((~num >> 8) & 0xFF)); _chunks.Write(data, i, num); } } } private void Adler(byte[] data, int count) { for (int i = 0; i < count; i = checked(i + 1)) { _adlerA = checked(_adlerA + data[i]) % 65521; _adlerB = checked(_adlerB + _adlerA) % 65521; } } private static void WriteChunk(Stream output, string type, byte[] data, int count) { byte[] array = new byte[8]; checked { BigEndian(array, 0, (uint)count); for (int i = 0; i < 4; i++) { array[4 + i] = (byte)type[i]; } byte[] array2 = new byte[4 + count]; Array.Copy(array, 4, array2, 0, 4); Array.Copy(data, 0, array2, 4, count); byte[] array3 = new byte[4]; BigEndian(array3, 0, Crc(array2, array2.Length)); output.Write(array, 0, 8); output.Write(data, 0, count); output.Write(array3, 0, 4); } } private static void BigEndian(byte[] into, int at, uint value) { into[at] = (byte)(value >> 24); into[checked(at + 1)] = (byte)(value >> 16); into[checked(at + 2)] = (byte)(value >> 8); into[checked(at + 3)] = (byte)value; } private static uint[] MakeCrcTable() { uint[] array = new uint[256]; checked { for (uint num = 0u; num < 256; num++) { uint num2 = num; for (int i = 0; i < 8; i++) { num2 = (((num2 & 1) != 0) ? (0xEDB88320u ^ (num2 >> 1)) : (num2 >> 1)); } array[num] = num2; } return array; } } } } namespace ALIVE.Server.World { public readonly struct MapSample { public int Biome { get; } public float Height { get; } public bool Forest { get; } public MapSample(int biome, float height, bool forest) { Biome = biome; Height = height; Forest = forest; } } public static class WorldMapPainter { public const float SeaLevel = 30f; private static readonly byte[] Outside = new byte[3] { 6, 9, 11 }; public static bool Paint(Stream output, int size, double radius, Func<double, double, MapSample> sample, Action<double>? progress, Func<bool>? stop) { if (output == null) { throw new ArgumentNullException("output"); } if (sample == null) { throw new ArgumentNullException("sample"); } if (size < 2 || size > 8192) { throw new ArgumentOutOfRangeException("size"); } if (radius <= 0.0) { throw new ArgumentOutOfRangeException("radius"); } double num = radius * 2.0 / (double)size; float[] array = new float[size]; float[] array2 = new float[size]; checked { byte[] array3 = new byte[size * 3]; using (PngWriter pngWriter = new PngWriter(output, size, size)) { for (int i = 0; i < size; i++) { if (stop != null && stop()) { return false; } double num2 = radius - ((double)i + 0.5) * num; for (int j = 0; j < size; j++) { double num3 = 0.0 - radius + ((double)j + 0.5) * num; int num4 = j * 3; if (num3 * num3 + num2 * num2 > radius * radius) { array2[j] = -20f; array3[num4] = Outside[0]; array3[num4 + 1] = Outside[1]; array3[num4 + 2] = Outside[2]; continue; } MapSample s = sample(num3, num2); float num5 = (array2[j] = ((float.IsNaN(s.Height) || float.IsInfinity(s.Height)) ? 30f : s.Height)); float num6 = ((j > 0) ? array2[j - 1] : num5); float num7 = ((i > 0) ? array[j] : num5); Colour(s, num5, num5 - num6 + (num5 - num7), out var red, out var green, out var blue); array3[num4] = red; array3[num4 + 1] = green; array3[num4 + 2] = blue; } pngWriter.WriteRow(array3); float[] array4 = array; array = array2; array2 = array4; if ((i & 0x3F) == 0) { progress?.Invoke((double)i / (double)size); } } pngWriter.Finish(); } progress?.Invoke(1.0); return true; } } public static void Colour(MapSample s, float h, float rise, out byte red, out byte green, out byte blue) { float v; float v2; float v3; if (h < 30f) { float t = Math.Min(1f, (30f - h) / 40f); v = Mix(0.34f, 0.07f, t); v2 = Mix(0.58f, 0.17f, t); v3 = Mix(0.7f, 0.29f, t); } else { switch (s.Biome) { case 1: v = 0.57f; v2 = 0.66f; v3 = 0.36f; break; case 2: v = 0.55f; v2 = 0.42f; v3 = 0.33f; break; case 4: v = 0.93f; v2 = 0.94f; v3 = 0.96f; break; case 8: v = 0.36f; v2 = 0.42f; v3 = 0.24f; break; case 16: v = 0.86f; v2 = 0.78f; v3 = 0.47f; break; case 32: v = 0.62f; v2 = 0.2f; v3 = 0.15f; break; case 64: v = 0.86f; v2 = 0.91f; v3 = 0.97f; break; case 512: v = 0.36f; v2 = 0.33f; v3 = 0.38f; break; default: v = 0.6f; v2 = 0.6f; v3 = 0.55f; break; } if (s.Forest && s.Biome != 4 && s.Biome != 64) { v *= 0.82f; v2 *= 0.86f; v3 *= 0.8f; } if (h < 31.2f && s.Biome != 4) { v = Mix(v, 0.8f, 0.5f); v2 = Mix(v2, 0.74f, 0.5f); v3 = Mix(v3, 0.56f, 0.5f); } float num = 1f + Math.Max(-0.38f, Math.Min(0.38f, rise * 0.045f)); v *= num; v2 *= num; v3 *= num; } red = Byte(v); green = Byte(v2); blue = Byte(v3); } private static float Mix(float a, float b, float t) { return a + (b - a) * t; } private static byte Byte(float v) { return checked((byte)Math.Max(0, Math.Min(255, (int)(v * 255f + 0.5f)))); } } } namespace ALIVE.Client { [BepInPlugin("com.imaginaryrealms.alive.client.admin", "ALIVE Admin", "0.61.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInIncompatibility("com.imaginaryrealms.alive.client.player")] [BepInIncompatibility("net.winterwolf.alive.client.player")] [BepInIncompatibility("net.winterwolf.alive.client.admin")] public sealed class AliveAdminPlugin : BaseUnityPlugin { private ClientHost? _host; private void Awake() { //IL_0187: Unknown result type (might be due to invalid IL or missing references) SettingsFile.Carry(((BaseUnityPlugin)this).Config, "net.winterwolf.alive.client.admin", "com.imaginaryrealms.alive.client.admin", ((BaseUnityPlugin)this).Logger); if (SettingsFile.BesideOldCopy("ALIVE Admin", ((BaseUnityPlugin)this).Logger)) { return; } AliveInput.Register((BaseUnityPlugin)(object)this, "com.imaginaryrealms.alive.client.admin", admin: true); ConsolePrefs.Bind(((BaseUnityPlugin)this).Config); ConfigEntry<bool> val = ((BaseUnityPlugin)this).Config.Bind<bool>("Quests", "ShowTracker", true, "Show the quest list on screen while you play."); ConfigEntry<float> trackerX = ((BaseUnityPlugin)this).Config.Bind<float>("Quests", "TrackerCenterX", 0.9f, "Where the tracker's centre sits, as a fraction of the screen's width from the left. Drag the tracker and this updates itself."); ConfigEntry<float> trackerY = ((BaseUnityPlugin)this).Config.Bind<float>("Quests", "TrackerCenterY", 0.6f, "Where the tracker's centre sits, as a fraction of the screen's height from the bottom. Drag the tracker and this updates itself."); ConfigEntry<float> val2 = ((BaseUnityPlugin)this).Config.Bind<float>("Quests", "TrackerScale", 1f, "How big the tracker is, between 0.75 and 1.5."); ConfigEntry<bool> val3 = ((BaseUnityPlugin)this).Config.Bind<bool>("Quests", "Sounds", true, "Play a sound when a quest is accepted, finished or lost."); ConfigEntry<float> val4 = ((BaseUnityPlugin)this).Config.Bind<float>("Quests", "SoundVolume", 0.5f, "How loud those sounds are, between 0 and 1."); ConfigEntry<bool> fromBank = ((BaseUnityPlugin)this).Config.Bind<bool>("Shops", "PayFromBank", false, "Pay shop prices in a banked currency (Coins and the like) from your bank rather than with what you carry. Also switched from the shop window; a shop can refuse it."); _host = ClientHost.Start((ClientRole)2, "com.imaginaryrealms.alive.client.admin", ((BaseUnityPlugin)this).Info.Location, ((BaseUnityPlugin)this).Logger); if (_host != null) { _host.TrackerEnabled = val.Value; _host.TrackerCenter = new Vector2(trackerX.Value, trackerY.Value); _host.TrackerScale = val2.Value; _host.SoundEnabled = val3.Value; _host.SoundVolume = val4.Value; _host.PayFromBank = fromBank.Value; _host.PayFromBankChanged = delegate(bool on) { fromBank.Value = on; }; _host.TrackerMoved = delegate(Vector2 anchor) { //IL_0006: 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) trackerX.Value = anchor.x; trackerY.Value = anchor.y; }; } } private void OnApplicationQuit() { _host?.Dispose(); _host = null; } } internal sealed class AdminConsole { private const int WindowId = 41247; private readonly AdminClient _admin; private readonly ShopEditorView _shops; private readonly ConsolePopups _popups = new ConsolePopups(41257); private static readonly Vector2 MinSize = new Vector2(640f, 420f); private static readonly float[] Presets = new float[5] { 1f, 1.25f, 1.5f, 1.75f, 2f }; private Rect _screen; private bool _placed; private float _scale = 1f; private int _gripControl; private Vector2 _gripFrom; private Vector2 _sizeFrom; private Texture2D? _background; private GUIStyle? _window; private Vector2 _scroll; private bool _openOnly; private ulong _confirmComplete; private ulong _confirmWipe; private string _giveFlag = string.Empty; private const string FlagBox = "alive_give_flag"; private const string CounterBox = "alive_set_counter"; private (string Control, string Value) _pendingName = (Control: string.Empty, Value: string.Empty); private string _activeNameBox = string.Empty; private string _openNameList = string.Empty; private string _lastTyped = string.Empty; private Vector2 _nameListScroll; private readonly Dictionary<string, NameRows> _nameRows = new Dictionary<string, NameRows>(StringComparer.Ordinal); private string _counterName = string.Empty; private string _counterValue = string.Empty; private uint _logCategories; private LogSearchItem? _detail; private Rect _detailRect; private Vector2 _detailScroll; private Action? _leave; private string _leaveWhat = string.Empty; private bool _leavePublishing; private bool _superAdmin; private string _hammerNote = string.Empty; private string _npcLabel = string.Empty; private string _spawnerLabel = string.Empty; private bool _confirmRemoveCreatures; private string _storyFlag = string.Empty; private bool _confirmClearAll; private string _storySwitch = string.Empty; private string _picturesAsked = string.Empty; private float _openedAt = -1f; private bool _drawnSinceOpened = true; private static GUIStyle? _tipStyle; private float _keptUpAt; private string _flagFind = string.Empty; private static readonly int[] LogSizes = new int[3] { 25, 50, 100 }; private DebugArea _serverAreas = (DebugArea)127; private DebugArea _gameAreas = (DebugArea)127; private bool _serverAreasRead; private string _serverNote = string.Empty; private string _gameNote = string.Empty; private string _gameSaid = string.Empty; internal bool Visible { get; private set; } internal Action<string, string>? PlaceWithTool { get; set; } internal Action? OpenEditor { get; set; } internal Action? StopEditor { get; set; } internal Func<string>? EditorLine { get; set; } internal Action<ulong, string>? MoveWithTool { get; set; } internal Func<string>? GiveHammer { get; set; } internal Action<string>? SpawnWithTool { get; set; } internal Action<string, string>? PlaceSpawnerWithTool { get; set; } internal Action<ulong, string>? MoveSpawnerWithTool { get; set; } internal AdminConsole(AdminClient admin) { //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) _admin = admin; _shops = new ShopEditorView(admin) { Popups = _popups }; _admin.Editor.AfterDelete = delegate { _admin.RefreshNpcs(); }; _shops.GoTo = delegate(EditorPage page) { //IL_000b: 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) //IL_000f: 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) Go((AdminTab)(page switch { EditorPage.Stories => 5, EditorPage.Npcs => 7, _ => 4, })); }; _shops.GuardWith = Guard; _admin.PicturesWanted = AskedForPictures; } private void AskedForPictures(IReadOnlyList<byte> kinds) { PictureRun pictures = _admin.Pictures; bool all; if (!pictures.Busy) { all = kinds.Count == 0; pictures.Creatures = Has(1) || Has(2); pictures.Items = Has(3); pictures.Pieces = Has(4); pictures.Objects = Has(5); List<string> list = new List<string>(); if (pictures.Creatures) { list.Add("creatures"); } if (pictures.Items) { list.Add("items"); } if (pictures.Pieces) { list.Add("building pieces"); } if (pictures.Objects) { list.Add("objects"); } _picturesAsked = "The browser editor asks for pictures of " + ((list.Count == 0) ? "everything" : string.Join(", ", list)) + ". It takes a few minutes; you can keep playing."; Visible = true; Go((AdminTab)8); } bool Has(byte k) { if (!all) { return kinds.Contains(k); } return true; } } internal void Toggle() { if (Visible) { Hide(); return; } Visible = true; _openedAt = Time.unscaledTime; _drawnSinceOpened = false; if (_admin.Players.Count == 0) { _admin.RefreshPlayers(); } } internal string Where() { //IL_00a3: 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) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) string text = Screen.width.ToString(CultureInfo.InvariantCulture) + "×" + Screen.height.ToString(CultureInfo.InvariantCulture); if (!_placed) { Rect? val = ConsolePrefs.Window(); if (val.HasValue) { Rect valueOrDefault = val.GetValueOrDefault(); return "its window as it was left, " + Size(valueOrDefault) + ", on a " + text + " screen"; } return "its window in the middle of a " + text + " screen"; } return "its window " + Size(_screen) + " on a " + text + " screen"; } private static string Size(Rect r) { return checked(((int)((Rect)(ref r)).width).ToString(CultureInfo.InvariantCulture) + "×" + ((int)((Rect)(ref r)).height).ToString(CultureInfo.InvariantCulture) + " at " + ((int)((Rect)(ref r)).x).ToString(CultureInfo.InvariantCulture) + "," + ((int)((Rect)(ref r)).y).ToString(CultureInfo.InvariantCulture)); } internal bool ClosePopup() { if (Visible) { if (!_shops.CloseTreePopup()) { return _popups.CloseTop(); } return true; } return false; } internal void Hide() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (Visible) { if (_placed) { ConsolePrefs.SaveWindow(_screen); } Visible = false; GUIUtility.keyboardControl = 0; } } internal void OnSessionReady(bool superAdmin) { _superAdmin = superAdmin; if (Visible) { _admin.RefreshPlayers(); } if (superAdmin) { _admin.CountWaiting(); } } internal void OnSuperAdminChanged(bool superAdmin) { if (_superAdmin != superAdmin) { _superAdmin = superAdmin; if (superAdmin) { _admin.CountWaiting(); } } } internal void Draw() { //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Expected O, but got Unknown //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_0321: Unknown result type (might be due to invalid IL or missing references) //IL_0333: Unknown result type (might be due to invalid IL or missing references) //IL_0339: Invalid comparison between Unknown and I4 //IL_02f2: Unknown result type (might be due to invalid IL or missing references) //IL_02fb: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_0320: Expected O, but got Unknown //IL_031b: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Expected O, but got Unknown //IL_029c: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) if (!Visible) { return; } Place(); if (!_drawnSinceOpened) { _drawnSinceOpened = true; float num = Time.unscaledTime - _openedAt; if (num >= 0.5f) { IAliveLog? log = AliveProps.Log; if (log != null) { log.Info("ALIVE: the admin console was drawn " + num.ToString("0.0", CultureInfo.InvariantCulture) + " s after its key opened it; " + Where() + "."); } } } KeepUp(); float num2 = (ConsolePrefs.GrowWithWindow ? Mathf.Clamp(Mathf.Min(((Rect)(ref _screen)).width / ConsolePrefs.BaseSize.x, ((Rect)(ref _screen)).height / ConsolePrefs.BaseSize.y), 0.6f, 3f) : 1f); _scale = Mathf.Clamp(ConsolePrefs.TextScale * num2, 0.5f, 4f); GUISkin val = RuneSkin.Prepare(); GUISkin skin = GUI.skin; Matrix4x4 matrix = GUI.matrix; if ((Object)(object)val != (Object)null) { GUI.skin = val; } GUI.matrix = Matrix4x4.Scale(new Vector3(_scale, _scale, 1f)); GUI.depth = 0; Rect val2 = default(Rect); ((Rect)(ref val2))..ctor(((Rect)(ref _screen)).x / _scale, ((Rect)(ref _screen)).y / _scale, ((Rect)(ref _screen)).width / _scale, ((Rect)(ref _screen)).height / _scale); Rect val3 = GUI.Window(41247, val2, new WindowFunction(DrawWindow), "ALIVE · ADMIN", ((Object)(object)val != (Object)null) ? RuneSkin.Window : Style()); _popups.Windows(val2); if (_gripControl == 0 || GUIUtility.hotControl != _gripControl) { ((Rect)(ref _screen)).x = ((Rect)(ref val3)).x * _scale; ((Rect)(ref _screen)).y = ((Rect)(ref val3)).y * _scale; } if (_detail != null) { if (((Rect)(ref _detailRect)).width <= 0f) { _detailRect = new Rect(((Rect)(ref val2)).x + ((Rect)(ref val2)).width - 560f, ((Rect)(ref val2)).y + 60f, 540f, 520f); } _detailRect = GUI.Window(41249, _detailRect, new WindowFunction(DrawDetail), "EVENT", ((Object)(object)val != (Object)null) ? RuneSkin.Window : Style()); } FollowPublish(); if (_leave != null) { Rect val4 = default(Rect); ((Rect)(ref val4))..ctor(((Rect)(ref val2)).x + (((Rect)(ref val2)).width - 560f) / 2f, ((Rect)(ref val2)).y + 140f, 560f, 230f); GUI.ModalWindow(41248, val4, new WindowFunction(DrawLeave), "UNPUBLISHED CHANGES", ((Object)(object)val != (Object)null) ? RuneSkin.Window : Style()); } GUI.matrix = matrix; GUI.skin = skin; if ((int)_admin.Tab == 5) { _shops.DrawTreeWindow(); } } private void Place() { //IL_006d: 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) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) if (!_placed) { _placed = true; Rect? val = ConsolePrefs.Window(); _screen = (Rect)(((??)val) ?? new Rect(0f, 0f, Mathf.Min(ConsolePrefs.BaseSize.x, (float)Screen.width - 40f), Mathf.Min(ConsolePrefs.BaseSize.y, (float)Screen.height - 40f))); if (!val.HasValue) { ((Rect)(ref _screen)).center = new Vector2((float)Screen.width / 2f, (float)Screen.height / 2f); } } ((Rect)(ref _screen)).width = Mathf.Clamp(((Rect)(ref _screen)).width, Mathf.Min(MinSize.x, (float)Screen.width), (float)Screen.width); ((Rect)(ref _screen)).height = Mathf.Clamp(((Rect)(ref _screen)).height, Mathf.Min(MinSize.y, (float)Screen.height), (float)Screen.height); ((Rect)(ref _screen)).x = Mathf.Clamp(((Rect)(ref _screen)).x, 0f, Mathf.Max(0f, (float)Screen.width - ((Rect)(ref _screen)).width)); ((Rect)(ref _screen)).y = Mathf.Clamp(((Rect)(ref _screen)).y, 0f, Mathf.Max(0f, (float)Screen.height - ((Rect)(ref _screen)).height)); } private void ResetWindow() { ConsolePrefs.ForgetWindow(); _placed = false; Place(); } private GUIStyle Style() { //IL_0022: 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_0034: Expected O, but got Unknown //IL_0050: 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_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown //IL_008d: Expected O, but got Unknown //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) if (_window != null && (Object)(object)_background != (Object)null) { return _window; } _background = new Texture2D(1, 1, (TextureFormat)4, false) { hideFlags = (HideFlags)61 }; _background.SetPixel(0, 0, new Color(0.07f, 0.07f, 0.08f, 0.97f)); _background.Apply(); _window = new GUIStyle(GUI.skin.window) { padding = new RectOffset(12, 12, 24, 16) }; _window.normal.background = _background; _window.onNormal.background = _background; _window.normal.textColor = Color.white; _window.onNormal.textColor = Color.white; return _window; } private static void Tip(float width, float height) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0039: 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_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Expected O, but got Unknown //IL_0054: Expected O, but got Unknown //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) string tooltip = GUI.tooltip; if (!string.IsNullOrEmpty(tooltip) && (int)Event.current.type == 7) { if (_tipStyle == null) { _tipStyle = new GUIStyle(GUI.skin.box) { wordWrap = true, alignment = (TextAnchor)0, padding = new RectOffset(8, 8, 6, 6) }; } float num = Mathf.Min(380f, width - 12f); float num2 = _tipStyle.CalcHeight(new GUIContent(tooltip), num); Vector2 mousePosition = Event.current.mousePosition; float num3 = Mathf.Clamp(mousePosition.x + 14f, 6f, Mathf.Max(6f, width - num - 6f)); float num4 = ((mousePosition.y + 22f + num2 > height - 6f) ? Mathf.Max(6f, mousePosition.y - num2 - 10f) : (mousePosition.y + 22f)); GUI.Box(new Rect(num3, num4, num, num2), tooltip, _tipStyle); } } private void DrawWindow(int id) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) GUISkin current = RuneSkin.Current; GUISkin skin = GUI.skin; if ((Object)(object)current != (Object)null) { GUI.skin = current; } float num = ((Rect)(ref _screen)).width / _scale; float num2 = ((Rect)(ref _screen)).height / _scale; try { _popups.Begin(num, num2); Rect val = default(Rect); ((Rect)(ref val))..ctor(num - 20f, num2 - 20f, 18f, 18f); Grip(val); if (GUI.Button(new Rect(num - 42f, 7f, 30f, 22f), "✕")) { Hide(); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); Rail(); GUILayout.Space(14f); GUILayout.BeginVertical(Array.Empty<GUILayoutOption>()); Page(); GUILayout.EndVertical(); GUILayout.EndHorizontal(); Texture2D grip = RuneSkin.Grip; if ((Object)(object)grip != (Object)null && (Object)(object)RuneSkin.Current != (Object)null) { GUI.DrawTexture(val, (Texture)(object)grip); } else { GUI.Label(val, "◢"); } Tip(num, num2); _popups.End(); } finally { GUI.skin = skin; } GUI.DragWindow(new Rect(0f, 0f, 10000f, 32f)); } private void Grip(Rect rect) { //IL_001b: 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_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected I4, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) int controlID = GUIUtility.GetControlID((FocusType)2); Event current = Event.current; Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(((Rect)(ref _screen)).x + current.mousePosition.x * _scale, ((Rect)(ref _screen)).y + current.mousePosition.y * _scale); EventType typeForControl = current.GetTypeForControl(controlID); switch ((int)typeForControl) { case 0: if (current.button == 0 && ((Rect)(ref rect)).Contains(current.mousePosition)) { GUIUtility.hotControl = controlID; _gripControl = controlID; _gripFrom = val; _sizeFrom = new Vector2(((Rect)(ref _screen)).width, ((Rect)(ref _screen)).height); current.Use(); } break; case 3: if (GUIUtility.hotControl == controlID) { ((Rect)(ref _screen)).width = Mathf.Max(MinSize.x, _sizeFrom.x + (val.x - _gripFrom.x)); ((Rect)(ref _screen)).height = Mathf.Max(MinSize.y, _sizeFrom.y + (val.y - _gripFrom.y)); current.Use(); } break; case 1: if (GUIUtility.hotControl == controlID) { GUIUtility.hotControl = 0; _gripControl = 0; ConsolePrefs.SaveWindow(_screen); current.Use(); } break; case 2: break; } } private void Rail() { //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); GUILayout.Space(4f); NavTo("Players", (AdminTab)0, delegate { _admin.RefreshPlayers(); }); NavTo("Quests", (AdminTab)1, delegate { _admin.RefreshQuests(_admin.QuestPlayer, _openOnly); }); NavTo("Activity", (AdminTab)2, delegate { _admin.RefreshLog(_logCategories); }); NavTo("NPCs", (AdminTab)3, delegate { _admin.RefreshNpcs(); _admin.Editor.RefreshLists(); }); NavTo("Creatures", (AdminTab)10, delegate { _admin.RefreshCreatures(); }); GUILayout.Space(10f); GUILayout.Label("CONTENT EDITOR", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); NavTo("Shops", (AdminTab)4, null); NavTo("Quest editor", (AdminTab)5, null); NavTo("NPC creator", (AdminTab)7, null); NavTo("Pictures", (AdminTab)8, null); NavTo("Test tools", (AdminTab)9, delegate { _admin.Editor.RefreshLists(); }); EditorButton(); GUILayout.Space(10f); GUILayout.Label("YOU", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); NavTo("Preferences", (AdminTab)6, null); NavTo("Debug log", (AdminTab)11, delegate { _admin.AskDebug(); }); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("A−", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f) })) { ConsolePrefs.TextScale -= 0.1f; } GUILayout.Label(Percent(ConsolePrefs.TextScale), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(52f) }); if (GUILayout.Button("A+", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f) })) { ConsolePrefs.TextScale += 0.1f; } GUILayout.EndHorizontal(); RuneSkin.Line(_superAdmin ? "● SuperAdmin" : "○ Not an admin here", _superAdmin ? RuneSkin.Moss : RuneSkin.Rust); if (_admin.TestKills) { RuneSkin.Line("⚔ Test mode on", RuneSkin.Amber); } GUILayout.Label("Esc closes · drag the corner to resize", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.EndVertical(); } private static string Percent(float scale) { return checked((int)(scale * 100f + 0.5f)).ToString(CultureInfo.InvariantCulture) + "%"; } private void NavTo(string label, AdminTab tab, Action? opened) { //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) //IL_0021: 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) bool flag = _admin.Tab == tab; if (!GUILayout.Button(label, RuneSkin.Or(flag ? RuneSkin.NavOn : RuneSkin.Nav, GUI.skin.button), Array.Empty<GUILayoutOption>())) { return; } if (flag) { opened?.Invoke(); return; } Guard("Going to " + label, delegate { //IL_0007: Unknown result type (might be due to invalid IL or missing references) Go(tab); opened?.Invoke(); }); } private void Guard(string what, Action go) { ContentEditor editor = _admin.Editor; if (editor.Form == null || !editor.Dirty) { go(); return; } _leave = go; _leaveWhat = what; _leavePublishing = false; } private void DrawLeave(int id) { //IL_006e: 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) GUISkin current = RuneSkin.Current; GUISkin skin = GUI.skin; if ((Object)(object)current != (Object)null) { GUI.skin = current; } try { JsonForm form = _admin.Editor.Form; string text = ((form == null) ? "this" : ((form.DisplayName.Length > 0) ? form.DisplayName : form.Id)); GUILayout.Space(6f); RuneSkin.Line("Changes have been made to " + text + " that are not published yet.", RuneSkin.Amber); GUILayout.Label(_leaveWhat + " would leave them behind. What would you like to do?", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.Space(10f); if (_leavePublishing) { RuneSkin.Line((_admin.Editor.Status.Length > 0) ? _admin.Editor.Status : "Publishing…", RuneSkin.Steel); return; } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("Publish, then go on", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) })) { _leavePublishing = true; _admin.Editor.Publish(_admin.Reason); } if (GUILayout.Button("Save as a draft, then go on", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) })) { _leavePublishing = true; _admin.Editor.SaveDraft(_admin.Reason); } if (GUILayout.Button("Go on without publishing", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) })) { Action leave = _leave; _leave = null; _admin.Editor.Close(); leave?.Invoke(); } if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) })) { _leave = null; } GUILayout.EndHorizontal(); } finally { GUI.skin = skin; } } private void FollowPublish() { ContentEditor editor = _admin.Editor; if (_leavePublishing && _leave != null && !editor.Busy) { _leavePublishing = false; if (editor.Dirty) { _leave = null; return; } Action leave = _leave; _leave = null; leave(); } } private void Go(AdminTab tab) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: 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) //IL_001c: 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) if (_admin.Tab != tab) { _admin.Tab = tab; _scroll = Vector2.zero; _shops.LeftPage(); } } private static string PageTitle(AdminTab tab) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected I4, but got Unknown return (int)tab switch { 0 => "Players", 1 => "Quests in progress", 3 => "NPCs in the world", 10 => "Creatures and spawners", 4 => "Shops, trades and money", 5 => "Quests and conversations", 7 => "NPC creator", 8 => "Pictures for the browser editor", 9 => "Test tools", 6 => "Preferences", 11 => "Debug log", _ => "Activity", }; } private void DrawPreferences() { //IL_0366: Unknown result type (might be due to invalid IL or missing references) //IL_0405: Unknown result type (might be due to invalid IL or missing references) RuneSkin.Header("Text"); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Text size", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); if (GUILayout.Button("A−", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f) })) { ConsolePrefs.TextScale -= 0.05f; } GUILayout.Label(Percent(ConsolePrefs.TextScale), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(56f) }); if (GUILayout.Button("A+", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f) })) { ConsolePrefs.TextScale += 0.05f; } GUILayout.Space(16f); float[] presets = Presets; foreach (float num in presets) { bool flag = Mathf.Abs(ConsolePrefs.TextScale - num) < 0.01f; if (GUILayout.Toggle(flag, Percent(num), GUI.skin.button, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(64f) }) && !flag) { ConsolePrefs.TextScale = num; } } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Resizing the window", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); bool flag2 = GUILayout.Toggle(ConsolePrefs.GrowWithWindow, "makes the text bigger or smaller with it", Array.Empty<GUILayoutOption>()); if (flag2 != ConsolePrefs.GrowWithWindow) { ConsolePrefs.GrowWithWindow = flag2; } GUILayout.EndHorizontal(); GUILayout.Label(ConsolePrefs.GrowWithWindow ? "Drag the window's corner: at its usual size the text is the size above; twice as big, twice the size." : "Drag the window's corner for more room; the text stays the size above.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Font", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); Choice("Averia Serif (Valheim's)", ConsolePrefs.Font == "averia", delegate { ConsolePrefs.Font = "averia"; }); Choice("Averia Serif light", ConsolePrefs.Font == "averia_light", delegate { ConsolePrefs.Font = "averia_light"; }); Choice("Plain", ConsolePrefs.Font == "plain", delegate { ConsolePrefs.Font = "plain"; }); GUILayout.EndHorizontal(); RuneSkin.Header("Look and colours"); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Look", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); Choice("Rune-carved", ConsolePrefs.Look == "rune", delegate { ConsolePrefs.Look = "rune"; }); Choice("Plain (Unity's own)", ConsolePrefs.Look == "plain", delegate { ConsolePrefs.Look = "plain"; }); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Accent", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); (string, string, Color, Color, Color)[] accents = RuneSkin.Accents; for (int num2 = 0; num2 < accents.Length; num2++) { (string, string, Color, Color, Color) tuple = accents[num2]; var (text, _, _, _, _) = tuple; if (RuneSkin.Swatch(tuple.Item3, 22f, ConsolePrefs.Accent == text)) { ConsolePrefs.Accent = text; } GUILayout.Label(tuple.Item2, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(62f) }); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Text colour", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); (string, string, Color)[] textColours = RuneSkin.TextColours; for (int num3 = 0; num3 < textColours.Length; num3++) { (string, string, Color) tuple3 = textColours[num3]; var (text2, _, _) = tuple3; if (RuneSkin.Swatch(tuple3.Item3, 22f, ConsolePrefs.TextColour == text2)) { ConsolePrefs.TextColour = text2; } GUILayout.Label(tuple3.Item2, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(82f) }); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Panel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); if (GUILayout.Button("−", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(30f) })) { ConsolePrefs.Opacity -= 0.05f; } GUILayout.Label(Percent(ConsolePrefs.Opacity) + " solid", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) }); if (GUILayout.Button("+", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(30f) })) { ConsolePrefs.Opacity += 0.05f; } GUILayout.Label("(lower lets the world show through)", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.EndHorizontal(); if (ConsolePrefs.Look == "plain") { GUILayout.Label("The accent, text colour, font and panel apply to the rune-carved look.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); } RuneSkin.Header("Window"); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Size", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); GUILayout.Label(checked(((int)((Rect)(ref _screen)).width).ToString(CultureInfo.InvariantCulture) + " × " + ((int)((Rect)(ref _screen)).height).ToString(CultureInfo.InvariantCulture)) + " pixels, drawn at " + Percent(_scale), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(260f) }); if (GUILayout.Button("Usual size, middle of the screen", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(240f) })) { ResetWindow(); } GUILayout.EndHorizontal(); GUILayout.Space(10f); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("Everything back to the defaults", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(260f) })) { ConsolePrefs.Reset(); ResetWindow(); } GUILayout.EndHorizontal(); GUILayout.Label("These are saved on this computer, in the ALIVE Admin config file under [Console]. They change only your console.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); } private static void Choice(string label, bool chosen, Action choose) { if (GUILayout.Toggle(chosen, label, GUI.skin.button, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }) && !chosen) { choose(); } } private void KeepUp() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Invalid comparison between Unknown and I4 //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Invalid comparison between Unknown and I4 //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Invalid comparison between Unknown and I4 //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Expected I4, but got Unknown //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Invalid comparison between Unknown and I4 if (Event.current == null || (int)Event.current.type != 7) { return; } float unscaledTime = Time.unscaledTime; float num = (((int)_admin.Tab == 3 || (int)_admin.Tab == 10) ? 15f : 10f); if (unscaledTime - _keptUpAt < num) { return; } _keptUpAt = unscaledTime; if (GUIUtility.keyboardControl != 0 || _leave != null) { return; } AdminTab tab = _admin.Tab; switch ((int)tab) { default: if ((int)tab == 10) { _admin.Quietly((Action)_admin.RefreshCreatures); } break; case 0: _admin.Quietly((Action)_admin.RefreshPlayers); if (_admin.FlagsPlayer.Length > 0) { _admin.Quietly((Action)delegate { _admin.ShowFlags(_admin.FlagsPlayer); }); } break; case 1: _admin.Quietly((Action)delegate { if (_admin.ShowingWaiting) { _admin.RefreshWaiting(); } else { _admin.RefreshQuests(_admin.QuestPlayer, _openOnly); } }); break; case 2: _admin.Quietly((Action)delegate { _admin.RefreshLog(_logCategories); }); break; case 3: _admin.Quietly((Action)_admin.RefreshNpcs); break; } } private void EditorButton() { //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) if (OpenEditor == null) { return; } GUILayout.Space(6f); bool enabled = GUI.enabled; GUI.enabled = enabled && _superAdmin; if (GUILayout.Button("Open the editor\nin my browser", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), Array.Empty<GUILayoutOption>())) { OpenEditor(); } GUI.enabled = enabled; if (!_superAdmin) { GUILayout.Label("For SuperAdmins only", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); return; } string text = EditorLine?.Invoke() ?? string.Empty; if (text.Length != 0) { RuneSkin.Line(text, text.Contains("not connected") ? RuneSkin.Rust : RuneSkin.Moss); if (StopEditor != null && GUILayout.Button("Stop it", Array.Empty<GUILayoutOption>())) { StopEditor(); } } } private void Page() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected I4, but got Unknown //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Invalid comparison between Unknown and I4 //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Invalid comparison between Unknown and I4 //IL_01e2: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_02ed: Unknown result type (might be due to invalid IL or missing references) GUILayout.Label(PageTitle(_admin.Tab), RuneSkin.Or(RuneSkin.Title, GUI.skin.label), Array.Empty<GUILayoutOption>()); _scroll = GUILayout.BeginScrollView(_scroll, Array.Empty<GUILayoutOption>()); AdminTab tab = _admin.Tab; switch ((int)tab) { case 0: DrawPlayers(); break; case 1: DrawQuests(); break; case 3: DrawNpcs(); break; case 10: DrawCreatures(); break; case 4: case 5: case 7: { ShopEditorView shops = _shops; AdminTab tab2 = _admin.Tab; EditorPage page = (((int)tab2 == 5) ? EditorPage.Stories : (((int)tab2 == 7) ? EditorPage.Npcs : EditorPage.Shops)); shops.Page = page; _shops.Draw(); if (_shops.WantsTop) { _shops.WantsTop = false; _scroll = Vector2.zero; } break; } case 6: DrawPreferences(); break; case 8: PicturesSection(); break; case 9: DrawTestTools(); break; case 11: DrawDebug(); break; default: DrawLog(); break; } GUILayout.EndScrollView(); GUILayout.Space(6f); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Note for the audit log", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) }); _admin.Reason = GUILayout.TextField(_admin.Reason ?? string.Empty, 256, Array.Empty<GUILayoutOption>()); GUILayout.EndHorizontal(); if (_superAdmin) { GUILayout.Label("Optional. Every change is recorded with your Steam id either way.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); } else { RuneSkin.Line(AdminClient.NotAnAdmin(_admin.PlatformId), RuneSkin.Rust); } if (_admin.PendingOpId.Length > 0) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); RuneSkin.Line("Waiting for another SuperAdmin: " + _admin.PendingOpId, RuneSkin.Amber); if (GUILayout.Button("Approve", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { _admin.Decide(_admin.PendingOpId, true); } if (GUILayout.Button("Refuse", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { _admin.Decide(_admin.PendingOpId, false); } GUILayout.EndHorizontal(); } if (_admin.Status.Length > 0) { RuneSkin.Line(_admin.Status, RuneSkin.Tone(_admin.Status)); } } private void DrawPlayers() { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Name or Steam id", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) }); _admin.PlayerQuery = GUILayout.TextField(_admin.PlayerQuery ?? string.Empty, 64, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(260f) }); if (GUILayout.Button("Search", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _admin.RefreshPlayers(); } GUILayout.EndHorizontal(); foreach (PlayerSearchItem player in _admin.Players) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label((player.Online ? "● " : "○ ") + ((player.LastName.Length == 0) ? "(no name yet)" : player.LastName), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); GUILayout.Label(player.PlatformId, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) }); GUILayout.Label(player.SessionCount + " visit(s), last " + Ago(player.LastSeenUnixMs), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }); if (GUILayout.Button("Quests", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _admin.RefreshQuests(player.PlatformId, false); } if (GUILayout.Button("Flags…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _confirmClearAll = false; _admin.ShowFlags(player.PlatformId); } GUILayout.EndHorizontal(); } if (_admin.Players.Count == 0) { GUILayout.Label("Nobody matched. The list holds players who have joined with ALIVE at least once.", Array.Empty<GUILayoutOption>()); } if (_admin.FlagsPlayer.Length > 0) { DrawFlags(); } } private void DrawFlags() { //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_02c5: Unknown result type (might be due to invalid IL or missing references) //IL_02ca: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Unknown result type (might be due to invalid IL or missing references) //IL_0309: Unknown result type (might be due to invalid IL or missing references) //IL_08c1: Unknown result type (might be due to invalid IL or missing references) GUIStyle val = RuneSkin.Or(RuneSkin.Aside, GUI.skin.label); string text = ((_admin.FlagsName.Length > 0) ? _admin.FlagsName : _admin.FlagsPlayer); GUILayout.Space(10f); RuneSkin.Header(text + "'s ALIVE flags" + ((_admin.FlagsTotal >= 0) ? (" · " + _admin.FlagsTotal) : string.Empty)); GUILayout.Label(_admin.FlagsPlayer + ". A flag is a yes-or-no mark ALIVE keeps for each player: quests and conversations give and take them and read them to decide what happens. The browser editor's Story memory page shows where each one is set and read.", val, Array.Empty<GUILayoutOption>()); foreach (string flagLine in _admin.FlagLines) { RuneSkin.Line(flagLine, RuneSkin.Tone(flagLine)); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Find", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(50f) }); _flagFind = GUILayout.TextField(_flagFind ?? string.Empty, 64, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(240f) }); if (GUILayout.Button("⟳ Read again", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) })) { _admin.ShowFlags(_admin.FlagsPlayer); } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); if (_admin.FlagsTotal < 0) { GUILayout.Label("Asking the server…", val, Array.Empty<GUILayoutOption>()); } else if (_admin.FlagsTotal == 0) { GUILayout.Label(text + " holds no ALIVE flags.", val, Array.Empty<GUILayoutOption>()); } string find = (_flagFind ?? string.Empty).Trim(); List<PlayerFlagItem> list = (from f in _admin.PlayerFlags where find.Length == 0 || f.Flag.Contains(find, StringComparison.OrdinalIgnoreCase) orderby (!string.Equals(f.Flag, _admin.LitFlag, StringComparison.Ordinal)) ? 1 : 0 select f).ToList(); if (find.Length > 0 && list.Count == 0 && _admin.FlagsTotal > 0) { GUILayout.Label("None of their flags is called that.", val, Array.Empty<GUILayoutOption>()); } foreach (PlayerFlagItem item in list) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); string text2 = (item.Flag.StartsWith("alive:flag/", StringComparison.Ordinal) ? item.Flag.Substring("alive:flag/".Length) : item.Flag); bool flag = string.Equals(item.Flag, _admin.LitFlag, StringComparison.Ordinal); Color contentColor = GUI.contentColor; if (flag) { GUI.contentColor = RuneSkin.Amber; } GUILayout.Label((flag ? "● " : string.Empty) + text2, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(300f) }); GUI.contentColor = contentColor; GUILayout.Label("set " + Ago(item.SetUnixMs), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) }); if (GUILayout.Button("Clear", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.ClearFlags(item.Flag); } GUILayout.EndHorizontal(); } if (_admin.FlagsTotal > _admin.PlayerFlags.Count) { GUILayout.Label("…and " + checked(_admin.FlagsTotal - _admin.PlayerFlags.Count) + " more, oldest first, not shown.", val, Array.Empty<GUILayoutOption>()); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Give a flag", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); _giveFlag = NameBox("alive_give_flag", _giveFlag); GUI.enabled = _giveFlag.Trim().Length > 0 && _admin.FlagsTotal >= 0; if (GUILayout.Button("Give", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.GiveFlag(_giveFlag); } GUI.enabled = true; GUILayout.EndHorizontal(); NameSuggestions("alive_give_flag", _giveFlag, _admin.KnownFlags, "alive:flag/", "flags", delegate(string v) { _giveFlag = v; }); GUILayout.Space(6f); GUILayout.Label("Counters: numbers ALIVE keeps for each player, which quests and conversations add to and compare.", val, Array.Empty<GUILayoutOption>()); foreach (PlayerCounterItem playerCounter in _admin.PlayerCounters) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); string text3 = (playerCounter.Counter.StartsWith("alive:counter/", StringComparison.Ordinal) ? playerCounter.Counter.Substring("alive:counter/".Length) : playerCounter.Counter); GUILayout.Label(text3, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(300f) }); GUILayout.Label(playerCounter.Value.ToString(CultureInfo.InvariantCulture), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) }); if (GUILayout.Button("Change…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _counterName = text3; _counterValue = playerCounter.Value.ToString(CultureInfo.InvariantCulture); } GUILayout.EndHorizontal(); } if (_admin.FlagsTotal >= 0 && _admin.PlayerCounters.Count == 0) { GUILayout.Label(text + " holds no ALIVE counters.", val, Array.Empty<GUILayoutOption>()); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Set a counter", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); _counterName = NameBox("alive_set_counter", _counterName); GUILayout.Label("to", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(20f) }); _counterValue = GUILayout.TextField(_counterValue, 12, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) }); long result; bool flag2 = long.TryParse(_counterValue.Trim(), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out result); GUI.enabled = _counterName.Trim().Length > 0 && flag2 && _admin.FlagsTotal >= 0; if (GUILayout.Button("Set", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.SetCounter(_counterName, result); } GUI.enabled = true; GUILayout.EndHorizontal(); if (_counterValue.Trim().Length > 0 && !flag2) { GUILayout.Label("A counter is a whole number, such as 3 or -1. 0 takes it away.", val, Array.Empty<GUILayoutOption>()); } NameSuggestions("alive_set_counter", _counterName, _admin.KnownCounters, "alive:counter/", "counters", delegate(string v) { _counterName = v; }); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUI.enabled = _admin.FlagsTotal > 0; if (GUILayout.Button("Clear all…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { _confirmClearAll = !_confirmClearAll; } GUI.enabled = true; if (GUILayout.Button("Read again", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.ShowFlags(_admin.FlagsPlayer); } if (GUILayout.Button("Close", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _confirmClearAll = false; _admin.HideFlags(); } GUILayout.EndHorizontal(); if (_confirmClearAll && _admin.FlagsTotal > 0) { RuneSkin.Line("Clear all " + _admin.FlagsTotal + " flags " + text + " holds? Quests and conversations that read them will treat " + text + " as if they never had them.", RuneSkin.Amber); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("Clear them all", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _confirmClearAll = false; _admin.ClearFlags(string.Empty); } if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _confirmClearAll = false; } GUILayout.EndHorizontal(); } } private string NameBox(string control, string value) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Invalid comparison between Unknown and I4 //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Invalid comparison between Unknown and I4 if ((int)Event.current.type == 8 && _pendingName.Control == control) { value = _pendingName.Value; _pendingName = (Control: string.Empty, Value: string.Empty); _activeNameBox = string.Empty; if (GUI.GetNameOfFocusedControl() == control) { GUIUtility.keyboardControl = 0; } } GUI.SetNextControlName(control); string text = GUILayout.TextField(value, 128, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(280f) }); if ((int)Event.current.type == 8 && GUI.GetNameOfFocusedControl() == control && !string.Equals(text, _lastTyped, StringComparison.Ordinal)) { _activeNameBox = control; } if ((int)Event.current.type == 8) { _lastTyped = ((GUI.GetNameOfFocusedControl() == control) ? text : _lastTyped); } bool flag = _openNameList == control; if (GUILayout.Button(flag ? "Hide list" : "List", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(72f) })) { _openNameList = (flag ? string.Empty : control); } return text; } private void NameSuggestions(string control, string value, IReadOnlyList<string> known, string prefix, string what, Action<string> chosen) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) if ((int)Event.current.type == 8) { _nameRows[control] = NameRows.Of(control == _openNameList, control == _activeNameBox, value, known, prefix); } if (!_nameRows.TryGetValue(control, out NameRows value2) || !value2.Shown) { return; } GUIStyle val = RuneSkin.Or(RuneSkin.Row, GUI.skin.button); GUIStyle val2 = RuneSkin.Or(RuneSkin.Aside, GUI.skin.label); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Space(110f); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(value2.Open ? 306f : 280f) }); if (value2.Open && value2.Names.Count == 0) { GUILayout.Label((value2.Known == 0) ? ("The server knows no " + what + " yet: none is set or read by its quests and conversations, and no player holds one.") : ("None of the " + what + " the server knows has that in its name."), val2, Array.Empty<GUILayoutOption>()); } else if (value2.Open) { _nameListScroll = GUILayout.BeginScrollView(_nameListScroll, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(Mathf.Min(220f, 26f * (float)value2.Names.Count + 8f)) }); foreach (string name in value2.Names) { if (GUILayout.Button(name, val, Array.Empty<GUILayoutOption>())) { Choose(control, name, chosen); } } GUILayout.EndScrollView(); } else { foreach (string name2 in value2.Names) { if (GUILayout.Button(name2, val, Array.Empty<GUILayoutOption>())) { Choose(control, name2, chosen); } } if (value2.More > 0) { GUILayout.Label("…and " + value2.More.ToString(CultureInfo.InvariantCulture) + " more: type more, or open the list.", val2, Array.Empty<GUILayoutOption>()); } } GUILayout.EndVertical(); GUILayout.EndHorizontal(); } private void Choose(string control, string name, Action<string> chosen) { chosen(name); _pendingName = (Control: control, Value: name); _openNameList = string.Empty; _activeNameBox = string.Empty; } private void DrawQuests() { //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_0539: Unknown result type (might be due to invalid IL or missing references) //IL_05a0: Unknown result type (might be due to invalid IL or missing references) //IL_065f: Unknown result type (might be due to invalid IL or missing references) GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label((_admin.QuestPlayer.Length == 0) ? "Every player" : ("Player " + _admin.QuestPlayer), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(260f) }); bool flag = GUILayout.Toggle(_openOnly, "Only unfinished", Array.Empty<GUILayoutOption>()); if (flag != _openOnly) { _openOnly = flag; _admin.RefreshQuests(_admin.QuestPlayer, _openOnly); } if (GUILayout.Button("Refresh", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { if (_admin.ShowingWaiting) { _admin.RefreshWaiting(); } else { _admin.RefreshQuests(_admin.QuestPlayer, _openOnly); } } if (_admin.QuestPlayer.Length > 0 && GUILayout.Button("All players", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { _admin.RefreshQuests(string.Empty, _openOnly); } string text = ((_admin.WaitingCount > 0) ? ("Waiting for me (" + _admin.WaitingCount.ToString(CultureInfo.InvariantCulture) + ")") : "Waiting for me"); if (GUILayout.Button(text, (GUIStyle)((_admin.WaitingCount > 0) ? ((object)RuneSkin.Or(RuneSkin.Primary, GUI.skin.button)) : ((object)GUI.skin.button)), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) })) { _admin.RefreshWaiting(); } GUILayout.EndHorizontal(); TestKillsRow(); if (_admin.ShowingWaiting) { RuneSkin.Line("Quests with a step waiting for an admin to check it. Mark the step done when the player has done it.", RuneSkin.Amber); } foreach (QuestInstanceRow quest in _admin.Quests) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(quest.QuestId, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(230f) }); GUILayout.Label(StateName(quest.State) + " (try " + quest.Attempt + ")", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) }); GUILayout.Label(Progress(quest), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) }); bool flag2 = quest.State != 0 && QuestStates.IsOpen((QuestState)quest.State); if (flag2 && GUILayout.Button("Clear progress", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { _admin.ResetQuest(quest.InstanceId, false); } if (GUILayout.Button(flag2 ? "Full reset" : "Let them retake", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(flag2 ? 80f : 120f) })) { _admin.ResetQuest(quest.InstanceId, true); } if (flag2 && GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.CancelQuest(quest.InstanceId); } if (GUILayout.Button("Take rewards", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.RevokeQuest(quest.InstanceId); } if (GUILayout.Button("Close to player", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { _admin.DenyQuest(quest.PlatformId, quest.QuestId, true, 0uL); } if (GUILayout.Button("Reopen", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.DenyQuest(quest.PlatformId, quest.QuestId, false, 0uL); } if ((quest.State == 2 || quest.State == 3 || quest.State == 7 || quest.State == 9) && GUILayout.Button("Complete…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { _confirmComplete = ((_confirmComplete == quest.InstanceId) ? 0 : quest.InstanceId); } if (quest.State == 7 && GUILayout.Button("Resume", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.ResumeQuest(quest.InstanceId); } GUI.enabled = _superAdmin; if (GUILayout.Button("Wipe…", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _confirmWipe = ((_confirmWipe == quest.InstanceId) ? 0 : quest.InstanceId); } GUI.enabled = true; GUILayout.EndHorizontal(); if (quest.Status.Length > 0) { RuneSkin.Line(" " + quest.Status, RuneSkin.Amber); } if (_confirmWipe == quest.InstanceId) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Space(24f); RuneSkin.Line("Wipe " + quest.QuestId + " from " + quest.PlatformId + "'s history, as if they never took it? Every attempt, its steps and the flags it uses go, and rewards it has not handed over are not handed over. What they were given stays theirs. This cannot be undone; the audit log keeps the record.", RuneSkin.Amber); if (GUILayout.Button("Wipe it", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { _confirmWipe = 0uL; _admin.WipeQuest(quest.InstanceId); } if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _confirmWipe = 0uL; } GUILayout.EndHorizontal(); } if (_confirmComplete == quest.InstanceId) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Space(24f); RuneSkin.Line("Complete it for " + quest.PlatformId + " as if they had finished it? The rewards are paid; nothing it asked for is taken.", RuneSkin.Amber); if (GUILayout.Button("Complete and pay", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _confirmComplete = 0uL; _admin.CompleteQuest(quest.InstanceId, ""); } if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _confirmComplete = 0uL; } GUILayout.EndHorizontal(); } foreach (QuestObjectiveRow objective in quest.Objectives) { if (objective.Manual) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Space(24f); GUILayout.Label("Step \"" + objective.ObjectiveId + "\"" + ((objective.Text.Length > 0) ? (": " + objective.Text) : string.Empty), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(520f) }); if (GUILayout.Button("Mark it done", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { _admin.CompleteQuest(quest.InstanceId, objective.ObjectiveId); } GUILayout.EndHorizontal(); } } } if (_admin.Quests.Count == 0) { GUILayout.Label(_admin.ShowingWaiting ? "Nothing is waiting for you to check." : "No quest instances yet.", Array.Empty<GUILayoutOption>()); } } private void TestKillsRow() { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); bool flag = GUILayout.Toggle(_admin.TestKills, "Test mode: what I do counts for my quests at once, even with creatures and items I spawned", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); if (flag != _admin.TestKills) { _admin.SetTestKills(flag); } GUILayout.EndHorizontal(); GUILayout.Label(_admin.TestKills ? "On for you until you log off: your kills, what you pick up for gathering steps, and taming count at once. Each is in the activity log (kill.test, quest.gather_test). Players beside you are checked as always." : "Off: you are checked like everyone else. A creature that appears right beside a player must be watched a while before its death counts, and only what was gathered in the world counts for gathering steps.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); } private void DrawTestTools() { //IL_0397: Unknown result type (might be due to invalid IL or missing references) GUIStyle val = RuneSkin.Or(RuneSkin.Aside, GUI.skin.label); RuneSkin.Header("Meet an NPC again for the first time"); GUILayout.Label("The NPC forgets you: how often you have spoken, the lines you heard and the answers you chose in their conversation, and the flags that conversation gives. Only you: players keep what they have.", val, Array.Empty<GUILayoutOption>()); IReadOnlyList<ContentListItem> readOnlyList = _admin.Editor.Listed((AliveIdKind)1); foreach (ContentListItem item in readOnlyList) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label((item.DisplayName.Length > 0) ? item.DisplayName : item.Id, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(280f) }); if (GUILayout.Button("Forget me", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { _admin.UseStoryTool((byte)1, item.Id); } GUILayout.EndHorizontal(); } if (readOnlyList.Count == 0) { GUILayout.Label("(no NPCs yet, or the list is still loading)", val, Array.Empty<GUILayoutOption>()); } GUILayout.Space(8f); RuneSkin.Header("Your own flags"); GUILayout.Label("Give yourself a flag, or take one away, to try a branch without playing up to it. Every flag, with what sets it and what reads it, is on the browser editor's Story memory page.", val, Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Flag", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) }); _storyFlag = GUILayout.TextField(_storyFlag, 128, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(280f) }); GUI.enabled = _storyFlag.Trim().Length > 0; if (GUILayout.Button("Give me", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.UseStoryTool((byte)2, _storyFlag); } if (GUILayout.Button("Take away", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.UseStoryTool((byte)3, _storyFlag); } GUI.enabled = true; GUILayout.EndHorizontal(); if (GUILayout.Button("See all my flags", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) })) { string playerQuery = (((Object)(object)Player.m_localPlayer != (Object)null) ? Player.m_localPlayer.GetPlayerName() : string.Empty); _admin.PlayerQuery = playerQuery; Go((AdminTab)0); _admin.RefreshPlayers(); } GUILayout.Space(8f); RuneSkin.Header("Server switches"); GUILayout.Label("One on/off for every player, read by conversations as \"Server switch is on\". Switching it changes what every player meets at once.", val, Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Switch", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) }); _storySwitch = GUILayout.TextField(_storySwitch, 64, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(280f) }); GUI.enabled = _storySwitch.Trim().Length > 0; if (GUILayout.Button("On for everyone", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _admin.UseStoryTool((byte)4, _storySwitch); } if (GUILayout.Button("Off for everyone", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _admin.UseStoryTool((byte)5, _storySwitch); } GUI.enabled = true; GUILayout.EndHorizontal(); GUILayout.Space(8f); RuneSkin.Header("Kills"); TestKillsRow(); if (_admin.StoryLines.Count == 0) { return; } GUILayout.Space(8f); foreach (string storyLine in _admin.StoryLines) { RuneSkin.Line(storyLine, RuneSkin.Moss); } } private void DrawNpcs() { //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) RuneSkin.Header("Place an NPC"); GUILayout.Label("Place here puts the NPC where you stand, facing you. Place… lets you aim: the NPC follows where you look, the wheel turns it, a click puts it down, right-click stops. The server takes any spot within 30 m of you.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Spot label", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }); _npcLabel = GUILayout.TextField(_npcLabel ?? string.Empty, 64, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }); GUILayout.FlexibleSpace(); GUI.enabled = _superAdmin && GiveHammer != null; if (GUILayout.Button("Get the Admin Tool", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) })) { _hammerNote = GiveHammer(); } GUI.enabled = true; if (GUILayout.Button("Refresh", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _admin.RefreshNpcs(); } GUILayout.EndHorizontal(); if (_hammerNote.Length > 0) { RuneSkin.Line(_hammerNote, _hammerNote.StartsWith("The ALIVE Admin Tool is in", StringComparison.Ordinal) ? RuneSkin.Moss : RuneSkin.Steel); } _shops.DrawDeleteBox(); if (_admin.Editor.DeleteId.Length == 0 && _admin.Editor.Status.StartsWith("Deleted", StringComparison.Ordinal)) { RuneSkin.Line(_admin.Editor.Status, RuneSkin.Moss); } string text = _npcLabel ?? string.Empty; foreach (string item in _admin.Placeable) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(NpcName(item), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); GUILayout.Label(item, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); if (GUILayout.Button("Place here", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.PlaceNpc(item, text); } if (GUILayout.Button("Place…", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }) && PlaceWithTool != null) { PlaceWithTool(item, text); } if (GUILayout.Button("Edit", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) })) { EditNpc(item); } ContentListItem val = Listed(item); GUI.enabled = val != null && !_admin.Editor.Busy; if (GUILayout.Button("Delete…", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }) && val != null) { _admin.Editor.AskDelete(val.Id, val.Version, NpcName(item)); } GUI.enabled = true; GUILayout.EndHorizontal(); } if (_admin.Placeable.Count == 0) { GUILayout.Label("The loaded content has no NPCs to place.", Array.Empty<GUILayoutOption>()); } RuneSkin.Header("In the world"); foreach (NpcPlacementRow placement in _admin.Placements) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label((placement.Enabled ? "● " : "○ ") + placement.Name, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); GUILayout.Label((placement.Label.Length == 0) ? "-" : placement.Label, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) }); GUILayout.Label(Metres(placement.XCm) + ", " + Metres(placement.YCm) + ", " + Metres(placement.ZCm), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); GUILayout.Label("placed " + Ago(placement.PlacedUnixMs), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); if (GUILayout.Button("Teleport to NPC", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(130f) })) { _admin.GoToNpc(placement.PlacementId); } if (GUILayout.Button("Move…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }) && MoveWithTool != null) { MoveWithTool(placement.PlacementId, placement.NpcId); } if (GUILayout.Button("Remove from world", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _admin.RemoveNpc(placement.PlacementId); } if (GUILayout.Button("Edit", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) })) { EditNpc(placement.NpcId); } GUILayout.EndHorizontal(); } if (_admin.Placements.Count == 0) { GUILayout.Label("No NPC has been placed yet.", Array.Empty<GUILayoutOption>()); } } private void DrawCreatures() { //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) GUILayout.Label("Creatures and spawners are made in the browser editor on the server machine and published there. Here you try them and place them.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUI.enabled = _superAdmin && GiveHammer != null; if (GUILayout.Button("Get the Admin Tool", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) })) { _hammerNote = GiveHammer(); } GUI.enabled = true; if (GUILayout.Button("Refresh", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _admin.RefreshCreatures(); } GUILayout.FlexibleSpace(); GUILayout.Label(_admin.CreaturesAlive.ToString(CultureInfo.InvariantCulture) + " of at most " + _admin.CreatureLimit.ToString(CultureInfo.InvariantCulture) + " ALIVE creatures alive · " + _admin.CreaturesMine.ToString(CultureInfo.InvariantCulture) + " spawned by you", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); GUILayout.EndHorizontal(); if (_hammerNote.Length > 0) { RuneSkin.Line(_hammerNote, _hammerNote.StartsWith("The ALIVE Admin Tool is in", StringComparison.Ordinal) ? RuneSkin.Moss : RuneSkin.Steel); } if (!_admin.CllcOnServer && _admin.CreaturesKnown) { GUILayout.Label("Creature Level & Loot Control is not on this server: creatures' settings for it are skipped.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); } RuneSkin.Header("Creatures"); GUILayout.Label("Spawn with the Admin Tool: aim, click for one, Shift+click for five, right-click to stop. A creature you spawn gives no loot, kill credit or world key, unless your test mode is on (Test tools).", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); foreach (CreatureRow creatureRow in _admin.CreatureRows) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(creatureRow.Name, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) }); GUILayout.Label(creatureRow.Base + ((creatureRow.Level > 1) ? (" " + new string('★', Math.Min(9, checked(creatureRow.Level - 1)))) : string.Empty) + (creatureRow.Boss ? " · boss" : string.Empty), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); GUILayout.Label(creatureRow.Alive.ToString(CultureInfo.InvariantCulture) + " alive", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }); GUI.enabled = _superAdmin && SpawnWithTool != null; if (GUILayout.Button("Spawn with the Admin Tool", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(190f) })) { if (NpcHammer.Held() == null && GiveHammer != null) { _hammerNote = GiveHammer(); } SpawnWithTool(creatureRow.Id); } GUI.enabled = true; GUILayout.EndHorizontal(); } if (_admin.CreatureRows.Count == 0) { GUILayout.Label(_admin.CreaturesKnown ? "No creatures yet: make one in the browser editor and publish it." : "Asking the server…", Array.Empty<GUILayoutOption>()); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("Remove the ones I spawned", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) })) { _admin.ClearCreatures((CreatureClearScope)0, 0uL); } GUI.enabled = _superAdmin; if (!_confirmRemoveCreatures) { if (GUILayout.Button("Remove every ALIVE creature…", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(240f) })) { _confirmRemoveCreatures = true; } } else { if (GUILayout.Button("Yes, remove them all", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) })) { _confirmRemoveCreatures = false; _admin.ClearCreatures((CreatureClearScope)2, 0uL); } if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _confirmRemoveCreatures = false; } } GUI.enabled = true; GUILayout.EndHorizontal(); RuneSkin.Header("Spawn points and altars"); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Spot label", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }); _spawnerLabel = GUILayout.TextField(_spawnerLabel ?? string.Empty, 64, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }); GUILayout.EndHorizontal(); foreach (SpawnerRow spawnerRow in _admin.SpawnerRows) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(spawnerRow.Name, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) }); GUILayout.Label(spawnerRow.Altar ? ("altar" + ((spawnerRow.Look.Length > 0) ? (" (" + spawnerRow.Look + ")") : string.Empty)) : "spawn point", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); if (GUILayout.Button("Place here", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.PlaceSpawner(spawnerRow.Id, _spawnerLabel ?? string.Empty); } if (GUILayout.Button("Place…", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }) && PlaceSpawnerWithTool != null) { PlaceSpawnerWithTool(spawnerRow.Id, _spawnerLabel ?? string.Empty); } GUILayout.EndHorizontal(); } if (_admin.SpawnerRows.Count == 0) { GUILayout.Label(_admin.CreaturesKnown ? "No spawners yet: make one in the browser editor and publish it." : "Asking the server…", Array.Empty<GUILayoutOption>()); } RuneSkin.Header("Placed"); foreach (SpawnerPlacementRow spawnerPlacement in _admin.SpawnerPlacements) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(_admin.SpawnerName(spawnerPlacement.SpawnerId), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) }); GUILayout.Label((spawnerPlacement.Label.Length == 0) ? "-" : spawnerPlacement.Label, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) }); GUILayout.Label(Metres(spawnerPlacement.Spot.XCm) + ", " + Metres(spawnerPlacement.Spot.YCm) + ", " + Metres(spawnerPlacement.Spot.ZCm), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) }); GUILayout.Label(spawnerPlacement.Alive.ToString(CultureInfo.InvariantCulture) + " alive", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }); GUI.enabled = _superAdmin && _admin.TeleportTo != null; if (GUILayout.Button("Teleport to", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.TeleportTo((double)spawnerPlacement.Spot.XCm / 100.0, (double)spawnerPlacement.Spot.YCm / 100.0, (double)spawnerPlacement.Spot.ZCm / 100.0, (double)spawnerPlacement.Spot.FacingCentiDeg / 100.0); } GUI.enabled = true; if (GUILayout.Button("Move…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }) && MoveSpawnerWithTool != null) { MoveSpawnerWithTool(spawnerPlacement.PlacementId, spawnerPlacement.SpawnerId); } if (GUILayout.Button("Remove from world", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _admin.RemoveSpawner(spawnerPlacement.PlacementId); } if (spawnerPlacement.Alive > 0 && GUILayout.Button("Remove its creatures", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) })) { _admin.ClearCreatures((CreatureClearScope)1, spawnerPlacement.PlacementId); } GUILayout.EndHorizontal(); } if (_admin.SpawnerPlacements.Count == 0) { GUILayout.Label("No spawner has been placed yet.", Array.Empty<GUILayoutOption>()); } } private void PicturesSection() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Invalid comparison between Unknown and I4 //IL_02b1: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Invalid comparison between Unknown and I4 //IL_02b6: Unknown result type (might be due to invalid IL or missing references) //IL_02aa: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_02d4: Unknown result type (might be due to invalid IL or missing references) PictureRun pictures = _admin.Pictures; if (_picturesAsked.Length > 0 && !pictures.Busy) { RuneSkin.Line(_picturesAsked, RuneSkin.Amber); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUI.enabled = _superAdmin; if (GUILayout.Button("Take pictures", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) })) { _picturesAsked = string.Empty; pictures.Start(); } GUI.enabled = true; if (GUILayout.Button("Not now", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _picturesAsked = string.Empty; } GUILayout.EndHorizontal(); GUILayout.Space(8f); } GUILayout.Label("The browser editor on the server machine shows a picture of each creature, item, building piece and object. The server has no graphics, so your game takes them and sends them. It takes a few minutes; you can keep playing.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUI.enabled = !pictures.Busy; GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); pictures.Creatures = GUILayout.Toggle(pictures.Creatures, "Creatures & characters", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); pictures.Items = GUILayout.Toggle(pictures.Items, "Items", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); pictures.Pieces = GUILayout.Toggle(pictures.Pieces, "Building pieces", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); pictures.Objects = GUILayout.Toggle(pictures.Objects, "Objects", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); pictures.RetakeAll = GUILayout.Toggle(pictures.RetakeAll, "Take again
plugins/ALIVE.Core.dll
Decompiled 3 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using ALIVE.Core.Abstractions; using ALIVE.Core.Client.Editing; using ALIVE.Core.Content; using ALIVE.Core.Content.Conditions; using ALIVE.Core.Content.Creatures; using ALIVE.Core.Content.Currencies; using ALIVE.Core.Content.Dialogue; using ALIVE.Core.Content.Economy; using ALIVE.Core.Content.Effects; using ALIVE.Core.Content.Ids; using ALIVE.Core.Content.Json; using ALIVE.Core.Content.Loading; using ALIVE.Core.Content.Mods; using ALIVE.Core.Content.Npcs; using ALIVE.Core.Content.Packs; using ALIVE.Core.Content.Pricing; using ALIVE.Core.Content.Quests; using ALIVE.Core.Content.Schema; using ALIVE.Core.Content.Shops; using ALIVE.Core.Content.Trades; using ALIVE.Core.Content.Validation; using ALIVE.Core.Diagnostics; using ALIVE.Core.Economy; using ALIVE.Core.Places; using ALIVE.Core.Protocol; using ALIVE.Core.Protocol.Messages; using ALIVE.Core.Storage; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Linq; [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("Valheim ALIVE")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.61.0.0")] [assembly: AssemblyInformationalVersion("0.61.0")] [assembly: AssemblyProduct("Valheim ALIVE")] [assembly: AssemblyTitle("ALIVE.Core")] [assembly: InternalsVisibleTo("ALIVE.Core.Tests")] [assembly: AssemblyVersion("0.61.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } } namespace System.Runtime.CompilerServices { internal static class IsExternalInit { } } namespace ALIVE.Core { public static class AliveCoreVersion { public static readonly string Value = ReadFromAssembly(); private static string ReadFromAssembly() { return typeof(AliveCoreVersion).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0"; } } public static class AliveGuid { public const string Server = "com.imaginaryrealms.alive.server"; public const string Player = "com.imaginaryrealms.alive.client.player"; public const string Admin = "com.imaginaryrealms.alive.client.admin"; public static bool IsPlayer(string? id) { if (!Is(id, "com.imaginaryrealms.alive.client.player")) { return Is(id, "net.winterwolf.alive.client.player"); } return true; } public static bool IsAdmin(string? id) { if (!Is(id, "com.imaginaryrealms.alive.client.admin")) { return Is(id, "net.winterwolf.alive.client.admin"); } return true; } public static bool IsAlive(string? id) { if (!IsPlayer(id) && !IsAdmin(id) && !Is(id, "com.imaginaryrealms.alive.server")) { return Is(id, "net.winterwolf.alive.server"); } return true; } public static bool IsOld(string? id) { if (!Is(id, "net.winterwolf.alive.server") && !Is(id, "net.winterwolf.alive.client.player")) { return Is(id, "net.winterwolf.alive.client.admin"); } return true; } private static bool Is(string? id, string guid) { return string.Equals(id, guid, StringComparison.Ordinal); } } public static class AliveOldGuid { public const string Server = "net.winterwolf.alive.server"; public const string Player = "net.winterwolf.alive.client.player"; public const string Admin = "net.winterwolf.alive.client.admin"; } public static class SettingsCarry { public static string? FromOldId(string configFolder, string oldId, string newId) { if (string.IsNullOrEmpty(configFolder) || string.IsNullOrEmpty(oldId) || string.IsNullOrEmpty(newId)) { return null; } string text = Path.Combine(configFolder, newId + ".cfg"); string text2 = Path.Combine(configFolder, oldId + ".cfg"); if (File.Exists(text) || !File.Exists(text2)) { return null; } File.Copy(text2, text, overwrite: false); return "settings carried over from " + oldId + ".cfg to " + newId + ".cfg, as ALIVE's id changed in 0.61.0. The old file is no longer read and may be deleted."; } } public static class OldCopies { public static readonly Version FirstWithNewIds = new Version(0, 61, 0); private static readonly string[] PluginFiles = new string[3] { "ALIVE.Server.dll", "ALIVE.Client.Player.dll", "ALIVE.Client.Admin.dll" }; public static IReadOnlyList<string> Find(string pluginFolder, Func<string, Version?> versionOf) { if (versionOf == null) { throw new ArgumentNullException("versionOf"); } List<string> list = new List<string>(); if (string.IsNullOrEmpty(pluginFolder) || !Directory.Exists(pluginFolder)) { return list; } string[] pluginFiles = PluginFiles; foreach (string searchPattern in pluginFiles) { IEnumerable<string> files; try { files = Directory.GetFiles(pluginFolder, searchPattern, SearchOption.AllDirectories); } catch (Exception ex) when (ex is UnauthorizedAccessException || ex is IOException) { continue; } foreach (string item in files) { Version version = versionOf(item); if (version != null && version < FirstWithNewIds) { list.Add(item); } } } list.Sort(StringComparer.OrdinalIgnoreCase); return list; } public static Version? VersionOfFile(string path) { try { return AssemblyName.GetAssemblyName(path).Version; } catch (Exception ex) when (ex is IOException || ex is BadImageFormatException || ex is UnauthorizedAccessException || ex is ArgumentException || ex is SecurityException) { return null; } } public static string Refusal(string plugin, string version, IReadOnlyList<string> copies) { return plugin + " " + version + " is not starting: an older copy of ALIVE (from before 0.61.0, when its id was net.winterwolf.alive.*) is still in BepInEx/plugins: " + string.Join("; ", copies ?? Array.Empty<string>()) + ". Delete that copy's folder, keep the one your mod manager installed, and start again."; } } public static class AliveNames { public const string Server = "ALIVE Server"; public const string Player = "ALIVE Player"; public const string Admin = "ALIVE Admin"; } public static class AliveWorld { public const string Prefab = "ALIVE_Signpost"; public const string BasePrefab = "piece_banner01"; public const string FallbackPrefab = "sign"; public const string PersonPrefab = "ALIVE_Villager"; public const string PersonBase = "Player"; public const string ModelPrefab = "ALIVE_Model"; public const string ModelBase = "piece_chest_wood"; public const string DvergrShape = "Dverger"; public const string ShapeKey = "alive_shape"; public const string TillPrefab = "ALIVE_Till"; public const string TillBase = "piece_chest_wood"; public const string TillKey = "alive_till"; public const int TillWidth = 8; public const int TillHeight = 4; public const string SubtitleKey = "alive_subtitle"; public const string ModelKey = "alive_model"; public const string HairKey = "alive_hair"; public const string BeardKey = "alive_beard"; public const string SkinKey = "alive_skin"; public const string HairColorKey = "alive_hair_color"; public const string ScaleKey = "alive_scale"; public const string FaceKey = "alive_face"; public const string EquipmentKeyPrefix = "alive_eq_"; public const string EquipmentColorKeyPrefix = "alive_eqc_"; public const string NpcKey = "alive_npc"; public const string NameKey = "alive_name"; public const string PromptKey = "alive_prompt"; public const string HoverKey = "alive_hover"; public const string NoUseKey = "alive_nouse"; public const string LifeKey = "alive_life"; public const string LifeKey2 = "alive_life2"; public const string LifeKey3 = "alive_life3"; public const string LifeKey4 = "alive_life4"; public const string HomeKey = "alive_home"; public const string HomeTurnKey = "alive_home_turn"; public const string LabelShowKey = "alive_label"; public const string LabelTextKey = "alive_label_text"; public const string LabelSubKey = "alive_label_sub"; public const string LabelColorKey = "alive_label_color"; public const string LabelSubColorKey = "alive_label_subcolor"; public const string LabelSizeKey = "alive_label_size"; public const string LabelHeightKey = "alive_label_height"; public const string LabelRangeKey = "alive_label_range"; public const string LabelStyleKey = "alive_label_style"; public const int LabelBold = 1; public const int LabelItalic = 2; public const int LabelOutline = 4; public const string PlacementKey = "alive_placement"; public const string HammerPrefab = "ALIVE_NpcHammer"; public const string HammerBase = "Hammer"; public const string BoardPiecePrefab = "ALIVE_JobBoard"; public const string BoardPieceBase = "sign"; public const string CreatureKey = "alive_creature"; public const string CreatureSpawnKey = "alive_spawn"; public const string CreatureFirstKey = "alive_cr_uid"; public const string CreatureDamageKey = "alive_cr_damage"; public const string CreatureScaleKey = "alive_cr_scale"; public const string CreatureResistKey = "alive_cr_resist"; public const string CreatureFactionKey = "alive_cr_faction"; public const string CreaturePassiveKey = "alive_cr_passive"; public const string CreatureAngryKey = "alive_cr_angry"; public const string CreatureNoDropsKey = "alive_cr_nodrops"; public const string CreatureColorsKey = "alive_cr_colors"; public const string AltarKey = "alive_altar"; public const string SentryKey = "alive_sentry"; public const string FightKey = "alive_fight"; public const string FightWithKey = "alive_fight_with"; public const string DownKey = "alive_down_until"; public const string SentryHealthKey = "alive_sentry_hp"; public const string SentryRestKey = "alive_sentry_rest"; public const string SentryPrefab = "ALIVE_Sentry"; public const string CreatureNoEliteKey = "alive_cr_noelite"; public const string SentryOfKey = "alive_sentry_of"; public const string FightFromKey = "alive_fight_from"; public const string FightKitKey = "alive_fight_kit"; public const string FightDoneKey = "alive_fight_done"; } } namespace ALIVE.Core.Web { public sealed class LocalHttpServer : IDisposable { public const int MaxHeadBytes = 16384; public const int MaxBodyBytes = 4194304; public const int MaxConnections = 8; private const int TimeoutMs = 15000; private readonly Func<LocalRequest, LocalResponse> _handle; private readonly IAliveLog _log; private TcpListener? _listener; private int _open; private volatile bool _stopping; private static readonly string[] LineBreak = new string[1] { "\r\n" }; public int Port { get; private set; } public LocalHttpServer(Func<LocalRequest, LocalResponse> handle, IAliveLog log) { _handle = handle ?? throw new ArgumentNullException("handle"); _log = log ?? throw new ArgumentNullException("log"); } public void Start(int port) { if (_listener != null) { throw new InvalidOperationException("The editor's server is already listening."); } TcpListener tcpListener = new TcpListener(IPAddress.Loopback, port); tcpListener.Start(16); _listener = tcpListener; Port = ((IPEndPoint)tcpListener.LocalEndpoint).Port; Thread thread = new Thread(AcceptLoop); thread.IsBackground = true; thread.Name = "ALIVE web editor"; thread.Start(); } public void Dispose() { _stopping = true; try { _listener?.Stop(); } catch (SocketException) { } _listener = null; } private void AcceptLoop() { while (!_stopping) { TcpClient client; try { TcpListener listener = _listener; if (listener == null) { break; } client = listener.AcceptTcpClient(); } catch (Exception) when (_stopping) { break; } catch (Exception ex2) { _log.Warning("ALIVE web editor: a connection could not be taken: " + ex2.Message); continue; } if (Interlocked.Increment(ref _open) > 8) { Interlocked.Decrement(ref _open); client.Close(); } else { ThreadPool.QueueUserWorkItem(delegate { Serve(client); }); } } } private void Serve(TcpClient client) { try { client.ReceiveTimeout = 15000; client.SendTimeout = 15000; using (client) { using NetworkStream stream = client.GetStream(); string refusal; LocalRequest localRequest = Read(stream, out refusal); LocalResponse response; if (localRequest == null) { response = LocalResponse.Text(400, refusal ?? "That request could not be read."); } else { try { response = _handle(localRequest); } catch (Exception exception) { _log.Failure("ALIVE web editor: answering " + localRequest.Method + " " + localRequest.Path + " failed.", exception); response = LocalResponse.Text(500, "Something went wrong on the server; its log says what."); } } Write(stream, response); } } catch (IOException) { } catch (SocketException) { } catch (ObjectDisposedException) { } finally { Interlocked.Decrement(ref _open); } } public static LocalRequest? Read(Stream stream, out string? refusal) { refusal = null; List<byte> list = new List<byte>(1024); checked { while (!EndsTheHead(list)) { int num = stream.ReadByte(); if (num < 0) { refusal = "The request ended early."; return null; } list.Add((byte)num); if (list.Count > 16384) { refusal = "The request's headers are too long."; return null; } } string[] array = Encoding.ASCII.GetString(list.ToArray(), 0, list.Count - 4).Split(LineBreak, StringSplitOptions.None); string[] array2 = array[0].Split(new char[1] { ' ' }); if (array2.Length != 3 || !array2[2].StartsWith("HTTP/1.", StringComparison.Ordinal)) { refusal = "That is not an HTTP request."; return null; } Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); for (int i = 1; i < array.Length; i++) { int num2 = array[i].IndexOf(':'); if (num2 > 0) { string key = array[i].Substring(0, num2).Trim(); string text = array[i].Substring(num2 + 1).Trim(); dictionary[key] = (dictionary.TryGetValue(key, out var value) ? (value + ", " + text) : text); } } int result = 0; if (dictionary.TryGetValue("Content-Length", out var value2) && (!int.TryParse(value2, NumberStyles.None, CultureInfo.InvariantCulture, out result) || result > 4194304)) { refusal = "The request's body is too large."; return null; } if (dictionary.ContainsKey("Transfer-Encoding")) { refusal = "Chunked requests are not taken; send a Content-Length."; return null; } byte[] array3 = new byte[result]; int num3; for (int j = 0; j < result; j += num3) { num3 = stream.Read(array3, j, result - j); if (num3 <= 0) { refusal = "The request's body ended early."; return null; } } string text2 = array2[1]; int num4 = text2.IndexOf('?'); string stringToUnescape = ((num4 < 0) ? text2 : text2.Substring(0, num4)); return new LocalRequest(array2[0].ToUpperInvariant(), Uri.UnescapeDataString(stringToUnescape), Query((num4 < 0) ? string.Empty : text2.Substring(num4 + 1)), dictionary, Encoding.UTF8.GetString(array3)); } } private static bool EndsTheHead(List<byte> head) { int count = head.Count; checked { if (count >= 4 && head[count - 4] == 13 && head[count - 3] == 10 && head[count - 2] == 13) { return head[count - 1] == 10; } return false; } } private static Dictionary<string, string> Query(string query) { Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.Ordinal); string[] array = query.Split(new char[1] { '&' }); foreach (string text in array) { if (text.Length != 0) { int num = text.IndexOf('='); string key = Uri.UnescapeDataString(((num < 0) ? text : text.Substring(0, num)).Replace('+', ' ')); string value = ((num < 0) ? string.Empty : Uri.UnescapeDataString(text.Substring(checked(num + 1)).Replace('+', ' '))); dictionary[key] = value; } } return dictionary; } private static void Write(Stream stream, LocalResponse response) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("HTTP/1.1 ").Append(response.Status.ToString(CultureInfo.InvariantCulture)).Append(' ') .Append(Reason(response.Status)) .Append("\r\n"); stringBuilder.Append("Content-Type: ").Append(response.ContentType).Append("\r\n"); stringBuilder.Append("Content-Length: ").Append(response.Bytes.Length.ToString(CultureInfo.InvariantCulture)).Append("\r\n"); stringBuilder.Append("Connection: close\r\n"); if (!response.Headers.ContainsKey("Cache-Control")) { stringBuilder.Append("Cache-Control: no-store\r\n"); } stringBuilder.Append("X-Content-Type-Options: nosniff\r\n"); stringBuilder.Append("X-Frame-Options: DENY\r\n"); stringBuilder.Append("Referrer-Policy: no-referrer\r\n"); stringBuilder.Append("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; form-action 'self'\r\n"); foreach (KeyValuePair<string, string> header in response.Headers) { stringBuilder.Append(header.Key).Append(": ").Append(header.Value) .Append("\r\n"); } stringBuilder.Append("\r\n"); byte[] bytes = Encoding.ASCII.GetBytes(stringBuilder.ToString()); stream.Write(bytes, 0, bytes.Length); stream.Write(response.Bytes, 0, response.Bytes.Length); stream.Flush(); } private static string Reason(int status) { return status switch { 200 => "OK", 303 => "See Other", 400 => "Bad Request", 401 => "Unauthorized", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 409 => "Conflict", 413 => "Payload Too Large", 415 => "Unsupported Media Type", 500 => "Internal Server Error", 503 => "Service Unavailable", _ => "Error", }; } } public sealed class LocalRequest { public string Method { get; } public string Path { get; } public IReadOnlyDictionary<string, string> Query { get; } public IReadOnlyDictionary<string, string> Headers { get; } public string Body { get; } public LocalRequest(string method, string path, IReadOnlyDictionary<string, string> query, IReadOnlyDictionary<string, string> headers, string body) { Method = method; Path = path; Query = query; Headers = headers; Body = body; } public string Header(string name) { if (!Headers.TryGetValue(name, out string value)) { return string.Empty; } return value; } public string Cookie(string name) { string[] array = Header("Cookie").Split(new char[1] { ';' }); foreach (string text in array) { int num = text.IndexOf('='); if (num > 0 && string.Equals(text.Substring(0, num).Trim(), name, StringComparison.Ordinal)) { return text.Substring(checked(num + 1)).Trim(); } } return string.Empty; } } public sealed class LocalResponse { public int Status { get; } public string ContentType { get; } public byte[] Bytes { get; } public Dictionary<string, string> Headers { get; } = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); public LocalResponse(int status, string contentType, byte[] body) { Status = status; ContentType = contentType; Bytes = body ?? Array.Empty<byte>(); } public static LocalResponse Text(int status, string text) { return new LocalResponse(status, "text/plain; charset=utf-8", Encoding.UTF8.GetBytes(text ?? string.Empty)); } public static LocalResponse Json(int status, string json) { return new LocalResponse(status, "application/json; charset=utf-8", Encoding.UTF8.GetBytes(json ?? "{}")); } public static LocalResponse Html(int status, string html) { return new LocalResponse(status, "text/html; charset=utf-8", Encoding.UTF8.GetBytes(html ?? string.Empty)); } } public static class LoopbackGate { public enum Verdict { WrongHost, OtherOrigin, ChangeFromElsewhere, Opening, Locked, Through } public const string KeyCookie = "alive_key"; public const string OpeningPage = "<!doctype html><meta charset=\"utf-8\"><title>ALIVE editor</title><meta http-equiv=\"refresh\" content=\"0; url=/\"><script>location.replace(\"/\");</script><body style=\"font-family:sans-serif;background:#16130f;color:#e8dcc4;padding:40px\"><p>Opening the editor. If nothing happens, <a href=\"/\" style=\"color:#d9b45a\">open it here</a>.</p></body>"; public static Verdict Check(LocalRequest request, int port, string key) { if (request == null) { throw new ArgumentNullException("request"); } if (string.IsNullOrEmpty(key)) { return Verdict.Locked; } string text = port.ToString(CultureInfo.InvariantCulture); string a = request.Header("Host"); if (!string.Equals(a, "127.0.0.1:" + text, StringComparison.OrdinalIgnoreCase) && !string.Equals(a, "localhost:" + text, StringComparison.OrdinalIgnoreCase)) { return Verdict.WrongHost; } string text2 = request.Header("Origin"); bool flag = string.Equals(text2, "http://127.0.0.1:" + text, StringComparison.OrdinalIgnoreCase) || string.Equals(text2, "http://localhost:" + text, StringComparison.OrdinalIgnoreCase); if (text2.Length > 0 && !flag) { return Verdict.OtherOrigin; } if (!IsRead(request) && !flag) { return Verdict.ChangeFromElsewhere; } if (request.Path == "/" && request.Query.TryGetValue("key", out string value)) { if (!Same(value, key)) { return Verdict.Locked; } return Verdict.Opening; } if (!Same(request.Cookie("alive_key"), key)) { return Verdict.Locked; } return Verdict.Through; } public static bool IsRead(LocalRequest request) { if (request != null) { if (!(request.Method == "GET")) { return request.Method == "HEAD"; } return true; } return false; } public static LocalResponse Opened(string key) { LocalResponse localResponse = LocalResponse.Html(200, "<!doctype html><meta charset=\"utf-8\"><title>ALIVE editor</title><meta http-equiv=\"refresh\" content=\"0; url=/\"><script>location.replace(\"/\");</script><body style=\"font-family:sans-serif;background:#16130f;color:#e8dcc4;padding:40px\"><p>Opening the editor. If nothing happens, <a href=\"/\" style=\"color:#d9b45a\">open it here</a>.</p></body>"); localResponse.Headers["Set-Cookie"] = "alive_key=" + key + "; Path=/; HttpOnly; SameSite=Strict"; return localResponse; } public static string Link(int port, string key) { return "http://127.0.0.1:" + port.ToString(CultureInfo.InvariantCulture) + "/?key=" + key; } public static bool Same(string? a, string b) { if (a == null || b == null || a.Length != b.Length) { return false; } int num = 0; for (int i = 0; i < a.Length; i = checked(i + 1)) { num |= a[i] ^ b[i]; } return num == 0; } } } namespace ALIVE.Core.Storage { public enum ActivityCategory { Session, Shop, Quest, Dialogue, Economy, Admin, Anticheat, Npc } public sealed class ActivityEntry { public const int MaxDetailChars = 512; public const int MaxSubjectChars = 128; public const int MaxEventChars = 64; public long AtUnixMs { get; init; } public string PlatformId { get; init; } = string.Empty; public ActivityCategory Category { get; init; } public string Event { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string SubjectSub { get; init; } = string.Empty; public string Detail { get; init; } = string.Empty; public int Outcome { get; init; } public int? PosX { get; init; } public int? PosZ { get; init; } public string Correlation { get; init; } = string.Empty; public int Severity { get; init; } } public sealed class ActivityRecord { public long ActivityId { get; } public ActivityEntry Entry { get; } public ActivityRecord(long activityId, ActivityEntry entry) { ActivityId = activityId; Entry = entry ?? throw new ArgumentNullException("entry"); } } public enum TextMatch { None, Exact, Prefix, Contains } public sealed class ActivityQuery { public long FromMs { get; init; } public long ToMs { get; init; } = long.MaxValue; public string PlatformId { get; init; } = string.Empty; public uint Categories { get; init; } public string Text { get; init; } = string.Empty; public TextMatch Match { get; init; } public long? BeforeId { get; init; } public int Limit { get; init; } = 100; } public enum PendingOpState { Pending, Approved, Rejected, Expired, Applied } public sealed class NewPendingOp { public string OpId { get; init; } = string.Empty; public string Action { get; init; } = string.Empty; public string Requester { get; init; } = string.Empty; public string SubjectKind { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string PayloadJson { get; init; } = string.Empty; public string Reason { get; init; } = string.Empty; public long CreatedMs { get; init; } public long ExpiresMs { get; init; } } public sealed class PendingOpRecord { public string OpId { get; init; } = string.Empty; public string Action { get; init; } = string.Empty; public string Requester { get; init; } = string.Empty; public string SubjectKind { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string PayloadJson { get; init; } = string.Empty; public string Reason { get; init; } = string.Empty; public PendingOpState State { get; init; } public string Approver { get; init; } = string.Empty; public string DecideNote { get; init; } = string.Empty; public long CreatedMs { get; init; } public long ExpiresMs { get; init; } public long? DecidedMs { get; init; } } public enum DecideOutcome { Ok, NotFound, AlreadyDecided, Expired, SelfApproval } public sealed class DecideResult { public DecideOutcome Outcome { get; } public PendingOpRecord? Op { get; } public DecideResult(DecideOutcome outcome, PendingOpRecord? op) { Outcome = outcome; Op = op; } } public sealed class QuestDenialRecord { public string PlatformId { get; } public string QuestId { get; } public long? UntilMs { get; } public string Reason { get; } public string Actor { get; } public long CreatedMs { get; } public QuestDenialRecord(string platformId, string questId, long? untilMs, string reason, string actor, long createdMs) { PlatformId = platformId ?? throw new ArgumentNullException("platformId"); QuestId = questId ?? throw new ArgumentNullException("questId"); UntilMs = untilMs; Reason = reason ?? string.Empty; Actor = actor ?? string.Empty; CreatedMs = createdMs; } public bool AppliesAt(long nowMs) { if (UntilMs.HasValue) { return UntilMs.Value > nowMs; } return true; } } public enum AuditTier { System, Super, Admin, Player } public sealed class AuditEntry { public const int MaxSnapshotChars = 4096; public DateTime AtUtc { get; init; } public string Actor { get; init; } = string.Empty; public AuditTier Tier { get; init; } public string Action { get; init; } = string.Empty; public string Permission { get; init; } = string.Empty; public bool Granted { get; init; } = true; public string SubjectKind { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string Before { get; init; } = string.Empty; public string After { get; init; } = string.Empty; public string Reason { get; init; } = string.Empty; public string CorrelationId { get; init; } = string.Empty; } public sealed class AuditRecord { public long AuditId { get; } public AuditEntry Entry { get; } public string RowHash { get; } public AuditRecord(long auditId, AuditEntry entry, string rowHash) { AuditId = auditId; Entry = entry ?? throw new ArgumentNullException("entry"); RowHash = rowHash ?? throw new ArgumentNullException("rowHash"); } } public sealed class AuditVerification { public bool Intact => !FirstBrokenId.HasValue; public long Rows { get; } public long? FirstBrokenId { get; } public string Detail { get; } public AuditVerification(long rows, long? firstBrokenId, string detail) { Rows = rows; FirstBrokenId = firstBrokenId; Detail = detail; } } public static class AuditHash { public static byte[] Genesis => new byte[32]; public static byte[] Compute(byte[] previous, long auditId, AuditEntry e) { if (previous == null || previous.Length != 32) { throw new ArgumentException("The previous hash must be 32 bytes.", "previous"); } if (e == null) { throw new ArgumentNullException("e"); } string[] array = new string[13] { auditId.ToString(CultureInfo.InvariantCulture), e.AtUtc.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture), e.Actor, TierName(e.Tier), e.Action, e.Permission, e.Granted ? "1" : "0", e.SubjectKind, e.SubjectId, e.Before, e.After, e.Reason, e.CorrelationId }; using SHA256 sHA = SHA256.Create(); sHA.TransformBlock(previous, 0, 32, null, 0); string[] array2 = array; foreach (string s in array2) { byte[] bytes = Encoding.UTF8.GetBytes(s); byte[] bytes2 = BitConverter.GetBytes(checked((uint)bytes.Length)); if (!BitConverter.IsLittleEndian) { Array.Reverse((Array)bytes2); } sHA.TransformBlock(bytes2, 0, 4, null, 0); sHA.TransformBlock(bytes, 0, bytes.Length, null, 0); } sHA.TransformFinalBlock(Array.Empty<byte>(), 0, 0); return sHA.Hash; } public static string TierName(AuditTier tier) { return tier switch { AuditTier.Super => "SUPER", AuditTier.Admin => "ADMIN", AuditTier.Player => "PLAYER", _ => "SYSTEM", }; } public static bool TryParseTier(string name, out AuditTier tier) { switch (name) { case "SUPER": tier = AuditTier.Super; return true; case "ADMIN": tier = AuditTier.Admin; return true; case "SYSTEM": tier = AuditTier.System; return true; case "PLAYER": tier = AuditTier.Player; return true; default: tier = AuditTier.System; return false; } } } public sealed class SpawnerPlacementRecord { public long PlacementId { get; init; } public string SpawnerId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public double X { get; init; } public double Y { get; init; } public double Z { get; init; } public double RotY { get; init; } public string ZdoId { get; init; } = string.Empty; public bool Enabled { get; init; } = true; public string PlacedBy { get; init; } = string.Empty; public long PlacedMs { get; init; } public long UpdatedMs { get; init; } public long LastSpawnMs { get; init; } public string SpotKey { get; init; } = string.Empty; } public static class CreatureSpawnKinds { public const string Hand = "hand"; public const string Spawner = "spawner"; public const string Altar = "altar"; public const string Encounter = "encounter"; } public static class CreatureStates { public const string Alive = "alive"; public const string Dead = "dead"; public const string Removed = "removed"; public const string Gone = "gone"; } public sealed class AliveCreatureRecord { public string Uid { get; init; } = string.Empty; public string CreatureId { get; init; } = string.Empty; public string SpawnKind { get; init; } = string.Empty; public long PlacementId { get; init; } public string QuestId { get; init; } = string.Empty; public string Step { get; init; } = string.Empty; public string OwnerPlatformId { get; init; } = string.Empty; public string State { get; init; } = "alive"; public long SpawnedMs { get; init; } public long LastNearMs { get; init; } public long ExpiresMs { get; init; } public double X { get; init; } public double Y { get; init; } public double Z { get; init; } } public enum GrantState { Pending = 1, Offered, Delivered, Mailbox, Stalled, Expired } public static class GrantReasons { public const byte QuestReward = 1; public const byte AdminGift = 2; public const byte Purchase = 3; public const byte Barter = 4; public const byte Withdrawal = 5; public const byte Returned = 6; public const byte Sale = 7; public const byte Effect = 8; } public sealed class GrantItem { public string Prefab { get; init; } = string.Empty; public int Count { get; init; } = 1; public int Quality { get; init; } = 1; public int Variant { get; init; } } public sealed class NewGrant { public string GrantId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public byte Reason { get; init; } public string SourceKind { get; init; } = string.Empty; public string SourceId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public IReadOnlyList<GrantItem> Items { get; init; } = Array.Empty<GrantItem>(); public long CreatedMs { get; init; } public long ExpiresMs { get; init; } } public sealed class GrantRecord { public string GrantId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public byte Reason { get; init; } public string SourceKind { get; init; } = string.Empty; public string SourceId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public IReadOnlyList<GrantItem> Items { get; init; } = Array.Empty<GrantItem>(); public GrantState State { get; init; } public int Attempts { get; init; } public long CreatedMs { get; init; } public long UpdatedMs { get; init; } public long ExpiresMs { get; init; } public string Detail { get; init; } = string.Empty; } public interface IAliveStore : IDisposable { int SchemaVersion { get; } string EngineDescription { get; } void RecordContentLoad(ContentLoadRecord record); IReadOnlyList<ContentLoadRecord> RecentContentLoads(int max); AuditRecord AppendAudit(AuditEntry entry); AuditVerification VerifyAudit(); IReadOnlyList<AuditRecord> RecentAudit(int max); PlayerRecord RecordSessionStart(string platformId, string characterName, long nowMs); void RecordSessionEnd(string platformId, long nowMs); PlayerRecord? FindPlayer(string platformId); IReadOnlyList<PlayerRecord> SearchPlayers(PlayerQuery query); long AppendActivity(ActivityEntry entry); IReadOnlyList<ActivityRecord> SearchActivity(ActivityQuery query); PostResult Post(IReadOnlyList<LedgerPosting> legs, IReadOnlyDictionary<string, LedgerBounds> bounds, IReadOnlyList<ActivityEntry> activity, long nowMs); long Balance(string platformId, string currencyId); IReadOnlyList<WalletRecord> Wallets(string platformId); (int Players, long Total) CurrencyHeld(string currencyId); IReadOnlyList<LedgerRecord> SearchLedger(LedgerQuery query); IReadOnlyList<LedgerRecord> LedgerGroup(string groupId); bool WalletReconciles(string platformId, string currencyId); ReconcileReport Reconcile(long nowMs); QuestInstanceRecord? CreateQuestInstance(NewQuestInstance instance); bool SaveJobPosting(JobPosting posting); JobPosting? LatestJobPosting(long placedId); bool MarkJobHanded(long instanceId, long morning); int JobsHandedSince(string platformId, long fromMorning); int JobsHandedOn(string platformId, long morning); IReadOnlyList<KeyValuePair<string, string>> JobTakers(long placedId, long posting); void RetireJobPostings(long placedId); void StartJobTravel(long instanceId); void SaveJobTravel(long instanceId, double countedMetres); void FreezeJobTravel(long instanceId, double countedMetres, long doneMs); JobTravelRow? JobTravel(long instanceId); IReadOnlyList<JobTravelRow> OpenJobTravel(); bool AddJobDone(string platformId, string boardKey, long nowMs); int JobsDone(string platformId, string boardKey); bool FillJobDoneOnce(IReadOnlyDictionary<long, string> boardKeyByPlacedId, long nowMs); QuestInstanceRecord? QuestInstance(long instanceId); QuestInstanceRecord? OpenQuestInstance(string platformId, string questId); IReadOnlyList<QuestInstanceRecord> SearchQuestInstances(QuestInstanceQuery query); QuestWipe WipeQuest(string platformId, string questId, string note, long nowMs); QuestInstanceRecord ApplyQuestTransition(QuestTransition transition); IReadOnlyList<QuestEventRecord> QuestEvents(long instanceId, int max); bool SetQuestClock(long instanceId, QuestClock clock); bool ClaimObjectiveEffects(string platformId, string questId, string objectiveId, long nowMs, long windowMs); NpcPlacementRecord AddPlacement(NewNpcPlacement placement); IReadOnlyList<NpcPlacementRecord> Placements(bool includeRemoved = false); NpcPlacementRecord? Placement(long placementId); void SetPlacementObject(long placementId, string zdoId, long nowMs); bool MovePlacement(long placementId, double x, double y, double z, double rotY, long nowMs); bool RemovePlacement(long placementId, long nowMs); SpawnerPlacementRecord AddSpawnerPlacement(string spawnerId, string label, double x, double y, double z, double rotY, string placedBy, long nowMs); IReadOnlyList<SpawnerPlacementRecord> SpawnerPlacements(); SpawnerPlacementRecord? SpawnerPlacement(long placementId); bool MoveSpawnerPlacement(long placementId, double x, double y, double z, double rotY, long nowMs); bool RemoveSpawnerPlacement(long placementId); int RemoveSpawnerPlacements(string spawnerId); void SetSpawnerPlacementObject(long placementId, string zdoId, long nowMs); void SetSpawnerPlacementSpawned(long placementId, long nowMs); bool SetSpawnerPlacementSpot(long placementId, string spotKey, long nowMs); void AddAliveCreature(AliveCreatureRecord creature); IReadOnlyList<AliveCreatureRecord> AliveCreatures(); AliveCreatureRecord? AliveCreature(string uid); void SeeAliveCreature(string uid, double x, double y, double z, long lastNearMs); bool RenameAliveCreature(string uid, string newUid); bool EndAliveCreature(string uid, string state, long nowMs); int PurgeEndedCreatures(long endedBeforeMs); GrantRecord AddGrant(NewGrant grant); GrantRecord? Grant(string grantId); IReadOnlyList<GrantRecord> Grants(string platformId, IReadOnlyList<GrantState> states, int limit = 200); int CountGrantsFrom(string sourceKind, string sourceIdPrefix); bool MoveGrant(string grantId, GrantState fromState, GrantState toState, long nowMs, bool countAttempt, string detail); ShopStockRecord? ShopStock(string shopId, string entryId); bool SetShopStock(ShopStockRecord stock, long? expectedRestockedMs); long ShopCredit(string platformId, string shopId); int ShopTradeCount(string platformId, ShopTradeKind kind, string refId, long sinceMs); long LastShopTradeMs(string platformId, ShopTradeKind kind, string refId); bool ApplyPlayerState(PlayerStateChange change); string? RewardRolls(string groupId); bool HasFlag(string platformId, string flagId); void AddCounters(string platformId, IReadOnlyDictionary<string, long> deltas, long atMs); IReadOnlyList<string> Flags(string platformId); IReadOnlyList<HeldFlag> FlagsHeld(string platformId); IReadOnlyList<string> ClearFlags(string platformId, IReadOnlyList<string>? flags); bool GiveFlag(string platformId, string flagId, long atMs); long SetCounter(string platformId, string counterId, long value); IReadOnlyList<KeyValuePair<string, long>> CountersOf(string platformId, string prefix, int most); IReadOnlyList<HeldName> HeldFlags(); IReadOnlyList<HeldName> HeldCounters(string prefix); int CountFlagHolders(string flagId); int CountCounterHolders(string counterId); IReadOnlyList<string> ClearFlagEverywhere(string flagId); IReadOnlyList<string> ClearCounterEverywhere(string counterId); bool DeleteServerSwitch(string switchId); int ForgetPlayerState(string platformId, IReadOnlyList<string> counters, IReadOnlyList<string> counterPrefixes, IReadOnlyList<string> flags); bool ServerSwitchOn(string switchId); IReadOnlyList<ServerSwitchRecord> ServerSwitches(); void SetServerSwitch(string switchId, bool isOn, string actor, long nowMs); IReadOnlyList<string> EditorFolders(); bool AddEditorFolder(string folder, string madeBy, long atMs); bool RemoveEditorFolder(string folder); void RenameEditorFolder(string oldFolder, string newFolder); string? PlayerVar(string platformId, string varId); void SetPlayerVar(string platformId, string varId, string value, long atMs); int CountVarHolders(string varId); IReadOnlyList<string> ClearVarEverywhere(string varId); long Counter(string platformId, string counterId); int Relationship(string platformId, string npcId); void SetRelationship(string platformId, string id, int value, long nowMs); IReadOnlyList<RelationshipRow> RelationshipsWith(string id); int CountRelationshipsWith(string id); int ForgetRelationshipsWith(string id); bool HasUnlock(string platformId, byte kind, string reference); void SetRewardChoice(long instanceId, string platformId, int choice, long atMs); int? RewardChoice(long instanceId); int ShopTradeCountSinceGameDay(string platformId, ShopTradeKind kind, string refId, long fromGameDay); ShopCommitOutcome CommitShopTrade(ShopCommit commit); IReadOnlyDictionary<string, int> SoldByItem(string platformId, SellWindow window); IReadOnlyDictionary<string, int> SoldByItemAt(string platformId, string shopId, SellWindow window); long SoldValue(string platformId, SellWindow window); long MerchantPaid(string shopId, SellWindow window); void SetShopTradeGrant(string tradeId, string grantId); IReadOnlyList<ShopTradeRecord> UngrantedShopTrades(int limit); PendingOpRecord CreatePendingOp(NewPendingOp op); PendingOpRecord? PendingOp(string opId); DecideResult DecidePendingOp(string opId, string approver, bool approve, string note, long nowMs); void MarkPendingOpApplied(string opId, long nowMs); int ExpirePendingOps(long nowMs); void SetQuestDenial(string platformId, string questId, long? untilMs, string reason, string actor, long nowMs); bool ClearQuestDenial(string platformId, string questId); QuestDenialRecord? QuestDenial(string platformId, string questId); IReadOnlyList<QuestDenialRecord> QuestDenials(string platformId); IReadOnlyList<WorldRow> WorldPlaces(); long SaveWorldPlace(long id, string key, string body, string by, long nowMs); bool RemoveWorldPlace(long id); IReadOnlyList<WorldRow> WorldLocks(); long SaveWorldLock(long id, string uid, string body, string by, long nowMs); bool RemoveWorldLock(long id); IReadOnlyList<WorldRow> WorldObjects(); long SaveWorldObject(long id, string uid, string body, string by, long nowMs); bool RemoveWorldObject(long id); IReadOnlyList<WorldRow> WorldSpots(); long SaveWorldSpot(long id, string key, string body, string by, long nowMs); bool RemoveWorldSpot(long id); void RenameWorldThings(bool objects, IReadOnlyList<KeyValuePair<long, string>> names); bool LockOpened(long lockId, string platformId); void MarkLockOpened(long lockId, string platformId, long nowMs); long PlaceSeen(long placeId, string platformId); void MarkPlaceSeen(long placeId, string platformId, long nowMs); } public sealed class ContentLoadRecord { public DateTime AtUtc { get; } public IReadOnlyList<string> Packs { get; } public IReadOnlyList<string> FailedPacks { get; } public int Published { get; } public int Quarantined { get; } public int Errors { get; } public int Warnings { get; } public string ContentHash { get; } public ContentLoadRecord(DateTime atUtc, IReadOnlyList<string> packs, IReadOnlyList<string> failedPacks, int published, int quarantined, int errors, int warnings, string contentHash) { AtUtc = atUtc; Packs = packs ?? throw new ArgumentNullException("packs"); FailedPacks = failedPacks ?? throw new ArgumentNullException("failedPacks"); Published = published; Quarantined = quarantined; Errors = errors; Warnings = warnings; ContentHash = contentHash ?? throw new ArgumentNullException("contentHash"); } } public enum LedgerReason { ShopBuy = 1, ShopSell, Barter, QuestReward, AdminGrant, Decay, Refund, Reconcile, StartingBalance, Deposit, Withdrawal, Penalty, Effect } public enum LedgerSourceKind { None, Shop, Quest, TradeRecipe, Admin, System, Bank } public sealed class LedgerPosting { public string GroupId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public string CurrencyId { get; init; } = string.Empty; public long DeltaMinor { get; init; } public LedgerReason Reason { get; init; } public LedgerSourceKind SourceKind { get; init; } public string SourceId { get; init; } = string.Empty; public string SourceSub { get; init; } = string.Empty; public string Actor { get; init; } = string.Empty; public string Note { get; init; } = string.Empty; public string Correlation { get; init; } = string.Empty; } public sealed class LedgerRecord { public long TxnId { get; } public LedgerPosting Posting { get; } public long BalanceAfterMinor { get; } public long AtUnixMs { get; } public LedgerRecord(long txnId, LedgerPosting posting, long balanceAfterMinor, long atUnixMs) { TxnId = txnId; Posting = posting ?? throw new ArgumentNullException("posting"); BalanceAfterMinor = balanceAfterMinor; AtUnixMs = atUnixMs; } } public sealed class WalletRecord { public string PlatformId { get; } public string CurrencyId { get; } public long BalanceMinor { get; } public long LifetimeInMinor { get; } public long LifetimeOutMinor { get; } public long UpdatedMs { get; } public WalletRecord(string platformId, string currencyId, long balanceMinor, long lifetimeInMinor, long lifetimeOutMinor, long updatedMs) { PlatformId = platformId ?? throw new ArgumentNullException("platformId"); CurrencyId = currencyId ?? throw new ArgumentNullException("currencyId"); BalanceMinor = balanceMinor; LifetimeInMinor = lifetimeInMinor; LifetimeOutMinor = lifetimeOutMinor; UpdatedMs = updatedMs; } } public sealed class LedgerBounds { public long MinMinor { get; } public long MaxMinor { get; } public LedgerBounds(long minMinor, long maxMinor) { if (maxMinor < minMinor) { throw new ArgumentOutOfRangeException("maxMinor", maxMinor, "The ceiling is below the floor."); } MinMinor = minMinor; MaxMinor = maxMinor; } } public enum PostOutcome { Posted, AlreadyPosted, BelowFloor, AboveCeiling, UnknownPlayer, UnknownCurrency } public sealed class PostResult { public PostOutcome Outcome { get; } public bool Accepted { get { if (Outcome != PostOutcome.Posted) { return Outcome == PostOutcome.AlreadyPosted; } return true; } } public IReadOnlyList<LedgerRecord> Legs { get; } public string Detail { get; } public PostResult(PostOutcome outcome, IReadOnlyList<LedgerRecord> legs, string detail) { Outcome = outcome; Legs = legs ?? throw new ArgumentNullException("legs"); Detail = detail ?? string.Empty; } } public sealed class LedgerQuery { public string PlatformId { get; init; } = string.Empty; public string CurrencyId { get; init; } = string.Empty; public long FromMs { get; init; } public long ToMs { get; init; } = long.MaxValue; public long? BeforeId { get; init; } public int Limit { get; init; } = 100; } public sealed class WalletDiscrepancy { public string PlatformId { get; } public string CurrencyId { get; } public long WalletMinor { get; } public long LedgerMinor { get; } public WalletDiscrepancy(string platformId, string currencyId, long walletMinor, long ledgerMinor) { PlatformId = platformId ?? throw new ArgumentNullException("platformId"); CurrencyId = currencyId ?? throw new ArgumentNullException("currencyId"); WalletMinor = walletMinor; LedgerMinor = ledgerMinor; } } public sealed class ReconcileReport { public int WalletsChecked { get; } public IReadOnlyList<WalletDiscrepancy> Repaired { get; } public bool Balanced => Repaired.Count == 0; public ReconcileReport(int walletsChecked, IReadOnlyList<WalletDiscrepancy> repaired) { WalletsChecked = walletsChecked; Repaired = repaired ?? throw new ArgumentNullException("repaired"); } } public sealed class NewNpcPlacement { public string NpcId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public double X { get; init; } public double Y { get; init; } public double Z { get; init; } public double RotY { get; init; } public string PlacedBy { get; init; } = string.Empty; public long PlacedMs { get; init; } } public sealed class NpcPlacementRecord { public long PlacementId { get; init; } public string NpcId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public double X { get; init; } public double Y { get; init; } public double Z { get; init; } public double RotY { get; init; } public string ZdoId { get; init; } = string.Empty; public bool Enabled { get; init; } = true; public string PlacedBy { get; init; } = string.Empty; public long PlacedMs { get; init; } public long UpdatedMs { get; init; } } public sealed class PlayerRecord { public long PlayerId { get; } public string PlatformId { get; } public string CharacterName { get; } public long FirstSeenMs { get; } public long LastSeenMs { get; } public long SessionCount { get; } public PlayerRecord(long playerId, string platformId, string characterName, long firstSeenMs, long lastSeenMs, long sessionCount) { PlayerId = playerId; PlatformId = platformId ?? throw new ArgumentNullException("platformId"); CharacterName = characterName ?? throw new ArgumentNullException("characterName"); FirstSeenMs = firstSeenMs; LastSeenMs = lastSeenMs; SessionCount = sessionCount; } } public enum PlayerQueryKind { PlatformId = 1, NamePrefix } public sealed class PlayerQuery { public PlayerQueryKind Kind { get; init; } = PlayerQueryKind.NamePrefix; public string Text { get; init; } = string.Empty; public string AlternateText { get; init; } = string.Empty; public string? AfterName { get; init; } public string AfterPlatformId { get; init; } = string.Empty; public int Limit { get; init; } = 50; } public static class UnlockKinds { public const byte Quest = 1; public const byte ShopEntry = 2; } public sealed class RelationshipRow { public string PlatformId { get; init; } = string.Empty; public int Value { get; init; } public long ChangedMs { get; init; } } public sealed class PlayerStateChange { public string GroupId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public IReadOnlyList<string> Flags { get; init; } = Array.Empty<string>(); public IReadOnlyList<string> ClearFlags { get; init; } = Array.Empty<string>(); public IReadOnlyDictionary<string, long> Counters { get; init; } = new Dictionary<string, long>(); public IReadOnlyDictionary<string, long> Relationships { get; init; } = new Dictionary<string, long>(); public IReadOnlyList<KeyValuePair<byte, string>> Unlocks { get; init; } = Array.Empty<KeyValuePair<byte, string>>(); public string Rolls { get; init; } = string.Empty; public long AtMs { get; init; } } public static class GrantPrefixes { public const string Skill = "@skill:"; public const string PovTree = "@pov:tree:"; public const string PovProfession = "@pov:prof:"; public static bool IsSkill(string? prefab) { return prefab?.StartsWith("@skill:", StringComparison.Ordinal) ?? false; } public static bool IsPov(string? prefab) { if (prefab != null) { if (!prefab.StartsWith("@pov:tree:", StringComparison.Ordinal)) { return prefab.StartsWith("@pov:prof:", StringComparison.Ordinal); } return true; } return false; } public static bool IsNotItem(string? prefab) { if (!IsSkill(prefab)) { return IsPov(prefab); } return true; } } public enum QuestState { NotOffered, Offered, Active, ReadyToTurnIn, Completed, Failed, Abandoned, Paused, Cooldown, Stale } public enum QuestEventKind { Offered, Accepted, Progress, ObjectiveDone, Ready, Completed, Failed, Abandoned, Paused, Resumed, Stale, Migrated, AdminAdjusted } public enum MigrationPolicy { Snapshot, FollowLive } public sealed class ObjectiveProgress { public string ObjectiveId { get; init; } = string.Empty; public long Current { get; init; } public long Required { get; init; } public long? CompletedMs { get; init; } public bool Optional { get; init; } public int OrderIndex { get; init; } public bool Revealed { get; init; } = true; public bool IsDone => CompletedMs.HasValue; } public static class QuestClockDomains { public const string None = ""; public const string Online = "online"; public const string Real = "real"; public const string World = "world"; } public static class QuestHolds { public const string None = ""; public const string Deadline = "deadline"; public const string Window = "window"; public const string Manual = "manual"; } public sealed class QuestClock { public static QuestClock Empty { get; } = new QuestClock(); public string Domain { get; init; } = ""; public long? DeadlineMs { get; init; } public long? LeftMs { get; init; } public long? WorldDeadlineS { get; init; } public string OnDeadline { get; init; } = string.Empty; public long GraceMs { get; init; } public long BudgetMs { get; init; } public string Hold { get; init; } = ""; public bool HasDeadline => Domain.Length > 0; public bool Running { get { if (!DeadlineMs.HasValue) { return WorldDeadlineS.HasValue; } return true; } } public QuestClock With(long? deadlineMs, long? leftMs, long? worldDeadlineS, string hold) { return new QuestClock { Domain = Domain, DeadlineMs = deadlineMs, LeftMs = leftMs, WorldDeadlineS = worldDeadlineS, OnDeadline = OnDeadline, GraceMs = GraceMs, BudgetMs = BudgetMs, Hold = (hold ?? "") }; } } public sealed class NewQuestInstance { public string PlatformId { get; init; } = string.Empty; public string QuestId { get; init; } = string.Empty; public QuestState State { get; init; } = QuestState.Offered; public int DefinitionVersion { get; init; } public MigrationPolicy Policy { get; init; } public string Snapshot { get; init; } = string.Empty; public long OfferedMs { get; init; } public long? AcceptedMs { get; init; } public long? DeadlineMs { get; init; } public QuestClock? Clock { get; init; } public IReadOnlyList<ObjectiveProgress> Objectives { get; init; } = Array.Empty<ObjectiveProgress>(); public JobTake? Job { get; init; } } public sealed class JobTake { public string Board { get; init; } = string.Empty; public long PlacedId { get; init; } public long Posting { get; init; } public string BoardNpc { get; init; } = string.Empty; public string HandIn { get; init; } = string.Empty; public long? HandedMorning { get; init; } public string Rolled { get; init; } = string.Empty; } public sealed class JobPosting { public const long NeverDue = long.MinValue; public long PlacedId { get; init; } public long Number { get; init; } public long Due { get; init; } public long PostedMs { get; init; } public IReadOnlyList<string> Notices { get; init; } = Array.Empty<string>(); public IReadOnlyDictionary<string, string> Rolls { get; init; } = new Dictionary<string, string>(StringComparer.Ordinal); } public sealed class JobTravelRow { public long InstanceId { get; init; } public double CountedMetres { get; init; } public long? DoneMs { get; init; } } public sealed class QuestInstanceRecord { public long InstanceId { get; init; } public string PlatformId { get; init; } = string.Empty; public string QuestId { get; init; } = string.Empty; public QuestState State { get; init; } public int Attempt { get; init; } = 1; public int DefinitionVersion { get; init; } public MigrationPolicy Policy { get; init; } public string Snapshot { get; init; } = string.Empty; public long? OfferedMs { get; init; } public long? AcceptedMs { get; init; } public long? DeadlineMs { get; init; } public long? CompletedMs { get; init; } public long? LastProgressMs { get; init; } public long? CooldownUntilMs { get; init; } public bool Tracked { get; init; } = true; public string RewardGroupId { get; init; } = string.Empty; public string StaleReason { get; init; } = string.Empty; public QuestClock Clock { get; init; } = QuestClock.Empty; public IReadOnlyList<ObjectiveProgress> Objectives { get; init; } = Array.Empty<ObjectiveProgress>(); public JobTake? Job { get; init; } public bool IsOpen => QuestStates.IsOpen(State); } public sealed class QuestEventRecord { public long EventId { get; } public long InstanceId { get; } public QuestEventKind Kind { get; } public string Detail { get; } public string Actor { get; } public string Correlation { get; } public long AtUnixMs { get; } public QuestEventRecord(long eventId, long instanceId, QuestEventKind kind, string detail, string actor, string correlation, long atUnixMs) { EventId = eventId; InstanceId = instanceId; Kind = kind; Detail = detail ?? string.Empty; Actor = actor ?? string.Empty; Correlation = correlation ?? string.Empty; AtUnixMs = atUnixMs; } } public sealed class QuestTransition { public long InstanceId { get; init; } public QuestState State { get; init; } public QuestEventKind Kind { get; init; } public string Detail { get; init; } = string.Empty; public string Actor { get; init; } = string.Empty; public string Correlation { get; init; } = string.Empty; public long AtUnixMs { get; init; } public long? AcceptedMs { get; init; } public long? DeadlineMs { get; init; } public long? CompletedMs { get; init; } public long? CooldownUntilMs { get; init; } public string? RewardGroupId { get; init; } public string? StaleReason { get; init; } public bool ClearTimestamps { get; init; } public IReadOnlyDictionary<string, long>? Progress { get; init; } public IReadOnlyCollection<string>? Reveal { get; init; } public QuestClock? Clock { get; init; } public bool ClearCooldown { get; init; } } public sealed class QuestInstanceQuery { public string PlatformId { get; init; } = string.Empty; public string QuestId { get; init; } = string.Empty; public IReadOnlyList<QuestState> States { get; init; } = Array.Empty<QuestState>(); public long? BeforeId { get; init; } public int Limit { get; init; } = 100; } public static class QuestStates { public static bool IsOpen(QuestState state) { if (state != QuestState.Offered && state != QuestState.Active && state != QuestState.ReadyToTurnIn && state != QuestState.Paused) { return state == QuestState.Stale; } return true; } public static bool IsTerminal(QuestState state) { if (state != QuestState.Completed && state != QuestState.Failed && state != QuestState.Abandoned) { return state == QuestState.Cooldown; } return true; } public static string Name(QuestState state) { return state switch { QuestState.Offered => "offered", QuestState.Active => "active", QuestState.ReadyToTurnIn => "ready_to_turn_in", QuestState.Completed => "completed", QuestState.Failed => "failed", QuestState.Abandoned => "abandoned", QuestState.Paused => "paused", QuestState.Cooldown => "cooldown", QuestState.Stale => "stale", _ => throw new ArgumentOutOfRangeException("state", state, "NOT_OFFERED is the absence of a row and is never stored."), }; } public static QuestState Parse(string name) { return name switch { "offered" => QuestState.Offered, "active" => QuestState.Active, "ready_to_turn_in" => QuestState.ReadyToTurnIn, "completed" => QuestState.Completed, "failed" => QuestState.Failed, "abandoned" => QuestState.Abandoned, "paused" => QuestState.Paused, "cooldown" => QuestState.Cooldown, "stale" => QuestState.Stale, _ => throw new ArgumentOutOfRangeException("name", name, "Unknown quest state."), }; } public static string EventName(QuestEventKind kind) { return kind switch { QuestEventKind.Offered => "offered", QuestEventKind.Accepted => "accepted", QuestEventKind.Progress => "progress", QuestEventKind.ObjectiveDone => "objective_done", QuestEventKind.Ready => "ready", QuestEventKind.Completed => "completed", QuestEventKind.Failed => "failed", QuestEventKind.Abandoned => "abandoned", QuestEventKind.Paused => "paused", QuestEventKind.Resumed => "resumed", QuestEventKind.Stale => "stale", QuestEventKind.Migrated => "migrated", QuestEventKind.AdminAdjusted => "admin_adjusted", _ => throw new ArgumentOutOfRangeException("kind", kind, "Unknown quest event kind."), }; } public static QuestEventKind ParseEvent(string name) { return name switch { "offered" => QuestEventKind.Offered, "accepted" => QuestEventKind.Accepted, "progress" => QuestEventKind.Progress, "objective_done" => QuestEventKind.ObjectiveDone, "ready" => QuestEventKind.Ready, "completed" => QuestEventKind.Completed, "failed" => QuestEventKind.Failed, "abandoned" => QuestEventKind.Abandoned, "paused" => QuestEventKind.Paused, "resumed" => QuestEventKind.Resumed, "stale" => QuestEventKind.Stale, "migrated" => QuestEventKind.Migrated, "admin_adjusted" => QuestEventKind.AdminAdjusted, _ => throw new ArgumentOutOfRangeException("name", name, "Unknown quest event kind."), }; } } public enum ShopTradeKind { Buy = 1, Barter, Sell } public sealed class ShopStockRecord { public string ShopId { get; init; } = string.Empty; public string EntryId { get; init; } = string.Empty; public int Qty { get; init; } public long RestockedMs { get; init; } } public sealed class ShopTradePart { public byte Kind { get; init; } public string Id { get; init; } = string.Empty; public long Amount { get; init; } } public sealed class ShopTradeRecord { public const string NoGrant = "-"; public string TradeId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public string ShopId { get; init; } = string.Empty; public string NpcId { get; init; } = string.Empty; public ShopTradeKind Kind { get; init; } public string RefId { get; init; } = string.Empty; public int Qty { get; init; } public IReadOnlyList<ShopTradePart> Paid { get; init; } = Array.Empty<ShopTradePart>(); public IReadOnlyList<ShopTradePart> Got { get; init; } = Array.Empty<ShopTradePart>(); public long CreditBefore { get; init; } public long CreditAfter { get; init; } public string GrantId { get; init; } = string.Empty; public long GameDay { get; init; } = -1L; public long ValueVu { get; init; } public long AtMs { get; init; } } public enum ShopCommitOutcome { Committed = 1, OutOfStock, CreditChanged } public sealed class ShopCommit { public ShopTradeRecord Trade { get; init; } = new ShopTradeRecord(); public int StockTake { get; init; } public string StockEntryId { get; init; } = string.Empty; public long CreditExpected { get; init; } public IReadOnlyList<ActivityEntry> Activity { get; init; } = Array.Empty<ActivityEntry>(); } public sealed class SellWindow { public long SinceMs { get; init; } public long FromGameDay { get; init; } = -1L; } public sealed class ServerSwitchRecord { public string SwitchId { get; init; } = string.Empty; public bool On { get; init; } public long ChangedMs { get; init; } public string ChangedBy { get; init; } = string.Empty; } public sealed class HeldName { public string Name { get; init; } = string.Empty; public int Holders { get; init; } } public sealed class HeldFlag { public string FlagId { get; init; } = string.Empty; public long SetMs { get; init; } } public sealed class QuestWipe { public IReadOnlyList<long> Instances { get; init; } = Array.Empty<long>(); public int Events { get; init; } public int GrantsClosed { get; init; } } public sealed class WorldRow { public long Id { get; init; } public string Key { get; init; } = string.Empty; public string Body { get; init; } = string.Empty; public string UpdatedBy { get; init; } = string.Empty; public long UpdatedMs { get; init; } } } namespace ALIVE.Core.Protocol { public static class AliveProtocol { public const ushort ProtoVersion = 1; public const byte EnvelopeVersion = 1; public const ushort Magic = 42782; public const int MaxFrameBytes = 8192; public const int MaxPayloadBytes = 4194304; public const int MaxPayloadBytesC2S = 262144; public const int MaxChunks = 64; public const int MaxChunksC2S = 8; public const int CompressMinBytes = 512; public const int MaxStringBytes = 4096; public const int MaxCollectionSize = 1024; public const string RpcChannelServer = "ALIVE.s2c"; public const string RpcChannelPlayer = "ALIVE.c2s.player"; public const string RpcChannelAdmin = "ALIVE.c2s.admin"; } public static class AttestationDigest { public const byte SpecNonceThenFile = 1; public static ByteString Response(ByteString serverNonce, byte[] fileBytes) { if (serverNonce == null) { throw new ArgumentNullException("serverNonce"); } if (fileBytes == null) { throw new ArgumentNullException("fileBytes"); } using SHA256 sHA = SHA256.Create(); sHA.TransformBlock(serverNonce.Raw, 0, serverNonce.Length, null, 0); sHA.TransformFinalBlock(fileBytes, 0, fileBytes.Length); return ByteString.Own(sHA.Hash); } public static ByteString Combined(IReadOnlyList<ByteString> responses) { if (responses == null) { throw new ArgumentNullException("responses"); } WireWriter wireWriter = new WireWriter(); foreach (ByteString response in responses) { wireWriter.WriteRaw(response); } return Sha256(wireWriter.ToArray()); } public static ByteString PluginSet(IReadOnlyList<PluginReport> plugins) { if (plugins == null) { throw new ArgumentNullException("plugins"); } WireWriter wireWriter = new WireWriter(); foreach (PluginReport plugin in plugins) { wireWriter.WriteRaw(ByteString.Own(Encoding.UTF8.GetBytes(plugin.PluginId))); wireWriter.WriteU8(0); wireWriter.WriteRaw(ByteString.Own(Encoding.UTF8.GetBytes(plugin.Version))); wireWriter.WriteU8(0); wireWriter.WriteRaw(plugin.FileHash); } return Sha256(wireWriter.ToArray()); } private static ByteString Sha256(byte[] data) { using SHA256 sHA = SHA256.Create(); return ByteString.Own(sHA.ComputeHash(data)); } } public sealed class ByteString : IEquatable<ByteString> { private readonly byte[] _bytes; public static ByteString Empty { get; } = new ByteString(Array.Empty<byte>()); public int Length => _bytes.Length; public byte this[int index] => _bytes[index]; public bool IsAllZero { get { byte[] bytes = _bytes; for (int i = 0; i < bytes.Length; i++) { if (bytes[i] != 0) { return false; } } return true; } } internal byte[] Raw => _bytes; private ByteString(byte[] owned) { _bytes = owned; } public static ByteString CopyFrom(byte[] bytes) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (bytes.Length != 0) { return new ByteString((byte[])bytes.Clone()); } return Empty; } public static ByteString CopyFrom(byte[] bytes, int offset, int count) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (offset < 0 || count < 0 || offset > checked(bytes.Length - count)) { throw new ArgumentOutOfRangeException("count"); } if (count == 0) { return Empty; } byte[] array = new byte[count]; Buffer.BlockCopy(bytes, offset, array, 0, count); return new ByteString(array); } public static ByteString Zeros(int length) { if (length != 0) { return new ByteString(new byte[length]); } return Empty; } internal static ByteString Own(byte[] bytes) { if (bytes.Length != 0) { return new ByteString(bytes); } return Empty; } public byte[] ToArray() { return (byte[])_bytes.Clone(); } public bool FixedTimeEquals(ByteString? other) { if (other == null || other._bytes.Length != _bytes.Length) { return false; } int num = 0; for (int i = 0; i < _bytes.Length; i = checked(i + 1)) { num |= _bytes[i] ^ other._bytes[i]; } return num == 0; } internal void CopyTo(byte[] destination, int offset) { Buffer.BlockCopy(_bytes, 0, destination, offset, _bytes.Length); } public bool Equals(ByteString? other) { return FixedTimeEquals(other); } public override bool Equals(object? obj) { if (obj is ByteString other) { return FixedTimeEquals(other); } return false; } public override int GetHashCode() { int num = -2128831035; byte[] bytes = _bytes; foreach (byte b in bytes) { num = (num ^ b) * 16777619; } return num; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(checked(_bytes.Length * 2)); byte[] bytes = _bytes; foreach (byte b in bytes) { stringBuilder.Append(b.ToString("x2", CultureInfo.InvariantCulture)); } return stringBuilder.ToString(); } } public static class Crc32C { private const uint Polynomial = 2197175160u; private static readonly uint[] Table = BuildTable(); public static uint Compute(byte[] data, int offset, int count) { if (data == null) { throw new ArgumentNullException("data"); } checked { if (offset < 0 || count < 0 || offset > data.Length - count) { throw new ArgumentOutOfRangeException("count"); } uint num = uint.MaxValue; int num2 = offset + count; for (int i = offset; i < num2; i++) { num = Table[(num ^ data[i]) & 0xFF] ^ (num >> 8); } return ~num; } } private static uint[] BuildTable() { uint[] array = new uint[256]; checked { for (uint num = 0u; num < 256; num++) { uint num2 = num; for (int i = 0; i < 8; i++) { num2 = (((num2 & 1) != 0) ? (0x82F63B78u ^ (num2 >> 1)) : (num2 >> 1)); } array[num] = num2; } return array; } } } public enum DecodeOutcome { Complete, Pending, Dropped, Rejected } public sealed class DecodeResult { public DecodeOutcome Outcome { get; } public ErrorCode Error { get; } public bool HardSignal { get; } public string Detail { get; } public FrameHeader? Header { get; } public ByteString? Payload { get; } private DecodeResult(DecodeOutcome outcome, ErrorCode error, bool hardSignal, string detail, FrameHeader? header, ByteString? payload) { Outcome = outcome; Error = error; HardSignal = hardSignal; Detail = detail; Header = header; Payload = payload; } internal static DecodeResult Complete(FrameHeader header, ByteString payload) { return new DecodeResult(DecodeOutcome.Complete, ErrorCode.None, hardSignal: false, string.Empty, header, payload); } internal static DecodeResult Pending() { return new DecodeResult(DecodeOutcome.Pending, ErrorCode.None, hardSignal: false, string.Empty, null, null); } internal static DecodeResult Dropped(string detail) { return new DecodeResult(DecodeOutcome.Dropped, ErrorCode.None, hardSignal: false, detail, null, null); } internal static DecodeResult Reject(ErrorCode error, bool hard, string detail) { return new DecodeResult(DecodeOutcome.Rejected, error, hard, detail, null, null); } } public static class Envelope { public const int HeaderBytes = 44; public const int ChunkHeaderBytes = 12; public const int CrcBytes = 4; public const int IdemKeyBytes = 16; public const byte FlagCompressed = 1; public const byte FlagChunk = 2; public const byte FlagAdmin = 4; public const byte ReservedFlags = 248; public static int SingleBodyLimit(int maxFrameBytes) { return checked(maxFrameBytes - 44 - 4); } public static int ChunkBodyLimit(int maxFrameBytes) { return checked(maxFrameBytes - 44 - 12 - 4); } } public enum ErrorCode { None = 0, Malformed = 1000, UnsupportedEnvVersion = 1001, ReservedBitsSet = 1002, TrailingBytes = 1003, WrongDirection = 1004, UnknownMsgType = 1005, SizeLimit = 1006, SenderIdMismatch = 1007, BadCrc = 1008, UnsupportedMsgVersion = 1009, NoSession = 2001, NotReady = 2002, SessionExpired = 2003, SessionMismatch = 2004, ProtoVersionMismatch = 2101, AttestationFailed = 2102, DualClientDetected = 2103, PluginPolicyDenied = 2104, AttestTimeout = 2105, SyncTimeout = 2106, ClientRequired = 2107, Banned = 2108, ServerFullAlive = 2109, ClientVersionMismatch = 2110, FieldInvalid = 3001, NotFound = 3002, QtyOutOfRange = 3003, ItemNotAllowed = 3004, StringTooLong = 3011, ContentSchemaInvalid = 3006, ContentBoundsExceeded = 3007, CollectionTooLarge = 3012, CharsetViolation = 3013, IdempotencyConflict = 3009, IdempotencyMissing = 3010, NotAuthorized = 4001, NotOwner = 4002, NotOffered = 4003, OutOfRange = 4005, OptionNotOffered = 4009, DualControlRequired = 4011, SuperAdminRequired = 4012, SelfApprovalForbidden = 4013, ShopClosed = 5001, StaleVersion = 5002, PriceChanged = 5003, OutOfStock = 5004, InsufficientFunds = 5005, ObjectivesIncomplete = 5006, NotActive = 5010, AlreadyCompleted = 5011, InstanceNotFound = 5016, NothingToRevoke = 5017, ApprovalExpired = 5020, LimitReached = 5021, RateLimited = 6001, BurstLimited = 6002, MemoryBudget = 6004, Internal = 7001 } public static class FieldRules { public static bool IsVersion(string? value) { if (value == null || value.Length == 0 || value.Length > 32) { return false; } int i = 0; int num = 0; checked { while (true) { int num2 = i; for (; i < value.Length && value[i] >= '0' && value[i] <= '9'; i++) { } int num3 = i - num2; if (num3 < 1 || num3 > 5) { return false; } num++; if (i == value.Length) { return num <= 4; } if (value[i] != '.' || num >= 4) { break; } i++; } if (value[i] != '-') { return false; } int num4 = value.Length - i - 1; if (num4 < 1 || num4 > 16) { return false; } for (int j = i + 1; j < value.Length; j++) { char c = value[j]; if ((c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '.') { return false; } } return true; } } public static bool IsPluginId(string? value) { return IsToken(value, 128, allowUpper: true, leadingUnderscore: true); } public static bool IsIdentifier(string? value) { return IsToken(value, 64, allowUpper: false); } public static bool IsBuildId(string? value) { if (value != null) { if (value.Length != 0) { return IsToken(value, 40, allowUpper: true); } return true; } return false; } private static bool IsToken(string? value, int max, bool allowUpper, bool leadingUnderscore = false) { if (value == null || value.Length == 0 || value.Length > max) { return false; } for (int i = 0; i < value.Length; i = checked(i + 1)) { char c = value[i]; if ((c < 'a' || c > 'z') && (c < '0' || c > '9') && (!allowUpper || c < 'A' || c > 'Z') && (i <= 0 || (c != '.' && c != '_' && c != '-')) && (!(i == 0 && leadingUnderscore) || c != '_')) { return false; } } return true; } } public sealed class Frame { public FrameHeader Header { get; } public bool Compressed { get; } public int PayloadLength { get; } public ChunkInfo? Chunk { get; } public ByteString Body { get; } internal Frame(FrameHeader header, bool compressed, int payloadLength, ChunkInfo? chunk, ByteString body) { Header = header; Compressed = compressed; PayloadLength = payloadLength; Chunk = chunk; Body = body; } } public sealed class ChunkInfo { public uint ChunkId { get; } public int Index { get; } public int Count { get; } public int TotalLength { get; } internal ChunkInfo(uint chunkId, int index, int count, int totalLength) { ChunkId = chunkId; Index = index; Count = count; TotalLength = totalLength; } } public static class FrameCodec { public static IReadOnlyList<byte[]> Encode(FrameHeader header, ByteString payload, FrameLimits limits, uint chunkId) { if (header == null) { throw new ArgumentNullException("header"); } if (payload == null) { throw new ArgumentNullException("payload"); } if (limits == null) { throw new ArgumentNullException("limits"); } if (header.IdemKey == null || header.IdemKey.Length != 16) { throw new ArgumentException("The idempotency key must be 16 bytes.", "header"); } if (payload.Length > limits.MaxPayloadBytes) { throw new ArgumentOutOfRangeException("payload", "Payload of " + payload.Length + " bytes exceeds the limit of " + limits.MaxPayloadBytes + "."); } bool flag = false; byte[] array = payload.Raw; if (payload.Length >= 512) { byte[] array2 = Deflate(array); if (array2.Length < array.Length) { array = array2; flag = true; } } byte b = checked((byte)((flag ? 1 : 0) | (header.Admin ? 4 : 0))); if (array.Length <= Envelope.SingleBodyLimit(limits.MaxFrameBytes)) { return new byte[1][] { Build(header, b, payload.Length, null, array, 0, array.Length) }; } int num = Envelope.ChunkBodyLimit(limits.MaxFrameBytes); int num2 = checked(array.Length + num - 1) / num; if (num2 > limits.MaxChunks) { throw new ArgumentOutOfRangeException("payload", "Payload needs " + num2 + " chunks; the limit is " + limits.MaxChunks + "."); } byte[][] array3 = new byte[num2][]; checked { for (int i = 0; i < num2; i++) { int num3 = i * num; int length = Math.Min(num, array.Length - num3); array3[i] = Build(header, (byte)(b | 2), payload.Length, new ChunkInfo(chunkId, i, num2, array.Length), array, num3, length); } return array3; } } public static bool TryDecode(byte[]? frame, FrameLimits limits, [NotNullWhen(true)] out Frame? decoded, [NotNullWhen(false)] out DecodeResult? failure) { decoded = null; failure = Check(frame, limits); if (failure != null) { return false; } Frame decoded2; DecodeResult decodeResult = Parse(frame, limits, out decoded2); if (decodeResult != null || decoded2 == null) { failure = decodeResult ?? DecodeResult.Reject(ErrorCode.Malformed, hard: true, "The envelope could not be read."); return false; } decoded = decoded2; failure = null; return true; } private static DecodeResult? Check(byte[]? frame, FrameLimits limits) { if (limits == null) { throw new ArgumentNullException("limits"); } if (frame == null || frame.Length < 2) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Frame is too short to hold an envelope."); } if ((frame[0] | (frame[1] << 8)) != 42782) { return DecodeResult.Dropped("Not an ALIVE frame (magic mismatch)."); } if (frame.Length < 48) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Frame of " + frame.Length + " bytes is shorter than an envelope."); } if (frame.Length > limits.MaxFrameBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Frame of " + frame.Length + " bytes exceeds the limit of " + limits.MaxFrameBytes + "."); } int num = checked(frame.Length - 4); WireReader wireReader = new WireReader(frame, num, 4); if (wireReader.ReadU32() != Crc32C.Compute(frame, 0, num)) { return DecodeResult.Reject(ErrorCode.BadCrc, hard: false, "CRC mismatch: the frame was corrupted or truncated."); } return null; } private static DecodeResult? Parse(byte[] frame, FrameLimits limits, out Frame? decoded) { decoded = null; checked { int num = frame.Length - 4; try { WireReader wireReader = new WireReader(frame, 2, num - 2); byte b = wireReader.ReadU8(); if (b != 1) { return DecodeResult.Reject(ErrorCode.UnsupportedEnvVersion, hard: false, "Envelope version " + b + " is not supported."); } byte b2 = wireReader.ReadU8(); if ((b2 & 0xF8) != 0) { return DecodeResult.Reject(ErrorCode.ReservedBitsSet, hard: true, "Reserved flag bits were set."); } ushort msgType = wireReader.ReadU16(); byte msgVersion = wireReader.ReadU8(); if (wireReader.ReadU8() != 0) { return DecodeResult.Reject(ErrorCode.ReservedBitsSet, hard: true, "The reserved header byte was not zero."); } uint seq = wireReader.ReadU32(); uint ackSeq = wireReader.ReadU32(); ulong sessionId = wireReader.ReadU64(); ByteString idemKey = wireReader.ReadFixed(16); uint num2 = wireReader.ReadU32(); if (num2 > (uint)limits.MaxPayloadBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Declared payload of " + num2 + " bytes exceeds the limit of " + limits.MaxPayloadBytes + "."); } ChunkInfo chunk = null; if ((b2 & 2) != 0) { uint chunkId = wireReader.ReadU32(); ushort num3 = wireReader.ReadU16(); ushort num4 = wireReader.ReadU16(); uint num5 = wireReader.ReadU32(); if (num4 == 0 || num4 > limits.MaxChunks) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunk count " + num4 + " is outside 1-" + limits.MaxChunks + "."); } if (num3 >= num4) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Chunk index " + num3 + " is not below the count " + num4 + "."); } if (num5 == 0 || num5 > limits.MaxChunkedBodyBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunked body of " + num5 + " bytes is outside the limit."); } if (wireReader.Remaining == 0) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "A chunk frame carried no bytes."); } chunk = new ChunkInfo(chunkId, num3, num4, (int)num5); } FrameHeader header = new FrameHeader { Admin = ((b2 & 4) != 0), MsgType = msgType, MsgVersion = msgVersion, Seq = seq, AckSeq = ackSeq, SessionId = sessionId, IdemKey = idemKey }; decoded = new Frame(header, (b2 & 1) != 0, (int)num2, chunk, wireReader.ReadRest()); return null; } catch (WireException ex) { return DecodeResult.Reject(ex.Code, hard: true, ex.Message); } } } public static DecodeResult DecodeSingle(byte[]? frame, FrameLimits limits) { if (!TryDecode(frame, limits, out Frame decoded, out DecodeResult failure)) { return failure; } if (decoded.Chunk != null) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "A chunk arrived where a single frame was required."); } return Open(decoded.Header, decoded.Body.Raw, decoded.Compressed, decoded.PayloadLength); } internal static DecodeResult Open(FrameHeader header, byte[] body, bool compressed, int payloadLength) { if (!compressed) { if (body.Length != payloadLength) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Payload is " + body.Length + " bytes but declared " + payloadLength + "."); } return DecodeResult.Complete(header, ByteString.Own(body)); } checked { try { byte[] array = new byte[payloadLength]; using (MemoryStream stream = new MemoryStream(body, writable: false)) { using DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress); int i; int num; for (i = 0; i < payloadLength; i += num) { num = deflateStream.Read(array, i, payloadLength - i); if (num == 0) { break; } } if (i != payloadLength) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Compressed payload inflated to " + i + " bytes but declared " + payloadLength + "."); } byte[] buffer = new byte[1]; if (deflateStream.Read(buffer, 0, 1) != 0) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Compressed payload inflates beyond its declared " + payloadLength + " bytes."); } } return DecodeResult.Complete(header, ByteString.Own(array)); } catch (Exception ex) when (ex is InvalidDataException || ex is IOException || ex is NotSupportedException) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Compressed payload is not valid deflate: " + ex.Message); } } } private static byte[] Deflate(byte[] data) { using MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal, leaveOpen: true)) { deflateStream.Write(data, 0, data.Length); } return memoryStream.ToArray(); } private static byte[] Build(FrameHeader h, byte flags, int payloadLength, ChunkInfo? chunk, byte[] body, int offset, int length) { checked { WireWriter wireWriter = new WireWriter(56 + length + 4); wireWriter.WriteU16(42782); wireWriter.WriteU8(1); wireWriter.WriteU8(flags); wireWriter.WriteU16(h.MsgType); wireWriter.WriteU8(h.MsgVersion); wireWriter.WriteU8(0); wireWriter.WriteU32(h.Seq); wireWriter.WriteU32(h.AckSeq); wireWriter.WriteU64(h.SessionId); wireWriter.WriteFixed(h.IdemKey, 16); wireWriter.WriteU32((uint)payloadLength); if (chunk != null) { wireWriter.WriteU32(chunk.ChunkId); wireWriter.WriteU16((ushort)chunk.Index); wireWriter.WriteU16((ushort)chunk.Count); wireWriter.WriteU32((uint)chunk.TotalLength); } wireWriter.WriteRaw(ByteString.CopyFrom(body, offset, length)); byte[] array = wireWriter.ToArray(); wireWriter.WriteU32(Crc32C.Compute(array, 0, array.Length)); return wireWriter.ToArray(); } } } public sealed class FrameHeader { public bool Admin { get; init; } public ushort MsgType { get; init; } public byte MsgVersion { get; init; } = 1; public uint Seq { get; init; } public uint AckSeq { get; init; } public ulong SessionId { get; init; } public ByteString IdemKey { get; init; } = ByteString.Zeros(16); public bool SameAs(FrameHeader other) { if (other != null && Admin == other.Admin && MsgType == other.MsgType && MsgVersion == other.MsgVersion && Seq == other.Seq && AckSeq == other.AckSeq && SessionId == other.SessionId) { return IdemKey.FixedTimeEquals(other.IdemKey); } return false; } } public sealed class FrameLimits { public static FrameLimits ServerToClient { get; } = new FrameLimits(8192, 4194304, 64); public static FrameLimits ClientToServer { get; } = new FrameLimits(8192, 262144, 8); public int MaxFrameBytes { get; } public int MaxPayloadBytes { get; } public int MaxChunks { get; } public long MaxChunkedBodyBytes { get { checked { return unchecked((long)MaxChunks) * unchecked((long)Envelope.ChunkBodyLimit(MaxFrameBytes)); } } } public FrameLimits(int maxFrameBytes, int maxPayloadBytes, int maxChunks) { if (maxFrameBytes < 1024) { throw new ArgumentOutOfRangeException("maxFrameBytes", "The protocol needs frames of at least 1 KiB."); } if (maxPayloadBytes < 1) { throw new ArgumentOutOfRangeException("maxPayloadBytes"); } if (maxChunks < 1 || maxChunks > 65535) { throw new ArgumentOutOfRangeException("maxChunks"); } MaxFrameBytes = maxFrameBytes; MaxPayloadBytes = maxPayloadBytes; MaxChunks = maxChunks; } } public sealed class FrameReceiver { private readonly FrameLimits _limits; public Reassembler Chunks { get; } public FrameReceiver(FrameLimits limits) { _limits = limits ?? throw new ArgumentNullException("limits"); Chunks = new Reassembler(limits, 4, 30000L, 8388608L); } public DecodeResult Receive(byte[]? frame, long nowMs) { if (!FrameCodec.TryDecode(frame, _limits, out Frame decoded, out DecodeResult failure)) { return failure; } if (decoded.Chunk != null) { return Chunks.Accept(decoded, nowMs); } return FrameCodec.Open(decoded.Header, decoded.Body.Raw, decoded.Compressed, decoded.PayloadLength); } } public sealed class Reassembler { private sealed class Pending { internal Frame First { get; } internal long StartedMs { get; } internal long Order { get; } internal ByteString?[] Parts { get; } internal int Received { get; set; } internal int Bytes { get; set; } internal Pending(Frame first, long startedMs, long order) { First = first; StartedMs = startedMs; Order = order; Parts = new ByteString[first.Chunk.Count]; } internal bool Matches(Frame f) { ChunkInfo chunk = First.Chunk; ChunkInfo chunk2 = f.Chunk; if (chunk.Count == chunk2.Count && chunk.TotalLength == chunk2.TotalLength && First.Compressed == f.Compressed && First.PayloadLength == f.PayloadLength) { return First.Header.SameAs(f.Header); } return false; } } public const int DefaultMaxConcurrent = 4; public const long DefaultTtlMs = 30000L; public const long DefaultMemoryBudget = 8388608L; private readonly FrameLimits _limits; private readonly int _maxConcurrent; private readonly long _ttlMs; private readonly long _memoryBudget; private readonly Dictionary<uint, Pending> _pending = new Dictionary<uint, Pending>(); private long _order; public int PendingCount => _pending.Count; public long BufferedBytes { get; private set; } public int Evictions { get; private set; } public int Expirations { get; private set; } public Reassembler(FrameLimits limits, int maxConcurrent = 4, long ttlMs = 30000L, long memoryBudget = 8388608L) { _limits = limits ?? throw new ArgumentNullException("limits"); if (maxConcurrent < 1) { throw new ArgumentOutOfRangeException("maxConcurrent"); } if (ttlMs < 1) { throw new ArgumentOutOfRangeException("ttlMs"); } if (memoryBudget < 1) { throw new ArgumentOutOfRangeException("memoryBudget"); } _maxConcurrent = maxConcurrent; _ttlMs = ttlMs; _memoryBudget = memoryBudget; } public DecodeResult Accept(Frame frame, long nowMs) { if (frame == null) { throw new ArgumentNullException("frame"); } ChunkInfo chunkInfo = frame.Chunk ?? throw new ArgumentException("Not a chunk frame.", "frame"); if (chunkInfo.Count > _limits.MaxChunks || frame.PayloadLength > _limits.MaxPayloadBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunked message " + chunkInfo.ChunkId + " exceeds this direction's limits."); } Expire(nowMs); checked { if (!_pending.TryGetValue(chunkInfo.ChunkId, out Pending value)) { while (_pending.Count >= _maxConcurrent) { Pending p = (from x in _pending.Values orderby x.StartedMs, x.Order select x).First(); Remove(p); Evictions++; } value = new Pending(frame, nowMs, _order++); _pending.Add(chunkInfo.ChunkId, value); } else if (!value.Matches(frame)) { Remove(value); return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Chunk " + chunkInfo.Index + " of message " + chunkInfo.ChunkId + " changed the message's header or chunk count mid-stream."); } ByteString byteString = value.Parts[chunkInfo.Index]; if (byteString != null) { if (byteString.FixedTimeEquals(frame.Body)) { return DecodeResult.Pending(); } Remove(value); return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Chunk " + chunkInfo.Index + " of message " + chunkInfo.ChunkId + " arrived twice with different bytes."); } if (BufferedBytes + frame.Body.Length > _memoryBudget) { Clear(); long memoryBudget = _memoryBudget; return DecodeResult.Reject(ErrorCode.MemoryBudget, hard: false, "Reassembly memory budget of " + memoryBudget + " bytes exhausted; all partial messages dropped."); } if (value.Bytes + frame.Body.Length > chunkInfo.TotalLength) { Remove(value); return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunks of message " + chunkInfo.ChunkId + " exceed its declared " + chunkInfo.TotalLength + " bytes."); } value.Parts[chunkInfo.Index] = frame.Body; value.Received++; value.Bytes += frame.Body.Length; BufferedBytes += frame.Body.Length; if (value.Received < chunkInfo.Count) { return DecodeResult.Pending(); } Remove(value); if (value.Bytes != chunkInfo.TotalLength) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Message " + chunkInfo.ChunkId + " reassembled to " + value.Bytes + " bytes but declared " + chunkInfo.TotalLength + "."); } byte[] array = new byte[value.Bytes]; int num = 0; ByteString[] parts = value.Parts; foreach (ByteString byteString2 in parts) { byteString2.CopyTo(array, num); num += byteString2.Length; } return FrameCodec.Open(value.First.Header, array, value.First.Compressed, value.First.PayloadLength); } } public void Expire(long nowMs) { checked { foreach (Pending item in _pending.Values.Where((Pending x) => nowMs - x.StartedMs > _ttlMs).ToList()) { Remove(item); Expirations++; } } } public void Clear() { _pending.Clear(); BufferedBytes = 0L; } private void Remove(Pending p) { checked { if (_pending.Remove(p.First.Chunk.ChunkId)) { BufferedBytes -= p.Bytes; } } } } public sealed class ReplayWindow { public const int Width = 64; private ulong _seen; public uint Highest { get; private set; } public long Rejected { get; private set; } public bool Accept(uint seq) { uint num2; checked { if (seq == 0) { Rejected++; return false; } if (seq > Highest) { uint num = seq - Highest; _seen = ((num >= 64) ? 0 : (_seen << (int)num)); _seen |= 1uL; Highest = seq; return true; } num2 = Highest - seq; if (num2 >= 64) { Rejected++; return false; } } ulong num3 = (ulong)(1L << checked((int)num2)); checked { if ((_seen & num3) != 0L) { Rejected++; return false; } _seen |= num3; return true; } } } public sealed class WireException : Exception { public ErrorCode Code { get; } = ErrorCode.Malformed; public WireException() { } public WireException(string message) : base(message) { } public WireException(string message, Exception innerException) : base(message, innerException) { } public WireException(ErrorCode code, string message) : base(message) { Code = code; } } public sealed class WireReader { private static readonly UTF8Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private readonly byte[] _buffer; private readonly int _end; private int _position; public int Remaining => checked(_end - _position); public WireReader(byte[] buffer) : this(buffer, 0, (buffer != null) ? buffer.Length : 0) { } public WireReader(byte[] buffer, int offset, int count) { _buffer = buffer ?? throw new ArgumentNullException("buffer"); checked { if (offset < 0 || count < 0 || offset > buffer.Length - count) { throw new ArgumentOutOfRangeException("count"); } _position = offset; _end = offset + count; } } public byte ReadU8() { Need(1, "u8"); return _buffer[checked(_position++)]; } public bool ReadBool() { byte b = ReadU8(); return b switch { 0 => false, 1 => true, _ => throw new WireException(ErrorCode.Malformed, "A bool field held " + b + "; only 0 and 1 are valid."), }; } public ushort ReadU16() { Need(2, "u16"); checked { int num = _buffer[_position] | (_buffer[_position + 1] << 8); _position += 2; return (ushort)num; } } public uint ReadU32() { Need(4, "u32"); uint num = 0u; for (int i = 0; i < 4; i = checked(i + 1)) { num |= (uint)checked(_buffer[_position + i] << 8 * i); } checked { _position += 4; return num; } } public ulong ReadU64() { Need(8, "u64"); ulong num = 0uL; for (int i = 0; i < 8; i = checked(i + 1)) { num |= (ulong)_buffer[checked(_position + i)] << checked(8 * i); } checked { _position += 8; return num; } } public long ReadI64() { return (long)ReadU64(); } public ByteString ReadFixed(int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length"); } Need(length, "byte[" + length + "]"); ByteString result = ByteString.CopyFrom(_buffer, _position, length); checked { _position += length; return result; } } public ByteString ReadRest() { ByteString result = ByteString.CopyFrom(_buffer, _position, Remaining); _position = _end; return result; } public ByteString ReadBlob(int maxBytes) { uint num = ReadU32(); checked { if (num > (uint)maxBytes) { throw new WireException(ErrorCode.SizeLimit, "A blob declared " + num + " bytes; the limit is " + maxBytes + "."); } return ReadFixed((int)num); } } public string ReadString(int maxBytes) { ushort num = ReadU16(); if (n