Changeset 455 for binary-improvements/MapRendering
- Timestamp:
- Jul 31, 2023, 4:06:13 PM (16 months ago)
- Location:
- binary-improvements/MapRendering
- Files:
-
- 1 added
- 2 deleted
- 19 edited
Legend:
- Unmodified
- Added
- Removed
-
binary-improvements/MapRendering/API.cs
r454 r455 1 1 using System; 2 2 using System.IO; 3 using Webserver;3 using JetBrains.Annotations; 4 4 using Webserver.FileCache; 5 5 using Webserver.UrlHandlers; 6 6 7 namespace AllocsFixes { 7 namespace AllocsFixes.Web { 8 [UsedImplicitly] 8 9 public class API : IModApi { 9 private Mod modInstance;10 private static Mod modInstance; 10 11 11 12 public void InitMod (Mod _modInstance) { 12 13 modInstance = _modInstance; 13 14 14 Web.ServerInitialized += _web => { 15 try { 16 const string legacyModUrl = "/legacymap"; 17 const string legacyFilesFoldername = "webserver_legacy"; 18 string legacyFilePath = $"{modInstance.Path}/{legacyFilesFoldername}"; 19 20 if (!Directory.Exists (legacyFilePath)) { 21 Log.Out ($"Legacy webmod feature not started (folder \"{legacyFilesFoldername}\" not found in Allocs_WebAndMapRendering mod folder)"); 22 return; 23 } 24 25 // TODO: Read from config 26 bool useStaticCache = false; 27 28 _web.RegisterPathHandler ("/legacymap.htm", new SimpleRedirectHandler ($"{legacyModUrl}/index.html")); 29 _web.RegisterPathHandler ($"{legacyModUrl}/", new StaticHandler (legacyFilePath, useStaticCache ? (AbstractCache) new SimpleCache () : new DirectAccess (), false)); 30 31 int webPort = GamePrefs.GetInt (EnumUtils.Parse<EnumGamePrefs> (nameof (EnumGamePrefs.WebDashboardPort))); 32 Log.Out ($"Started legacy webmod feature on port {webPort}, local adress {legacyModUrl}"); 33 } catch (Exception e) { 34 Log.Out ("Error in Web.ctor: " + e); 35 } 36 }; 15 Webserver.Web.ServerInitialized += OnWebServerInitialized; 37 16 } 38 17 39 // public static void SetResponseTextContent (HttpListenerResponse _context.Response, string _text) { 40 // byte[] buf = Encoding.UTF8.GetBytes (_text); 41 // _context.Response.ContentLength64 = buf.Length; 42 // _context.Response.ContentType = "text/html"; 43 // _context.Response.ContentEncoding = Encoding.UTF8; 44 // _context.Response.OutputStream.Write (buf, 0, buf.Length); 45 // } 18 private static void OnWebServerInitialized (Webserver.Web _web) { 19 try { 20 const string legacyModUrl = "/legacymap"; 21 const string legacyFilesFoldername = "webserver_legacy"; 22 string legacyFilePath = $"{modInstance.Path}/{legacyFilesFoldername}"; 46 23 47 24 if (!Directory.Exists (legacyFilePath)) { 25 Log.Out ($"Legacy webmod feature not started (folder \"{legacyFilesFoldername}\" not found in Allocs_WebAndMapRendering mod folder)"); 26 return; 27 } 28 29 // TODO: Read from config 30 bool useStaticCache = false; 31 32 _web.RegisterPathHandler ($"{legacyModUrl}", new SimpleRedirectHandler ($"{legacyModUrl}/index.html")); 33 _web.RegisterPathHandler ($"{legacyModUrl}/", new StaticHandler (legacyFilePath, useStaticCache ? new SimpleCache () : new DirectAccess (), false)); 34 35 int webPort = GamePrefs.GetInt (EnumUtils.Parse<EnumGamePrefs> (nameof(EnumGamePrefs.WebDashboardPort))); 36 Log.Out ($"Started legacy webmod feature on port {webPort}, local adress {legacyModUrl}"); 37 } catch (Exception e) { 38 Log.Out ($"Error in Web.ctor: {e}"); 39 } 40 } 48 41 } 49 42 } -
binary-improvements/MapRendering/API/ExecuteConsoleCommand.cs
r454 r455 1 1 using System; 2 2 using System.Net; 3 using JetBrains.Annotations; 3 4 using Webserver; 4 5 using Webserver.WebAPI; 5 using WebCommandResult = AllocsFixes. NetConnections.Servers.Web.WebCommandResult;6 using WebCommandResult = AllocsFixes.Web.WebCommandResult; 6 7 7 8 namespace AllocsFixes.WebAPIs { 9 [UsedImplicitly] 8 10 public class ExecuteConsoleCommand : AbsWebAPI { 9 11 public override void HandleRequest (RequestContext _context) { … … 16 18 _context.Request.QueryString ["raw"] != null 17 19 ? WebCommandResult.ResultType.Raw 18 : (_context.Request.QueryString ["simple"] != null20 : _context.Request.QueryString ["simple"] != null 19 21 ? WebCommandResult.ResultType.ResultOnly 20 : WebCommandResult.ResultType.Full );22 : WebCommandResult.ResultType.Full; 21 23 22 24 string commandline = _context.Request.QueryString ["command"]; -
binary-improvements/MapRendering/API/GetAllowedCommands.cs
r454 r455 1 using AllocsFixes.JSON; 1 using JetBrains.Annotations; 2 using Utf8Json; 2 3 using Webserver; 3 4 using Webserver.WebAPI; 4 5 5 6 namespace AllocsFixes.WebAPIs { 7 [UsedImplicitly] 6 8 public class GetAllowedCommands : AbsWebAPI { 9 private static readonly byte[] jsonKeyCommands = JsonWriter.GetEncodedPropertyNameWithBeginObject ("commands"); 10 11 private static readonly byte[] jsonKeyCommand = JsonWriter.GetEncodedPropertyNameWithBeginObject ("command"); 12 private static readonly byte[] jsonKeyDescription = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("description"); 13 private static readonly byte[] jsonKeyHelp = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("help"); 14 7 15 public override void HandleRequest (RequestContext _context) { 8 JSONObject result = new JSONObject (); 9 JSONArray entries = new JSONArray (); 16 JsonWriter writer = new JsonWriter (); 17 18 writer.WriteRaw (jsonKeyCommands); 19 writer.WriteBeginArray (); 20 21 bool first = true; 22 10 23 foreach (IConsoleCommand cc in SdtdConsole.Instance.GetCommands ()) { 11 24 int commandPermissionLevel = GameManager.Instance.adminTools.Commands.GetCommandPermissionLevel (cc.GetCommands ()); 12 if (_context.PermissionLevel <= commandPermissionLevel) { 13 string cmd = string.Empty; 14 foreach (string s in cc.GetCommands ()) { 15 if (s.Length > cmd.Length) { 16 cmd = s; 17 } 25 if (_context.PermissionLevel > commandPermissionLevel) { 26 continue; 27 } 28 29 string cmd = string.Empty; 30 foreach (string s in cc.GetCommands ()) { 31 if (s.Length > cmd.Length) { 32 cmd = s; 18 33 } 34 } 19 35 20 JSONObject cmdObj = new JSONObject (); 21 cmdObj.Add ("command", new JSONString (cmd)); 22 cmdObj.Add ("description", new JSONString (cc.GetDescription ())); 23 cmdObj.Add ("help", new JSONString (cc.GetHelp ())); 24 entries.Add (cmdObj); 36 if (!first) { 37 writer.WriteValueSeparator (); 25 38 } 39 40 first = false; 41 42 writer.WriteRaw (jsonKeyCommand); 43 writer.WriteString (cmd); 44 45 writer.WriteRaw (jsonKeyDescription); 46 writer.WriteString (cc.GetDescription ()); 47 48 writer.WriteRaw (jsonKeyHelp); 49 if (cc.GetHelp () == null) { 50 writer.WriteString (""); 51 } else { 52 writer.WriteString (cc.GetHelp ()); 53 } 54 55 writer.WriteEndObject (); 26 56 } 27 57 28 result.Add ("commands", entries); 29 30 LegacyApiHelper.WriteJSON (_context.Response, result); 58 writer.WriteEndArray (); 59 writer.WriteEndObject (); 60 61 WebUtils.WriteJsonData (_context.Response, ref writer); 31 62 } 32 63 -
binary-improvements/MapRendering/API/GetAnimalsLocation.cs
r454 r455 1 using System.Collections.Generic; 2 using AllocsFixes.JSON; 3 using AllocsFixes.LiveData; 4 using Webserver; 5 using Webserver.WebAPI; 1 using AllocsFixes.LiveData; 2 using JetBrains.Annotations; 6 3 7 4 namespace AllocsFixes.WebAPIs { 8 internal class GetAnimalsLocation : AbsWebAPI { 9 private readonly List<EntityAnimal> animals = new List<EntityAnimal> (); 10 11 public override void HandleRequest (RequestContext _context) { 12 JSONArray animalsJsResult = new JSONArray (); 13 14 Animals.Instance.Get (animals); 15 for (int i = 0; i < animals.Count; i++) { 16 EntityAnimal entity = animals [i]; 17 Vector3i position = new Vector3i (entity.GetPosition ()); 18 19 JSONObject jsonPOS = new JSONObject (); 20 jsonPOS.Add ("x", new JSONNumber (position.x)); 21 jsonPOS.Add ("y", new JSONNumber (position.y)); 22 jsonPOS.Add ("z", new JSONNumber (position.z)); 23 24 JSONObject pJson = new JSONObject (); 25 pJson.Add ("id", new JSONNumber (entity.entityId)); 26 27 if (!string.IsNullOrEmpty (entity.EntityName)) { 28 pJson.Add ("name", new JSONString (entity.EntityName)); 29 } else { 30 pJson.Add ("name", new JSONString ("animal class #" + entity.entityClass)); 31 } 32 33 pJson.Add ("position", jsonPOS); 34 35 animalsJsResult.Add (pJson); 36 } 37 38 LegacyApiHelper.WriteJSON (_context.Response, animalsJsResult); 5 [UsedImplicitly] 6 internal class GetAnimalsLocation : GetEntityListAbs<EntityAnimal> { 7 public GetAnimalsLocation () : base (Animals.Instance.Get) { 39 8 } 40 9 } -
binary-improvements/MapRendering/API/GetHostileLocation.cs
r454 r455 1 using System.Collections.Generic; 2 using AllocsFixes.JSON; 3 using AllocsFixes.LiveData; 4 using Webserver; 5 using Webserver.WebAPI; 1 using AllocsFixes.LiveData; 2 using JetBrains.Annotations; 6 3 7 4 namespace AllocsFixes.WebAPIs { 8 internal class GetHostileLocation : AbsWebAPI { 9 private readonly List<EntityEnemy> enemies = new List<EntityEnemy> (); 10 11 public override void HandleRequest (RequestContext _context) { 12 JSONArray hostilesJsResult = new JSONArray (); 13 14 Hostiles.Instance.Get (enemies); 15 for (int i = 0; i < enemies.Count; i++) { 16 EntityEnemy entity = enemies [i]; 17 Vector3i position = new Vector3i (entity.GetPosition ()); 18 19 JSONObject jsonPOS = new JSONObject (); 20 jsonPOS.Add ("x", new JSONNumber (position.x)); 21 jsonPOS.Add ("y", new JSONNumber (position.y)); 22 jsonPOS.Add ("z", new JSONNumber (position.z)); 23 24 JSONObject pJson = new JSONObject (); 25 pJson.Add ("id", new JSONNumber (entity.entityId)); 26 27 if (!string.IsNullOrEmpty (entity.EntityName)) { 28 pJson.Add ("name", new JSONString (entity.EntityName)); 29 } else { 30 pJson.Add ("name", new JSONString ("enemy class #" + entity.entityClass)); 31 } 32 33 pJson.Add ("position", jsonPOS); 34 35 hostilesJsResult.Add (pJson); 36 } 37 38 LegacyApiHelper.WriteJSON (_context.Response, hostilesJsResult); 5 [UsedImplicitly] 6 internal class GetHostileLocation : GetEntityListAbs<EntityEnemy> { 7 public GetHostileLocation () : base (Hostiles.Instance.Get) { 39 8 } 40 9 } -
binary-improvements/MapRendering/API/GetLandClaims.cs
r454 r455 1 1 using System.Collections.Generic; 2 2 using System.Net; 3 using AllocsFixes.JSON;4 3 using AllocsFixes.PersistentData; 4 using JetBrains.Annotations; 5 using Utf8Json; 5 6 using Webserver; 6 7 using Webserver.Permissions; … … 8 9 9 10 namespace AllocsFixes.WebAPIs { 11 [UsedImplicitly] 10 12 public class GetLandClaims : AbsWebAPI { 13 private static readonly byte[] jsonKeyClaimSize = JsonWriter.GetEncodedPropertyNameWithBeginObject ("claimsize"); 14 private static readonly byte[] jsonKeyClaimOwners = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("claimowners"); 15 16 private static readonly byte[] jsonKeySteamId = JsonWriter.GetEncodedPropertyNameWithBeginObject ("steamid"); 17 private static readonly byte[] jsonKeyCrossPlatformId = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("crossplatformid"); 18 private static readonly byte[] jsonKeyClaimActive = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("claimactive"); 19 private static readonly byte[] jsonKeyPlayerName = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("playername"); 20 private static readonly byte[] jsonKeyClaims = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("claims"); 21 11 22 public override void HandleRequest (RequestContext _context) { 12 23 PlatformUserIdentifierAbs requestedUserId = null; … … 23 34 bool bViewAll = PermissionUtils.CanViewAllClaims (_context.PermissionLevel); 24 35 25 JSONObject result = new JSONObject ();26 result.Add ("claimsize", new JSONNumber (GamePrefs.GetInt (EnumUtils.Parse<EnumGamePrefs> (nameof(EnumGamePrefs.LandClaimSize)))));27 28 JSONArray claimOwners = new JSONArray ();29 result.Add ("claimowners", claimOwners);30 31 36 LandClaimList.OwnerFilter[] ownerFilters = null; 32 37 if (requestedUserId != null || !bViewAll) { … … 34 39 ownerFilters = new[] { 35 40 LandClaimList.UserIdFilter (userId), 36 LandClaimList.UserIdFilter (requestedUserId) 41 LandClaimList.UserIdFilter (requestedUserId), 37 42 }; 38 43 } else if (!bViewAll) { … … 47 52 Dictionary<Player, List<Vector3i>> claims = LandClaimList.GetLandClaims (ownerFilters, posFilters); 48 53 54 JsonWriter writer = new JsonWriter (); 55 56 writer.WriteRaw (jsonKeyClaimSize); 57 writer.WriteInt32 (GamePrefs.GetInt (EnumUtils.Parse<EnumGamePrefs> (nameof(EnumGamePrefs.LandClaimSize)))); 58 59 writer.WriteRaw (jsonKeyClaimOwners); 60 writer.WriteBeginArray (); 61 62 bool first = true; 63 49 64 foreach (KeyValuePair<Player, List<Vector3i>> kvp in claims) { 50 JSONObject owner = new JSONObject (); 51 claimOwners.Add (owner); 52 53 owner.Add ("steamid", new JSONString (kvp.Key.PlatformId?.CombinedString ?? "")); 54 owner.Add ("crossplatformid", new JSONString (kvp.Key.CrossPlatformId?.CombinedString ?? "")); 55 owner.Add ("claimactive", new JSONBoolean (kvp.Key.LandProtectionActive)); 56 57 if (kvp.Key.Name.Length > 0) { 58 owner.Add ("playername", new JSONString (kvp.Key.Name)); 59 } else { 60 owner.Add ("playername", new JSONNull ()); 65 if (!first) { 66 writer.WriteValueSeparator (); 61 67 } 62 68 63 JSONArray claimsJson = new JSONArray (); 64 owner.Add ("claims", claimsJson); 69 first = false; 70 71 writer.WriteRaw (jsonKeySteamId); 72 writer.WriteString (kvp.Key.PlatformId?.CombinedString ?? ""); 73 74 writer.WriteRaw (jsonKeyCrossPlatformId); 75 writer.WriteString (kvp.Key.CrossPlatformId?.CombinedString ?? ""); 76 77 writer.WriteRaw (jsonKeyClaimActive); 78 writer.WriteBoolean (kvp.Key.LandProtectionActive); 79 80 writer.WriteRaw (jsonKeyPlayerName); 81 if (kvp.Key.Name.Length > 0) { 82 writer.WriteString (kvp.Key.Name); 83 } else { 84 writer.WriteNull (); 85 } 86 87 writer.WriteRaw (jsonKeyClaims); 88 writer.WriteBeginArray (); 89 90 bool first2 = true; 65 91 66 92 foreach (Vector3i v in kvp.Value) { 67 JSONObject claim = new JSONObject (); 68 claim.Add ("x", new JSONNumber (v.x)); 69 claim.Add ("y", new JSONNumber (v.y)); 70 claim.Add ("z", new JSONNumber (v.z)); 93 if (!first2) { 94 writer.WriteValueSeparator (); 95 } 71 96 72 claimsJson.Add (claim); 97 first2 = false; 98 99 JsonCommons.WriteVector3I (ref writer, v); 73 100 } 101 102 writer.WriteEndArray (); 103 104 writer.WriteEndObject (); 74 105 } 75 106 76 LegacyApiHelper.WriteJSON (_context.Response, result); 107 writer.WriteEndArray (); 108 109 writer.WriteEndObject (); 110 WebUtils.WriteJsonData (_context.Response, ref writer); 77 111 } 78 112 } -
binary-improvements/MapRendering/API/GetLog.cs
r454 r455 1 1 using System.Collections.Generic; 2 using AllocsFixes.JSON; 2 using JetBrains.Annotations; 3 using Utf8Json; 3 4 using Webserver; 4 5 using Webserver.WebAPI; 5 6 6 7 namespace AllocsFixes.WebAPIs { 8 [UsedImplicitly] 7 9 public class GetLog : AbsWebAPI { 8 10 private const int MAX_COUNT = 1000; 9 11 12 private static readonly byte[] jsonKeyFirstLine = JsonWriter.GetEncodedPropertyNameWithBeginObject ("firstLine"); 13 private static readonly byte[] jsonKeyLastLine = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("lastLine"); 14 private static readonly byte[] jsonKeyEntries = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("entries"); 15 16 private static readonly byte[] jsonKeyEntDate = JsonWriter.GetEncodedPropertyNameWithBeginObject ("date"); 17 private static readonly byte[] jsonKeyEntTime = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("time"); 18 private static readonly byte[] jsonKeyEntUptime = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("uptime"); 19 private static readonly byte[] jsonKeyEntMsg = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("msg"); 20 private static readonly byte[] jsonKeyEntTrace = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("trace"); 21 private static readonly byte[] jsonKeyEntType = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("type"); 22 10 23 public override void HandleRequest (RequestContext _context) { 11 24 if (_context.Request.QueryString ["count"] == null || !int.TryParse (_context.Request.QueryString ["count"], out var count)) { … … 26 39 27 40 if (_context.Request.QueryString ["firstLine"] == null || !int.TryParse (_context.Request.QueryString ["firstLine"], out var firstLine)) { 28 if (count > 0) { 29 firstLine = LogBuffer.Instance.OldestLine; 30 } else { 31 firstLine = LogBuffer.Instance.LatestLine; 32 } 41 firstLine = count > 0 ? LogBuffer.Instance.OldestLine : LogBuffer.Instance.LatestLine; 33 42 } 34 35 JSONObject result = new JSONObject ();36 43 37 44 List<LogBuffer.LogEntry> logEntries = LogBuffer.Instance.GetRange (ref firstLine, count, out var lastLine); 38 45 39 JSONArray entries = new JSONArray (); 46 JsonWriter writer = new JsonWriter (); 47 48 writer.WriteRaw (jsonKeyFirstLine); 49 writer.WriteInt32 (firstLine); 50 51 writer.WriteRaw (jsonKeyLastLine); 52 writer.WriteInt32 (lastLine); 53 54 writer.WriteRaw (jsonKeyEntries); 55 writer.WriteBeginArray (); 56 57 bool first = true; 58 40 59 foreach (LogBuffer.LogEntry logEntry in logEntries) { 41 JSONObject entry = new JSONObject (); 60 if (!first) { 61 writer.WriteValueSeparator (); 62 } 63 64 first = false; 65 42 66 var logEntryTimestamp = logEntry.Timestamp; 43 entry.Add ("date", new JSONString ($"{logEntryTimestamp.Year:0000}-{logEntryTimestamp.Month:00}-{logEntryTimestamp.Day:00}")); 44 entry.Add ("time", new JSONString ($"{logEntryTimestamp.Hour:00}:{logEntryTimestamp.Minute:00}:{logEntryTimestamp.Second:00}")); 45 entry.Add ("uptime", new JSONString (logEntry.Uptime.ToString())); 46 entry.Add ("msg", new JSONString (logEntry.Message)); 47 entry.Add ("trace", new JSONString (logEntry.Trace)); 48 entry.Add ("type", new JSONString (logEntry.Type.ToStringCached ())); 49 entries.Add (entry); 67 68 writer.WriteRaw (jsonKeyEntDate); 69 writer.WriteString ($"{logEntryTimestamp.Year:0000}-{logEntryTimestamp.Month:00}-{logEntryTimestamp.Day:00}"); 70 71 writer.WriteRaw (jsonKeyEntTime); 72 writer.WriteString ($"{logEntryTimestamp.Hour:00}:{logEntryTimestamp.Minute:00}:{logEntryTimestamp.Second:00}"); 73 74 writer.WriteRaw (jsonKeyEntUptime); 75 writer.WriteString (logEntry.Uptime.ToString()); 76 77 writer.WriteRaw (jsonKeyEntMsg); 78 writer.WriteString (logEntry.Message); 79 80 writer.WriteRaw (jsonKeyEntTrace); 81 writer.WriteString (logEntry.Trace); 82 83 writer.WriteRaw (jsonKeyEntType); 84 writer.WriteString (logEntry.Type.ToStringCached ()); 85 86 writer.WriteEndObject (); 50 87 } 51 88 52 result.Add ("firstLine", new JSONNumber (firstLine)); 53 result.Add ("lastLine", new JSONNumber (lastLine)); 54 result.Add ("entries", entries); 55 56 LegacyApiHelper.WriteJSON (_context.Response, result); 89 writer.WriteEndArray (); 90 91 writer.WriteEndObject (); 92 WebUtils.WriteJsonData (_context.Response, ref writer); 57 93 } 58 94 } -
binary-improvements/MapRendering/API/GetPlayerInventories.cs
r454 r455 1 1 using System.Collections.Generic; 2 using AllocsFixes.JSON;3 2 using AllocsFixes.PersistentData; 3 using JetBrains.Annotations; 4 using Utf8Json; 4 5 using Webserver; 5 6 using Webserver.WebAPI; 6 7 7 8 namespace AllocsFixes.WebAPIs { 9 [UsedImplicitly] 8 10 public class GetPlayerInventories : AbsWebAPI { 9 11 public override void HandleRequest (RequestContext _context) { 10 12 GetPlayerInventory.GetInventoryArguments (_context, out bool showIconColor, out bool showIconName); 11 13 12 JSONArray AllInventoriesResult = new JSONArray (); 14 JsonWriter writer = new JsonWriter (); 15 16 writer.WriteBeginArray (); 17 18 bool first = true; 13 19 14 20 foreach (KeyValuePair<PlatformUserIdentifierAbs, Player> kvp in PersistentContainer.Instance.Players.Dict) { … … 20 26 21 27 if (p.IsOnline) { 22 AllInventoriesResult.Add (GetPlayerInventory.DoPlayer (p, showIconColor, showIconName)); 28 if (!first) { 29 writer.WriteValueSeparator (); 30 } 31 32 first = false; 33 34 GetPlayerInventory.DoPlayer (ref writer, p, showIconColor, showIconName); 23 35 } 24 36 } 25 26 LegacyApiHelper.WriteJSON (_context.Response, AllInventoriesResult); 37 38 writer.WriteEndArray (); 39 40 WebUtils.WriteJsonData (_context.Response, ref writer); 27 41 } 28 42 } -
binary-improvements/MapRendering/API/GetPlayerInventory.cs
r454 r455 1 1 using System.Collections.Generic; 2 2 using System.Net; 3 using AllocsFixes.JSON;4 3 using AllocsFixes.PersistentData; 4 using JetBrains.Annotations; 5 using Utf8Json; 5 6 using Webserver; 6 7 using Webserver.WebAPI; 7 8 8 9 namespace AllocsFixes.WebAPIs { 10 [UsedImplicitly] 9 11 public class GetPlayerInventory : AbsWebAPI { 10 12 public override void HandleRequest (RequestContext _context) { … … 28 30 GetInventoryArguments (_context, out bool showIconColor, out bool showIconName); 29 31 30 J SONObject result = DoPlayer (p, showIconColor, showIconName);31 32 LegacyApiHelper.WriteJSON (_context.Response, result);32 JsonWriter writer = new JsonWriter (); 33 DoPlayer (ref writer, p, showIconColor, showIconName); 34 WebUtils.WriteJsonData (_context.Response, ref writer); 33 35 } 34 36 … … 43 45 } 44 46 45 internal static JSONObject DoPlayer (Player _player, bool _showIconColor, bool _showIconName) { 47 private static readonly byte[] jsonKeyUserId = JsonWriter.GetEncodedPropertyNameWithBeginObject ("userid"); 48 private static readonly byte[] jsonKeyCrossPlatformId = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("crossplatformid"); 49 private static readonly byte[] jsonKeyEntityId = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("entityid"); 50 private static readonly byte[] jsonKeyPlayerName = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("playername"); 51 private static readonly byte[] jsonKeyBag = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("bag"); 52 private static readonly byte[] jsonKeyBelt = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("belt"); 53 private static readonly byte[] jsonKeyEquipment = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("equipment"); 54 55 internal static void DoPlayer (ref JsonWriter _writer, Player _player, bool _showIconColor, bool _showIconName) { 46 56 PersistentData.Inventory inv = _player.Inventory; 47 48 JSONObject result = new JSONObject (); 49 50 JSONArray bag = new JSONArray (); 51 JSONArray belt = new JSONArray (); 52 JSONObject equipment = new JSONObject (); 53 result.Add ("userid", new JSONString (_player.PlatformId.CombinedString)); 54 result.Add ("crossplatformid", new JSONString (_player.CrossPlatformId?.CombinedString ?? "")); 55 result.Add ("entityid", new JSONNumber (_player.EntityID)); 56 result.Add ("playername", new JSONString (_player.Name)); 57 result.Add ("bag", bag); 58 result.Add ("belt", belt); 59 result.Add ("equipment", equipment); 60 61 DoInventory (belt, inv.belt, _showIconColor, _showIconName); 62 DoInventory (bag, inv.bag, _showIconColor, _showIconName); 63 64 AddEquipment (equipment, "head", inv.equipment, EquipmentSlots.Headgear, _showIconColor, _showIconName); 65 AddEquipment (equipment, "eyes", inv.equipment, EquipmentSlots.Eyewear, _showIconColor, _showIconName); 66 AddEquipment (equipment, "face", inv.equipment, EquipmentSlots.Face, _showIconColor, _showIconName); 67 68 AddEquipment (equipment, "armor", inv.equipment, EquipmentSlots.ChestArmor, _showIconColor, _showIconName); 69 AddEquipment (equipment, "jacket", inv.equipment, EquipmentSlots.Jacket, _showIconColor, _showIconName); 70 AddEquipment (equipment, "shirt", inv.equipment, EquipmentSlots.Shirt, _showIconColor, _showIconName); 71 72 AddEquipment (equipment, "legarmor", inv.equipment, EquipmentSlots.LegArmor, _showIconColor, _showIconName); 73 AddEquipment (equipment, "pants", inv.equipment, EquipmentSlots.Legs, _showIconColor, _showIconName); 74 AddEquipment (equipment, "boots", inv.equipment, EquipmentSlots.Feet, _showIconColor, _showIconName); 75 76 AddEquipment (equipment, "gloves", inv.equipment, EquipmentSlots.Hands, _showIconColor, _showIconName); 77 78 return result; 57 58 _writer.WriteRaw (jsonKeyUserId); 59 _writer.WriteString (_player.PlatformId.CombinedString); 60 61 _writer.WriteRaw (jsonKeyCrossPlatformId); 62 _writer.WriteString (_player.CrossPlatformId?.CombinedString ?? ""); 63 64 _writer.WriteRaw (jsonKeyEntityId); 65 _writer.WriteInt32 (_player.EntityID); 66 67 _writer.WriteRaw (jsonKeyPlayerName); 68 _writer.WriteString (_player.Name); 69 70 _writer.WriteRaw (jsonKeyBag); 71 DoInventory (ref _writer, inv.bag, _showIconColor, _showIconName); 72 73 _writer.WriteRaw (jsonKeyBelt); 74 DoInventory (ref _writer, inv.belt, _showIconColor, _showIconName); 75 76 _writer.WriteRaw (jsonKeyEquipment); 77 DoEquipment (ref _writer, inv.equipment, _showIconColor, _showIconName); 78 79 _writer.WriteEndObject (); 79 80 } 80 81 81 private static void DoInventory (JSONArray _jsonRes, List<InvItem> _inv, bool _showIconColor, bool _showIconName) { 82 private static void DoInventory (ref JsonWriter _writer, IReadOnlyList<InvItem> _inv, bool _showIconColor, bool _showIconName) { 83 _writer.WriteBeginArray (); 82 84 for (int i = 0; i < _inv.Count; i++) { 83 _jsonRes.Add (GetJsonForItem (_inv [i], _showIconColor, _showIconName)); 85 if (i > 0) { 86 _writer.WriteValueSeparator (); 87 } 88 GetJsonForItem (ref _writer, _inv [i], _showIconColor, _showIconName); 84 89 } 90 _writer.WriteEndArray (); 85 91 } 86 92 87 private static void AddEquipment (JSONObject _eq, string _slotname, InvItem[] _items, EquipmentSlots _slot, bool _showIconColor, bool _showIconName) { 93 private static void DoEquipment (ref JsonWriter _writer, IReadOnlyList<InvItem> _equ, bool _showIconColor, bool _showIconName) { 94 _writer.WriteBeginObject (); 95 96 AddEquipment (ref _writer, "head", _equ, EquipmentSlots.Headgear, _showIconColor, _showIconName); 97 _writer.WriteValueSeparator (); 98 AddEquipment (ref _writer, "eyes", _equ, EquipmentSlots.Eyewear, _showIconColor, _showIconName); 99 _writer.WriteValueSeparator (); 100 AddEquipment (ref _writer, "face", _equ, EquipmentSlots.Face, _showIconColor, _showIconName); 101 _writer.WriteValueSeparator (); 102 103 AddEquipment (ref _writer, "armor", _equ, EquipmentSlots.ChestArmor, _showIconColor, _showIconName); 104 _writer.WriteValueSeparator (); 105 AddEquipment (ref _writer, "jacket", _equ, EquipmentSlots.Jacket, _showIconColor, _showIconName); 106 _writer.WriteValueSeparator (); 107 AddEquipment (ref _writer, "shirt", _equ, EquipmentSlots.Shirt, _showIconColor, _showIconName); 108 _writer.WriteValueSeparator (); 109 110 AddEquipment (ref _writer, "legarmor", _equ, EquipmentSlots.LegArmor, _showIconColor, _showIconName); 111 _writer.WriteValueSeparator (); 112 AddEquipment (ref _writer, "pants", _equ, EquipmentSlots.Legs, _showIconColor, _showIconName); 113 _writer.WriteValueSeparator (); 114 AddEquipment (ref _writer, "boots", _equ, EquipmentSlots.Feet, _showIconColor, _showIconName); 115 _writer.WriteValueSeparator (); 116 117 AddEquipment (ref _writer, "gloves", _equ, EquipmentSlots.Hands, _showIconColor, _showIconName); 118 119 _writer.WriteEndObject (); 120 } 121 122 private static void AddEquipment (ref JsonWriter _writer, string _slotname, IReadOnlyList<InvItem> _items, EquipmentSlots _slot, bool _showIconColor, bool _showIconName) { 123 _writer.WritePropertyName (_slotname); 124 88 125 int[] slotindices = XUiM_PlayerEquipment.GetSlotIndicesByEquipmentSlot (_slot); 89 126 … … 91 128 if (_items? [slotindices [i]] != null) { 92 129 InvItem item = _items [slotindices [i]]; 93 _eq.Add (_slotname, GetJsonForItem (item, _showIconColor, _showIconName)); 130 131 GetJsonForItem (ref _writer, item, _showIconColor, _showIconName); 94 132 return; 95 133 } 96 134 } 97 135 98 _eq.Add (_slotname, new JSONNull ()); 136 // Slot not found / empty 137 _writer.WriteNull (); 99 138 } 100 139 101 private static JSONNode GetJsonForItem (InvItem _item, bool _showIconColor, bool _showIconName) { 140 private static readonly byte[] jsonKeyCount = JsonWriter.GetEncodedPropertyNameWithBeginObject ("count"); 141 private static readonly byte[] jsonKeyName = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("name"); 142 private static readonly byte[] jsonKeyIcon = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("icon"); 143 private static readonly byte[] jsonKeyIconColor = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("iconcolor"); 144 private static readonly byte[] jsonKeyQuality = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("quality"); 145 private static readonly byte[] jsonKeyQualityColor = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("qualitycolor"); 146 147 private static void GetJsonForItem (ref JsonWriter _writer, InvItem _item, bool _showIconColor, bool _showIconName) { 102 148 if (_item == null) { 103 return new JSONNull (); 149 _writer.WriteNull (); 150 return; 104 151 } 105 106 JSONObject jsonItem = new JSONObject (); 107 jsonItem.Add ("count", new JSONNumber (_item.count)); 108 jsonItem.Add ("name", new JSONString (_item.itemName)); 152 153 _writer.WriteRaw (jsonKeyCount); 154 _writer.WriteInt32 (_item.count); 155 156 _writer.WriteRaw (jsonKeyName); 157 _writer.WriteString (_item.itemName); 109 158 110 159 if (_showIconName) { 111 jsonItem.Add ("icon", new JSONString (_item.icon)); 160 _writer.WriteRaw (jsonKeyIcon); 161 _writer.WriteString (_item.icon); 112 162 } 113 163 114 164 if (_showIconColor) { 115 jsonItem.Add ("iconcolor", new JSONString (_item.iconcolor)); 165 _writer.WriteRaw (jsonKeyIconColor); 166 _writer.WriteString (_item.iconcolor); 116 167 } 117 168 118 jsonItem.Add ("quality", new JSONNumber (_item.quality)); 169 _writer.WriteRaw (jsonKeyQuality); 170 _writer.WriteInt32 (_item.quality); 171 119 172 if (_item.quality >= 0) { 120 jsonItem.Add ("qualitycolor", new JSONString (QualityInfo.GetQualityColorHex (_item.quality))); 173 _writer.WriteRaw (jsonKeyQualityColor); 174 _writer.WriteString (QualityInfo.GetQualityColorHex (_item.quality)); 121 175 } 122 123 return jsonItem; 124 176 177 _writer.WriteEndObject (); 125 178 } 126 179 } -
binary-improvements/MapRendering/API/GetPlayerList.cs
r454 r455 2 2 using System.Collections.Generic; 3 3 using System.Linq; 4 using System.Text; 4 5 using System.Text.RegularExpressions; 5 using AllocsFixes.JSON;6 6 using AllocsFixes.PersistentData; 7 using JetBrains.Annotations; 7 8 using Webserver; 8 9 using Webserver.Permissions; … … 10 11 11 12 namespace AllocsFixes.WebAPIs { 13 [UsedImplicitly] 12 14 public class GetPlayerList : AbsWebAPI { 13 15 private static readonly Regex numberFilterMatcher = … … 121 123 result.Add ("players", playersJsResult); 122 124 123 LegacyApiHelper.WriteJSON (_context.Response, result); 124 } 125 126 private IEnumerable<JSONObject> ExecuteFilter (IEnumerable<JSONObject> _list, string _filterCol, 125 StringBuilder sb = new StringBuilder (); 126 result.ToString (sb); 127 WebUtils.WriteText (_context.Response, sb.ToString(), _mimeType: WebUtils.MimeJson); 128 } 129 130 private static IEnumerable<JSONObject> ExecuteFilter (IEnumerable<JSONObject> _list, string _filterCol, 127 131 string _filterVal) { 128 132 if (!_list.Any()) { … … 144 148 // regex-match whole ^string$, replace * by .*, ? by .?, + by .+ 145 149 _filterVal = _filterVal.Replace ("*", ".*").Replace ("?", ".?").Replace ("+", ".+"); 146 _filterVal = "^" + _filterVal + "$";150 _filterVal = $"^{_filterVal}$"; 147 151 148 152 //Log.Out ("GetPlayerList: Filter on String with Regex '" + _filterVal + "'"); … … 156 160 157 161 158 private IEnumerable<JSONObject> ExecuteNumberFilter (IEnumerable<JSONObject> _list, string _filterCol,162 private static IEnumerable<JSONObject> ExecuteNumberFilter (IEnumerable<JSONObject> _list, string _filterCol, 159 163 string _filterVal) { 160 164 // allow value (exact match), =, ==, >=, >, <=, < … … 207 211 } 208 212 209 Log.Out ( "GetPlayerList: ignoring invalid filter for number-column '{0}': '{1}'", _filterCol, _filterVal);213 Log.Out ($"GetPlayerList: ignoring invalid filter for number-column '{_filterCol}': '{_filterVal}'"); 210 214 return _list; 211 215 } 212 216 213 217 214 private IEnumerable<JSONObject> ExecuteSort (IEnumerable<JSONObject> _list, string _sortCol, bool _ascending) {218 private static IEnumerable<JSONObject> ExecuteSort (IEnumerable<JSONObject> _list, string _sortCol, bool _ascending) { 215 219 if (_list.Count () == 0) { 216 220 return _list; … … 246 250 247 251 248 private bool NearlyEqual (double _a, double _b, double _epsilon) {252 private static bool NearlyEqual (double _a, double _b, double _epsilon) { 249 253 double absA = Math.Abs (_a); 250 254 double absB = Math.Abs (_b); … … 267 271 GreaterEqual, 268 272 Lesser, 269 LesserEqual 270 } 273 LesserEqual, 274 } 275 276 277 #region JSON encoder 278 279 private abstract class JSONNode { 280 public abstract void ToString (StringBuilder _stringBuilder, bool _prettyPrint = false, int _currentLevel = 0); 281 282 public override string ToString () { 283 StringBuilder sb = new StringBuilder (); 284 ToString (sb); 285 return sb.ToString (); 286 } 287 } 288 289 private abstract class JSONValue : JSONNode { 290 } 291 292 private class JSONNull : JSONValue { 293 public override void ToString (StringBuilder _stringBuilder, bool _prettyPrint = false, int _currentLevel = 0) { 294 _stringBuilder.Append ("null"); 295 } 296 } 297 298 private class JSONBoolean : JSONValue { 299 private readonly bool value; 300 301 public JSONBoolean (bool _value) { 302 value = _value; 303 } 304 305 public bool GetBool () { 306 return value; 307 } 308 309 public override void ToString (StringBuilder _stringBuilder, bool _prettyPrint = false, int _currentLevel = 0) { 310 _stringBuilder.Append (value ? "true" : "false"); 311 } 312 } 313 314 private class JSONNumber : JSONValue { 315 private readonly double value; 316 317 public JSONNumber (double _value) { 318 value = _value; 319 } 320 321 public double GetDouble () { 322 return value; 323 } 324 325 public override void ToString (StringBuilder _stringBuilder, bool _prettyPrint = false, int _currentLevel = 0) { 326 _stringBuilder.Append (value.ToCultureInvariantString ()); 327 } 328 } 329 330 private class JSONString : JSONValue { 331 private readonly string value; 332 333 public JSONString (string _value) { 334 value = _value; 335 } 336 337 public string GetString () { 338 return value; 339 } 340 341 public override void ToString (StringBuilder _stringBuilder, bool _prettyPrint = false, int _currentLevel = 0) { 342 if (string.IsNullOrEmpty (value)) { 343 _stringBuilder.Append ("\"\""); 344 return; 345 } 346 347 int len = value.Length; 348 349 _stringBuilder.EnsureCapacity (_stringBuilder.Length + 2 * len); 350 351 _stringBuilder.Append ('"'); 352 353 foreach (char c in value) { 354 switch (c) { 355 case '\\': 356 case '"': 357 358 // case '/': 359 _stringBuilder.Append ('\\'); 360 _stringBuilder.Append (c); 361 break; 362 case '\b': 363 _stringBuilder.Append ("\\b"); 364 break; 365 case '\t': 366 _stringBuilder.Append ("\\t"); 367 break; 368 case '\n': 369 _stringBuilder.Append ("\\n"); 370 break; 371 case '\f': 372 _stringBuilder.Append ("\\f"); 373 break; 374 case '\r': 375 _stringBuilder.Append ("\\r"); 376 break; 377 default: 378 if (c < ' ') { 379 _stringBuilder.Append ("\\u"); 380 _stringBuilder.Append (((int) c).ToString ("X4")); 381 } else { 382 _stringBuilder.Append (c); 383 } 384 385 break; 386 } 387 } 388 389 _stringBuilder.Append ('"'); 390 } 391 392 } 393 394 private class JSONArray : JSONNode { 395 private readonly List<JSONNode> nodes = new List<JSONNode> (); 396 397 public void Add (JSONNode _node) { 398 nodes.Add (_node); 399 } 400 401 public override void ToString (StringBuilder _stringBuilder, bool _prettyPrint = false, int _currentLevel = 0) { 402 _stringBuilder.Append ("["); 403 if (_prettyPrint) { 404 _stringBuilder.Append ('\n'); 405 } 406 407 foreach (JSONNode n in nodes) { 408 if (_prettyPrint) { 409 _stringBuilder.Append (new string ('\t', _currentLevel + 1)); 410 } 411 412 n.ToString (_stringBuilder, _prettyPrint, _currentLevel + 1); 413 _stringBuilder.Append (","); 414 if (_prettyPrint) { 415 _stringBuilder.Append ('\n'); 416 } 417 } 418 419 if (nodes.Count > 0) { 420 _stringBuilder.Remove (_stringBuilder.Length - (_prettyPrint ? 2 : 1), 1); 421 } 422 423 if (_prettyPrint) { 424 _stringBuilder.Append (new string ('\t', _currentLevel)); 425 } 426 427 _stringBuilder.Append ("]"); 428 } 429 430 } 431 432 private class JSONObject : JSONNode { 433 private readonly Dictionary<string, JSONNode> nodes = new Dictionary<string, JSONNode> (); 434 435 public JSONNode this [string _name] => nodes [_name]; 436 437 public bool ContainsKey (string _name) { 438 return nodes.ContainsKey (_name); 439 } 440 441 public void Add (string _name, JSONNode _node) { 442 nodes.Add (_name, _node); 443 } 444 445 public override void ToString (StringBuilder _stringBuilder, bool _prettyPrint = false, int _currentLevel = 0) { 446 _stringBuilder.Append ("{"); 447 if (_prettyPrint) { 448 _stringBuilder.Append ('\n'); 449 } 450 451 foreach (KeyValuePair<string, JSONNode> kvp in nodes) { 452 if (_prettyPrint) { 453 _stringBuilder.Append (new string ('\t', _currentLevel + 1)); 454 } 455 456 _stringBuilder.Append ($"\"{kvp.Key}\":"); 457 if (_prettyPrint) { 458 _stringBuilder.Append (" "); 459 } 460 461 kvp.Value.ToString (_stringBuilder, _prettyPrint, _currentLevel + 1); 462 _stringBuilder.Append (","); 463 if (_prettyPrint) { 464 _stringBuilder.Append ('\n'); 465 } 466 } 467 468 if (nodes.Count > 0) { 469 _stringBuilder.Remove (_stringBuilder.Length - (_prettyPrint ? 2 : 1), 1); 470 } 471 472 if (_prettyPrint) { 473 _stringBuilder.Append (new string ('\t', _currentLevel)); 474 } 475 476 _stringBuilder.Append ("}"); 477 } 478 479 } 480 481 #endregion 482 271 483 } 272 484 } -
binary-improvements/MapRendering/API/GetPlayersLocation.cs
r454 r455 1 1 using System.Collections.Generic; 2 using AllocsFixes.JSON;3 2 using AllocsFixes.PersistentData; 3 using JetBrains.Annotations; 4 using Utf8Json; 4 5 using Webserver; 5 6 using Webserver.Permissions; … … 7 8 8 9 namespace AllocsFixes.WebAPIs { 10 [UsedImplicitly] 9 11 public class GetPlayersLocation : AbsWebAPI { 12 private static readonly byte[] jsonKeySteamId = JsonWriter.GetEncodedPropertyNameWithBeginObject ("steamid"); 13 private static readonly byte[] jsonKeyCrossPlatformId = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("crossplatformid"); 14 private static readonly byte[] jsonKeyName = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("name"); 15 private static readonly byte[] jsonKeyOnline = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("online"); 16 private static readonly byte[] jsonKeyPosition = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("position"); 17 10 18 public override void HandleRequest (RequestContext _context) { 11 19 AdminTools admTools = GameManager.Instance.adminTools; … … 19 27 bool bViewAll = PermissionUtils.CanViewAllPlayers (_context.PermissionLevel); 20 28 21 JSONArray playersJsResult = new JSONArray (); 29 JsonWriter writer = new JsonWriter (); 30 31 writer.WriteBeginArray (); 32 33 bool first = true; 22 34 23 35 Players playersList = PersistentContainer.Instance.Players; … … 34 46 if (listOffline || p.IsOnline) { 35 47 if (bViewAll || p.InternalId.Equals (userId)) { 36 JSONObject pos = new JSONObject ();37 pos.Add ("x", new JSONNumber (p.LastPosition.x));38 pos.Add ("y", new JSONNumber (p.LastPosition.y));39 pos.Add ("z", new JSONNumber (p.LastPosition.z));40 48 41 JSONObject pJson = new JSONObject ();42 pJson.Add ("steamid", new JSONString (kvp.Value.PlatformId.CombinedString));43 pJson.Add ("crossplatformid", new JSONString (kvp.Value.CrossPlatformId?.CombinedString ?? ""));49 if (!first) { 50 writer.WriteValueSeparator (); 51 } 44 52 45 // pJson.Add("entityid", new JSONNumber (p.EntityID)); 46 // pJson.Add("ip", new JSONString (p.IP)); 47 pJson.Add ("name", new JSONString (p.Name)); 48 pJson.Add ("online", new JSONBoolean (p.IsOnline)); 49 pJson.Add ("position", pos); 50 51 // pJson.Add ("totalplaytime", new JSONNumber (p.TotalPlayTime)); 52 // pJson.Add ("lastonline", new JSONString (p.LastOnline.ToString ("s"))); 53 // pJson.Add ("ping", new JSONNumber (p.IsOnline ? p.ClientInfo.ping : -1)); 54 55 playersJsResult.Add (pJson); 53 first = false; 54 55 writer.WriteRaw (jsonKeySteamId); 56 writer.WriteString (kvp.Value.PlatformId.CombinedString); 57 58 writer.WriteRaw (jsonKeyCrossPlatformId); 59 writer.WriteString (kvp.Value.CrossPlatformId?.CombinedString ?? ""); 60 61 writer.WriteRaw (jsonKeyName); 62 writer.WriteString (p.Name); 63 64 writer.WriteRaw (jsonKeyOnline); 65 writer.WriteBoolean (p.IsOnline); 66 67 writer.WriteRaw (jsonKeyPosition); 68 JsonCommons.WriteVector3I (ref writer, p.LastPosition); 69 70 writer.WriteEndObject (); 56 71 } 57 72 } 58 73 } 59 60 LegacyApiHelper.WriteJSON (_context.Response, playersJsResult); 74 75 writer.WriteEndArray (); 76 77 WebUtils.WriteJsonData (_context.Response, ref writer); 61 78 } 62 79 } -
binary-improvements/MapRendering/API/GetPlayersOnline.cs
r454 r455 1 1 using System.Collections.Generic; 2 using AllocsFixes.JSON;3 2 using AllocsFixes.PersistentData; 3 using JetBrains.Annotations; 4 using Utf8Json; 4 5 using Webserver; 5 6 using Webserver.WebAPI; 6 7 7 8 namespace AllocsFixes.WebAPIs { 9 [UsedImplicitly] 8 10 public class GetPlayersOnline : AbsWebAPI { 11 private static readonly byte[] jsonKeySteamId = JsonWriter.GetEncodedPropertyNameWithBeginObject ("steamid"); 12 private static readonly byte[] jsonKeyCrossPlatformId = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("crossplatformid"); 13 private static readonly byte[] jsonKeyEntityId = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("entityid"); 14 private static readonly byte[] jsonKeyIp = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("ip"); 15 private static readonly byte[] jsonKeyName = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("name"); 16 private static readonly byte[] jsonKeyOnline = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("online"); 17 private static readonly byte[] jsonKeyPosition = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("position"); 18 19 private static readonly byte[] jsonKeyLevel = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("level"); 20 private static readonly byte[] jsonKeyHealth = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("health"); 21 private static readonly byte[] jsonKeyStamina = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("stamina"); 22 private static readonly byte[] jsonKeyZombieKills = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("zombiekills"); 23 private static readonly byte[] jsonKeyPlayerKills = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("playerkills"); 24 private static readonly byte[] jsonKeyPlayerDeaths = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("playerdeaths"); 25 private static readonly byte[] jsonKeyScore = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("score"); 26 27 private static readonly byte[] jsonKeyTotalPlaytime = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("totalplaytime"); 28 private static readonly byte[] jsonKeyLastOnline = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("lastonline"); 29 private static readonly byte[] jsonKeyPing = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("ping"); 30 9 31 public override void HandleRequest (RequestContext _context) { 10 JSONArray players = new JSONArray (); 32 JsonWriter writer = new JsonWriter (); 33 34 writer.WriteBeginArray (); 35 36 bool first = true; 11 37 12 38 World w = GameManager.Instance.World; … … 15 41 Player player = PersistentContainer.Instance.Players.GetByInternalId (ci.InternalId); 16 42 17 JSONObject pos = new JSONObject (); 18 pos.Add ("x", new JSONNumber ((int) current.Value.GetPosition ().x)); 19 pos.Add ("y", new JSONNumber ((int) current.Value.GetPosition ().y)); 20 pos.Add ("z", new JSONNumber ((int) current.Value.GetPosition ().z)); 43 if (!first) { 44 writer.WriteValueSeparator (); 45 } 21 46 22 JSONObject p = new JSONObject (); 23 p.Add ("steamid", new JSONString (ci.PlatformId.CombinedString)); 24 p.Add ("crossplatformid", new JSONString (ci.CrossplatformId?.CombinedString ?? "")); 25 p.Add ("entityid", new JSONNumber (ci.entityId)); 26 p.Add ("ip", new JSONString (ci.ip)); 27 p.Add ("name", new JSONString (current.Value.EntityName)); 28 p.Add ("online", new JSONBoolean (true)); 29 p.Add ("position", pos); 47 first = false; 48 49 writer.WriteRaw (jsonKeySteamId); 50 writer.WriteString (ci.PlatformId.CombinedString); 51 52 writer.WriteRaw (jsonKeyCrossPlatformId); 53 writer.WriteString (ci.CrossplatformId?.CombinedString ?? ""); 54 55 writer.WriteRaw (jsonKeyEntityId); 56 writer.WriteInt32 (ci.entityId); 57 58 writer.WriteRaw (jsonKeyIp); 59 writer.WriteString (ci.ip); 60 61 writer.WriteRaw (jsonKeyName); 62 writer.WriteString (current.Value.EntityName); 63 64 writer.WriteRaw (jsonKeyOnline); 65 writer.WriteBoolean (true); 66 67 writer.WriteRaw (jsonKeyPosition); 68 JsonCommons.WriteVector3I (ref writer, new Vector3i (current.Value.GetPosition ())); 69 70 writer.WriteRaw (jsonKeyLevel); 71 writer.WriteSingle (player?.Level ?? -1); 72 73 writer.WriteRaw (jsonKeyHealth); 74 writer.WriteInt32 (current.Value.Health); 75 76 writer.WriteRaw (jsonKeyStamina); 77 writer.WriteSingle (current.Value.Stamina); 78 79 writer.WriteRaw (jsonKeyZombieKills); 80 writer.WriteInt32 (current.Value.KilledZombies); 81 82 writer.WriteRaw (jsonKeyPlayerKills); 83 writer.WriteInt32 (current.Value.KilledPlayers); 84 85 writer.WriteRaw (jsonKeyPlayerDeaths); 86 writer.WriteInt32 (current.Value.Died); 87 88 writer.WriteRaw (jsonKeyScore); 89 writer.WriteInt32 (current.Value.Score); 30 90 31 p.Add ("level", new JSONNumber (player?.Level ?? -1)); 32 p.Add ("health", new JSONNumber (current.Value.Health)); 33 p.Add ("stamina", new JSONNumber (current.Value.Stamina)); 34 p.Add ("zombiekills", new JSONNumber (current.Value.KilledZombies)); 35 p.Add ("playerkills", new JSONNumber (current.Value.KilledPlayers)); 36 p.Add ("playerdeaths", new JSONNumber (current.Value.Died)); 37 p.Add ("score", new JSONNumber (current.Value.Score)); 91 writer.WriteRaw (jsonKeyTotalPlaytime); 92 writer.WriteInt64 (player?.TotalPlayTime ?? -1); 93 94 writer.WriteRaw (jsonKeyLastOnline); 95 writer.WriteString (player != null ? player.LastOnline.ToString ("s") : string.Empty); 38 96 39 p.Add ("totalplaytime", new JSONNumber (player?.TotalPlayTime ?? -1)); 40 p.Add ("lastonline", new JSONString (player != null ? player.LastOnline.ToString ("s") : string.Empty)); 41 p.Add ("ping", new JSONNumber (ci.ping)); 42 43 players.Add (p); 97 writer.WriteRaw (jsonKeyPing); 98 writer.WriteInt32 (ci.ping); 99 100 writer.WriteEndObject (); 44 101 } 45 46 LegacyApiHelper.WriteJSON (_context.Response, players); 102 103 writer.WriteEndArray (); 104 105 WebUtils.WriteJsonData (_context.Response, ref writer); 47 106 } 48 107 } -
binary-improvements/MapRendering/API/GetServerInfo.cs
r454 r455 1 1 using System; 2 using AllocsFixes.JSON; 2 using JetBrains.Annotations; 3 using Utf8Json; 3 4 using Webserver; 4 5 using Webserver.WebAPI; 5 6 6 7 namespace AllocsFixes.WebAPIs { 8 [UsedImplicitly] 7 9 public class GetServerInfo : AbsWebAPI { 10 private static readonly byte[] jsonKeyType = JsonWriter.GetEncodedPropertyNameWithBeginObject ("type"); 11 private static readonly byte[] jsonKeyValue = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("value"); 12 8 13 public override void HandleRequest (RequestContext _context) { 9 JSONObject serverInfo = new JSONObject ();14 GameServerInfo gsi = ConnectionManager.Instance.LocalServerInfo; 10 15 11 GameServerInfo gsi = ConnectionManager.Instance.LocalServerInfo; 16 JsonWriter writer = new JsonWriter (); 17 writer.WriteBeginObject (); 18 19 bool first = true; 12 20 13 21 foreach (string stringGamePref in Enum.GetNames (typeof (GameInfoString))) { 14 22 string value = gsi.GetValue ((GameInfoString) Enum.Parse (typeof (GameInfoString), stringGamePref)); 23 24 if (!first) { 25 writer.WriteValueSeparator (); 26 } 15 27 16 JSONObject singleStat = new JSONObject (); 17 singleStat.Add ("type", new JSONString ("string")); 18 singleStat.Add ("value", new JSONString (value)); 28 first = false; 19 29 20 serverInfo.Add (stringGamePref, singleStat); 30 writer.WritePropertyName (stringGamePref); 31 writer.WriteRaw (jsonKeyType); 32 writer.WriteString ("string"); 33 34 writer.WriteRaw (jsonKeyValue); 35 writer.WriteString (value); 36 37 writer.WriteEndObject (); 21 38 } 22 39 … … 24 41 int value = gsi.GetValue ((GameInfoInt) Enum.Parse (typeof (GameInfoInt), intGamePref)); 25 42 26 JSONObject singleStat = new JSONObject ();27 singleStat.Add ("type", new JSONString ("int"));28 singleStat.Add ("value", new JSONNumber (value));43 if (!first) { 44 writer.WriteValueSeparator (); 45 } 29 46 30 serverInfo.Add (intGamePref, singleStat); 47 first = false; 48 49 writer.WritePropertyName (intGamePref); 50 writer.WriteRaw (jsonKeyType); 51 writer.WriteString ("int"); 52 53 writer.WriteRaw (jsonKeyValue); 54 writer.WriteInt32 (value); 55 56 writer.WriteEndObject (); 31 57 } 32 58 … … 34 60 bool value = gsi.GetValue ((GameInfoBool) Enum.Parse (typeof (GameInfoBool), boolGamePref)); 35 61 36 JSONObject singleStat = new JSONObject ();37 singleStat.Add ("type", new JSONString ("bool"));38 singleStat.Add ("value", new JSONBoolean (value));62 if (!first) { 63 writer.WriteValueSeparator (); 64 } 39 65 40 serverInfo.Add (boolGamePref, singleStat); 66 first = false; 67 68 writer.WritePropertyName (boolGamePref); 69 writer.WriteRaw (jsonKeyType); 70 writer.WriteString ("bool"); 71 72 writer.WriteRaw (jsonKeyValue); 73 writer.WriteBoolean (value); 74 75 writer.WriteEndObject (); 41 76 } 42 43 44 LegacyApiHelper.WriteJSON (_context.Response, serverInfo); 77 78 writer.WriteEndObject (); 79 80 WebUtils.WriteJsonData (_context.Response, ref writer); 45 81 } 46 82 } -
binary-improvements/MapRendering/API/GetStats.cs
r454 r455 1 using AllocsFixes.JSON;2 1 using AllocsFixes.LiveData; 2 using JetBrains.Annotations; 3 using Utf8Json; 3 4 using Webserver; 4 5 using Webserver.WebAPI; 5 6 6 7 namespace AllocsFixes.WebAPIs { 8 [UsedImplicitly] 7 9 public class GetStats : AbsWebAPI { 10 private static readonly byte[] jsonKeyGameTime = JsonWriter.GetEncodedPropertyNameWithBeginObject ("gametime"); 11 12 private static readonly byte[] jsonKeyPlayers = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("players"); 13 private static readonly byte[] jsonKeyHostiles = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("hostiles"); 14 private static readonly byte[] jsonKeyAnimals = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("animals"); 15 8 16 public override void HandleRequest (RequestContext _context) { 9 JSONObject result = new JSONObject (); 10 11 JSONObject time = new JSONObject (); 12 time.Add ("days", new JSONNumber (GameUtils.WorldTimeToDays (GameManager.Instance.World.worldTime))); 13 time.Add ("hours", new JSONNumber (GameUtils.WorldTimeToHours (GameManager.Instance.World.worldTime))); 14 time.Add ("minutes", new JSONNumber (GameUtils.WorldTimeToMinutes (GameManager.Instance.World.worldTime))); 15 result.Add ("gametime", time); 16 17 result.Add ("players", new JSONNumber (GameManager.Instance.World.Players.Count)); 18 result.Add ("hostiles", new JSONNumber (Hostiles.Instance.GetCount ())); 19 result.Add ("animals", new JSONNumber (Animals.Instance.GetCount ())); 20 21 LegacyApiHelper.WriteJSON (_context.Response, result); 17 JsonWriter writer = new JsonWriter (); 18 19 writer.WriteRaw (jsonKeyGameTime); 20 (int days, int hours, int minutes) = GameUtils.WorldTimeToElements (GameManager.Instance.World.worldTime); 21 JsonCommons.WriteGameTimeObject (ref writer, days, hours, minutes); 22 23 writer.WriteRaw (jsonKeyPlayers); 24 writer.WriteInt32 (GameManager.Instance.World.Players.Count); 25 26 writer.WriteRaw (jsonKeyHostiles); 27 writer.WriteInt32 (Hostiles.Instance.GetCount ()); 28 29 writer.WriteRaw (jsonKeyAnimals); 30 writer.WriteInt32 (Animals.Instance.GetCount ()); 31 32 writer.WriteEndObject (); 33 34 WebUtils.WriteJsonData (_context.Response, ref writer); 22 35 } 23 36 -
binary-improvements/MapRendering/API/GetWebUIUpdates.cs
r454 r455 1 using AllocsFixes.JSON;2 1 using AllocsFixes.LiveData; 2 using JetBrains.Annotations; 3 using Utf8Json; 3 4 using Webserver; 4 5 using Webserver.WebAPI; 5 6 6 7 namespace AllocsFixes.WebAPIs { 8 [UsedImplicitly] 7 9 public class GetWebUIUpdates : AbsWebAPI { 10 private static readonly byte[] jsonKeyGameTime = JsonWriter.GetEncodedPropertyNameWithBeginObject ("gametime"); 11 12 private static readonly byte[] jsonKeyPlayers = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("players"); 13 private static readonly byte[] jsonKeyHostiles = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("hostiles"); 14 private static readonly byte[] jsonKeyAnimals = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("animals"); 15 private static readonly byte[] jsonKeyNewLogs = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("newlogs"); 16 8 17 public override void HandleRequest (RequestContext _context) { 9 18 int latestLine; … … 13 22 } 14 23 15 J SONObject result = new JSONObject();24 JsonWriter writer = new JsonWriter (); 16 25 17 JSONObject time = new JSONObject (); 18 time.Add ("days", new JSONNumber (GameUtils.WorldTimeToDays (GameManager.Instance.World.worldTime))); 19 time.Add ("hours", new JSONNumber (GameUtils.WorldTimeToHours (GameManager.Instance.World.worldTime))); 20 time.Add ("minutes", new JSONNumber (GameUtils.WorldTimeToMinutes (GameManager.Instance.World.worldTime))); 21 result.Add ("gametime", time); 22 23 result.Add ("players", new JSONNumber (GameManager.Instance.World.Players.Count)); 24 result.Add ("hostiles", new JSONNumber (Hostiles.Instance.GetCount ())); 25 result.Add ("animals", new JSONNumber (Animals.Instance.GetCount ())); 26 27 result.Add ("newlogs", new JSONNumber (LogBuffer.Instance.LatestLine - latestLine)); 28 29 LegacyApiHelper.WriteJSON (_context.Response, result); 26 writer.WriteRaw (jsonKeyGameTime); 27 (int days, int hours, int minutes) = GameUtils.WorldTimeToElements (GameManager.Instance.World.worldTime); 28 JsonCommons.WriteGameTimeObject (ref writer, days, hours, minutes); 29 30 writer.WriteRaw (jsonKeyPlayers); 31 writer.WriteInt32 (GameManager.Instance.World.Players.Count); 32 33 writer.WriteRaw (jsonKeyHostiles); 34 writer.WriteInt32 (Hostiles.Instance.GetCount ()); 35 36 writer.WriteRaw (jsonKeyAnimals); 37 writer.WriteInt32 (Animals.Instance.GetCount ()); 38 39 writer.WriteRaw (jsonKeyNewLogs); 40 writer.WriteInt32 (LogBuffer.Instance.LatestLine - latestLine); 41 42 writer.WriteEndObject (); 43 44 WebUtils.WriteJsonData (_context.Response, ref writer); 30 45 } 31 46 -
binary-improvements/MapRendering/ModInfo.xml
r454 r455 5 5 <Description value="Render the game map to image map tiles as it is uncovered" /> 6 6 <Author value="Christian 'Alloc' Illy" /> 7 <Version value="4 3" />8 <Website value="http ://7dtd.illy.bz" />7 <Version value="44" /> 8 <Website value="https://7dtd.illy.bz" /> 9 9 </ModInfo> 10 10 </xml> -
binary-improvements/MapRendering/SteamLoginApi.cs
r454 r455 1 using System;2 1 using System.Net; 3 using Platform.Steam;2 using JetBrains.Annotations; 4 3 using Webserver; 5 4 using Webserver.UrlHandlers; 6 5 using Webserver.WebAPI; 7 6 8 namespace AllocsFixes { 7 namespace AllocsFixes.Web { 8 [UsedImplicitly] 9 9 public class SteamLoginApi : AbsWebAPI { 10 10 public override int DefaultPermissionLevel () => 2000; … … 15 15 private const string steamLoginUrl = "loginsteam"; 16 16 17 public SteamLoginApi (Web _parentWeb) : base(_parentWeb) {17 public SteamLoginApi (Webserver.Web _parentWeb) : base(_parentWeb) { 18 18 } 19 19 … … 43 43 44 44 if (subpath.StartsWith (steamLoginUrl)) { 45 varabsoluteUrl = _context.Request.Url.AbsolutePath;45 string absoluteUrl = _context.Request.Url.AbsolutePath; 46 46 absoluteUrl = absoluteUrl.Substring (0, absoluteUrl.Length - _context.RequestPath.Length); 47 47 SessionHandler.HandleSteamLogin (_context, $"{absoluteUrl}{steamOpenIdVerifyUrl}"); -
binary-improvements/MapRendering/WebAndMapRendering.csproj
r454 r455 89 89 <Private>False</Private> 90 90 </Reference> 91 <Reference Include="Utf8Json"> 92 <HintPath>..\7dtd-binaries\Utf8Json.dll</HintPath> 93 <Private>False</Private> 94 </Reference> 91 95 <Reference Include="WebServer, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"> 92 96 <HintPath>..\7dtd-binaries\WebServer.dll</HintPath> … … 98 102 <Compile Include="API\GetAllowedCommands.cs" /> 99 103 <Compile Include="API\GetAnimalsLocation.cs" /> 104 <Compile Include="API\GetEntityListAbs.cs" /> 100 105 <Compile Include="API\GetHostileLocation.cs" /> 101 106 <Compile Include="API\GetLandClaims.cs" /> … … 111 116 <Compile Include="AssemblyInfo.cs" /> 112 117 <Compile Include="API.cs" /> 113 <Compile Include="LegacyApiHelper.cs" />114 118 <Compile Include="SteamLoginApi.cs" /> 115 119 <Compile Include="WebCommandResult.cs" /> -
binary-improvements/MapRendering/WebCommandResult.cs
r454 r455 5 5 using System.Text; 6 6 using System.Threading; 7 using AllocsFixes.JSON;8 7 using UnityEngine; 8 using Utf8Json; 9 9 using Webserver; 10 10 11 namespace AllocsFixes. NetConnections.Servers.Web {11 namespace AllocsFixes.Web { 12 12 public class WebCommandResult : IConsoleConnection { 13 13 public enum ResultType { 14 14 Full, 15 15 ResultOnly, 16 Raw 16 Raw, 17 17 } 18 18 … … 35 35 responseType = _resultType; 36 36 } 37 38 private static readonly byte[] jsonKeyCommand = JsonWriter.GetEncodedPropertyNameWithBeginObject ("command"); 39 private static readonly byte[] jsonKeyParameters = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("parameters"); 40 private static readonly byte[] jsonKeyResult = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("result"); 37 41 38 42 public void SendLines (List<string> _output) { … … 44 48 } 45 49 50 string result = sb.ToString (); 51 46 52 try { 47 53 context.Response.SendChunked = false; 48 54 49 55 if (responseType == ResultType.Raw) { 50 WebUtils.WriteText (context.Response, sb.ToString ());56 WebUtils.WriteText (context.Response, result); 51 57 } else { 52 JSONNode result; 58 JsonWriter writer = new JsonWriter (); 59 53 60 if (responseType == ResultType.ResultOnly) { 54 result = new JSONString (sb.ToString ());61 writer.WriteString (result); 55 62 } else { 56 JSONObject resultObj = new JSONObject (); 57 58 resultObj.Add ("command", new JSONString (command)); 59 resultObj.Add ("parameters", new JSONString (parameters)); 60 resultObj.Add ("result", new JSONString (sb.ToString ())); 61 62 result = resultObj; 63 writer.WriteRaw (jsonKeyCommand); 64 writer.WriteString (command); 65 66 writer.WriteRaw (jsonKeyParameters); 67 writer.WriteString (parameters); 68 69 writer.WriteRaw (jsonKeyResult); 70 writer.WriteString (result); 71 72 writer.WriteEndObject (); 63 73 } 64 74 65 LegacyApiHelper.WriteJSON (context.Response, result);75 WebUtils.WriteJsonData (context.Response, ref writer); 66 76 } 67 77 } catch (IOException e) { 68 78 if (e.InnerException is SocketException) { 69 Log.Out ( "Error in WebCommandResult.SendLines(): Remote host closed connection: " + e.InnerException.Message);79 Log.Out ($"Error in WebCommandResult.SendLines(): Remote host closed connection: {e.InnerException.Message}"); 70 80 } else { 71 Log.Out ( "Error (IO) in WebCommandResult.SendLines(): " + e);81 Log.Out ($"Error (IO) in WebCommandResult.SendLines(): {e}"); 72 82 } 73 83 } catch (Exception e) { 74 Log.Out ( "Error in WebCommandResult.SendLines(): " + e);84 Log.Out ($"Error in WebCommandResult.SendLines(): {e}"); 75 85 } finally { 76 86 context.Response?.Close (); … … 99 109 100 110 public string GetDescription () { 101 return "WebCommandResult_for_" + command;111 return $"WebCommandResult_for_{command}"; 102 112 } 103 113 }
Note:
See TracChangeset
for help on using the changeset viewer.