Changeset 325 for binary-improvements
- Timestamp:
- Sep 4, 2018, 1:00:48 PM (6 years ago)
- Location:
- binary-improvements
- Files:
-
- 86 edited
Legend:
- Unmodified
- Added
- Removed
-
binary-improvements/7dtd-server-fixes/src/API.cs
r324 r325 1 using System;2 1 using System.Collections.Generic; 3 2 4 namespace AllocsFixes 5 { 3 namespace AllocsFixes { 6 4 public class API : IModApi { 5 public void InitMod () { 6 ModEvents.GameAwake.RegisterHandler (GameAwake); 7 ModEvents.GameShutdown.RegisterHandler (GameShutdown); 8 ModEvents.SavePlayerData.RegisterHandler (SavePlayerData); 9 ModEvents.PlayerSpawning.RegisterHandler (PlayerSpawning); 10 ModEvents.PlayerDisconnected.RegisterHandler (PlayerDisconnected); 11 ModEvents.ChatMessage.RegisterHandler (ChatMessage); 12 } 7 13 8 14 public void GameAwake () { … … 13 19 StateManager.Shutdown (); 14 20 } 15 21 16 22 public void SavePlayerData (ClientInfo _cInfo, PlayerDataFile _playerDataFile) { 17 23 PlayerDataStuff.GM_SavePlayerData (_cInfo, _playerDataFile); … … 21 27 AllocsLogFunctions.RequestToSpawnPlayer (_cInfo, _chunkViewDim, _playerProfile); 22 28 } 23 29 24 30 public void PlayerDisconnected (ClientInfo _cInfo, bool _bShutdown) { 25 31 AllocsLogFunctions.PlayerDisconnected (_cInfo, _bShutdown); 26 32 } 27 33 28 public bool ChatMessage (ClientInfo _cInfo, EChatType _type, int _senderId, string _msg, string _mainName, bool _localizeMain, List<int> _recipientEntityIds) { 34 public bool ChatMessage (ClientInfo _cInfo, EChatType _type, int _senderId, string _msg, string _mainName, 35 bool _localizeMain, List<int> _recipientEntityIds) { 29 36 return ChatHookExample.Hook (_cInfo, _type, _msg, _mainName); 30 }31 32 public void InitMod () {33 ModEvents.GameAwake.RegisterHandler (GameAwake);34 ModEvents.GameShutdown.RegisterHandler (GameShutdown);35 ModEvents.SavePlayerData.RegisterHandler (SavePlayerData);36 ModEvents.PlayerSpawning.RegisterHandler (PlayerSpawning);37 ModEvents.PlayerDisconnected.RegisterHandler (PlayerDisconnected);38 ModEvents.ChatMessage.RegisterHandler (ChatMessage);39 37 } 40 38 } 41 39 } 42 -
binary-improvements/7dtd-server-fixes/src/AllocsLogFunctions.cs
r273 r325 1 using System; 1 2 using AllocsFixes.PersistentData; 2 using System;3 using System.Collections.Generic;4 using UnityEngine;5 3 6 namespace AllocsFixes 7 { 8 public class AllocsLogFunctions 9 { 10 public static void RequestToSpawnPlayer (ClientInfo _cInfo, int _chunkViewDim, PlayerProfile _playerProfile) 11 { 4 namespace AllocsFixes { 5 public class AllocsLogFunctions { 6 public static void RequestToSpawnPlayer (ClientInfo _cInfo, int _chunkViewDim, PlayerProfile _playerProfile) { 12 7 try { 13 8 Log.Out ("Player connected" + 14 15 16 17 18 9 ", entityid=" + _cInfo.entityId + 10 ", name=" + _cInfo.playerName + 11 ", steamid=" + _cInfo.playerId + 12 ", steamOwner=" + _cInfo.ownerId + 13 ", ip=" + _cInfo.ip 19 14 ); 20 15 21 16 PersistentContainer.Instance.Players [_cInfo.playerId, true].SetOnline (_cInfo); 22 Persistent Data.PersistentContainer.Instance.Save ();17 PersistentContainer.Instance.Save (); 23 18 } catch (Exception e) { 24 19 Log.Out ("Error in AllocsLogFunctions.RequestToSpawnPlayer: " + e); … … 26 21 } 27 22 28 public static void PlayerDisconnected (ClientInfo _cInfo, bool _bShutdown) 29 { 23 public static void PlayerDisconnected (ClientInfo _cInfo, bool _bShutdown) { 30 24 try { 31 25 Player p = PersistentContainer.Instance.Players [_cInfo.playerId, true]; … … 35 29 Log.Out ("Disconnected player not found in client list..."); 36 30 } 37 PersistentData.PersistentContainer.Instance.Save (); 31 32 PersistentContainer.Instance.Save (); 38 33 } catch (Exception e) { 39 34 Log.Out ("Error in AllocsLogFunctions.PlayerDisconnected: " + e); -
binary-improvements/7dtd-server-fixes/src/AllocsUtils.cs
r253 r325 1 using System;1 using UnityEngine; 2 2 3 namespace AllocsFixes 4 { 3 namespace AllocsFixes { 5 4 public static class AllocsUtils { 6 7 public static string ColorToHex (UnityEngine.Color _color) {8 return string.Format ("{0:X02}{1:X02}{2:X02}", (int)(_color.r * 255), (int)(_color.g * 255), (int)(_color.b * 255));5 public static string ColorToHex (Color _color) { 6 return string.Format ("{0:X02}{1:X02}{2:X02}", (int) (_color.r * 255), (int) (_color.g * 255), 7 (int) (_color.b * 255)); 9 8 } 10 11 9 } 12 10 } 13 -
binary-improvements/7dtd-server-fixes/src/AssemblyInfo.cs
r244 r325 1 1 using System.Reflection; 2 using System.Runtime.CompilerServices;3 2 4 3 // Information about this assembly is defined by the following attributes. 5 4 // Change them to the values specific to your project. 6 5 7 [assembly: AssemblyTitle ("7dtd-server-fixes")]8 [assembly: AssemblyDescription ("")]9 [assembly: AssemblyConfiguration ("")]10 [assembly: AssemblyCompany ("")]11 [assembly: AssemblyProduct ("")]12 [assembly: AssemblyCopyright ("Alloc")]13 [assembly: AssemblyTrademark ("")]14 [assembly: AssemblyCulture ("")]6 [assembly: AssemblyTitle ("7dtd-server-fixes")] 7 [assembly: AssemblyDescription ("")] 8 [assembly: AssemblyConfiguration ("")] 9 [assembly: AssemblyCompany ("")] 10 [assembly: AssemblyProduct ("")] 11 [assembly: AssemblyCopyright ("Alloc")] 12 [assembly: AssemblyTrademark ("")] 13 [assembly: AssemblyCulture ("")] 15 14 16 15 // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". … … 18 17 // and "{Major}.{Minor}.{Build}.*" will update just the revision. 19 18 20 [assembly: AssemblyVersion ("0.0.0.0")]19 [assembly: AssemblyVersion ("0.0.0.0")] 21 20 22 21 // The following attributes are used to specify the signing key for the assembly, … … 25 24 //[assembly: AssemblyDelaySign(false)] 26 25 //[assembly: AssemblyKeyFile("")] 27 -
binary-improvements/7dtd-server-fixes/src/BlockingQueue.cs
r190 r325 1 using System;2 1 using System.Collections.Generic; 3 2 using System.Threading; 4 3 5 namespace AllocsFixes 6 { 7 public class BlockingQueue<T> 8 { 9 private bool closing = false; 10 private Queue<T> queue = new Queue<T> (); 4 namespace AllocsFixes { 5 public class BlockingQueue<T> { 6 private readonly Queue<T> queue = new Queue<T> (); 7 private bool closing; 11 8 12 public void Enqueue (T item) 13 { 9 public void Enqueue (T item) { 14 10 lock (queue) { 15 11 queue.Enqueue (item); … … 18 14 } 19 15 20 public T Dequeue () 21 { 16 public T Dequeue () { 22 17 lock (queue) { 23 18 while (queue.Count == 0) { 24 19 if (closing) { 25 return default (T);20 return default (T); 26 21 } 22 27 23 Monitor.Wait (queue); 28 24 } 25 29 26 return queue.Dequeue (); 30 27 } 31 28 } 32 29 33 public void Close () 34 { 30 public void Close () { 35 31 lock (queue) { 36 32 closing = true; … … 38 34 } 39 35 } 40 41 36 } 42 37 } 43 -
binary-improvements/7dtd-server-fixes/src/ChatHookExample.cs
r324 r325 1 using System; 2 3 namespace AllocsFixes 4 { 1 namespace AllocsFixes { 5 2 public class ChatHookExample { 6 private const string ANSWER = " [ff0000]I[-] [ff7f00]W[-][ffff00]A[-][80ff00]S[-] [00ffff]H[-][0080ff]E[-][0000ff]R[-][8b00ff]E[-]"; 3 private const string ANSWER = 4 " [ff0000]I[-] [ff7f00]W[-][ffff00]A[-][80ff00]S[-] [00ffff]H[-][0080ff]E[-][0000ff]R[-][8b00ff]E[-]"; 7 5 8 6 public static bool Hook (ClientInfo _cInfo, EChatType _type, string _message, string _playerName) { … … 11 9 if (_cInfo != null) { 12 10 Log.Out ("Sent chat hook reply to {0}", _cInfo.playerId); 13 _cInfo.SendPackage (new NetPackageChat (EChatType.Whisper, -1, ANSWER, "", false, null));11 _cInfo.SendPackage (new NetPackageChat (EChatType.Whisper, -1, ANSWER, "", false, null)); 14 12 } else { 15 13 Log.Error ("ChatHookExample: Argument _cInfo null on message: {0}", _message); 16 14 } 15 17 16 return false; 18 17 } … … 21 20 return true; 22 21 } 23 24 22 } 25 23 } -
binary-improvements/7dtd-server-fixes/src/FileCache/AbstractCache.cs
r324 r325 1 1 namespace AllocsFixes.FileCache { 2 public abstract class AbstractCache { 3 public AbstractCache () { 4 } 5 6 public abstract byte[] GetFileContent (string filename); 7 } 2 public abstract class AbstractCache { 3 public abstract byte[] GetFileContent (string filename); 4 } 8 5 } -
binary-improvements/7dtd-server-fixes/src/FileCache/DirectAccess.cs
r199 r325 1 1 using System; 2 using System.Collections.Generic;3 2 using System.IO; 4 3 5 namespace AllocsFixes.FileCache 6 { 4 namespace AllocsFixes.FileCache { 7 5 // Not caching at all, simply reading from disk on each request 8 public class DirectAccess : AbstractCache 9 { 10 11 public DirectAccess () 12 { 13 } 14 15 public override byte[] GetFileContent (string filename) 16 { 6 public class DirectAccess : AbstractCache { 7 public override byte[] GetFileContent (string filename) { 17 8 try { 18 9 if (!File.Exists (filename)) { … … 24 15 Log.Out ("Error in DirectAccess.GetFileContent: " + e); 25 16 } 17 26 18 return null; 27 19 } 28 29 20 } 30 21 } 31 -
binary-improvements/7dtd-server-fixes/src/FileCache/MapTileCache.cs
r324 r325 2 2 using System.IO; 3 3 using UnityEngine; 4 using Object = UnityEngine.Object; 4 5 5 namespace AllocsFixes.FileCache 6 { 6 namespace AllocsFixes.FileCache { 7 7 // Special "cache" for map tile folder as both map rendering and webserver access files in there. 8 8 // Only map rendering tiles are cached. Writing is done by WriteThrough. 9 public class MapTileCache : AbstractCache 10 { 11 private struct CurrentZoomFile 12 { 13 public string filename; 14 public byte[] data; 15 } 16 9 public class MapTileCache : AbstractCache { 10 private readonly byte[] transparentTile; 17 11 private CurrentZoomFile[] cache; 18 12 19 private byte[] transparentTile; 20 21 public MapTileCache (int _tileSize) 22 { 13 public MapTileCache (int _tileSize) { 23 14 Texture2D tex = new Texture2D (_tileSize, _tileSize); 24 15 Color nullColor = new Color (0, 0, 0, 0); … … 28 19 } 29 20 } 21 30 22 transparentTile = tex.EncodeToPNG (); 31 UnityEngine.Object.Destroy (tex);23 Object.Destroy (tex); 32 24 } 33 25 34 public void SetZoomCount (int count) 35 { 26 public void SetZoomCount (int count) { 36 27 cache = new CurrentZoomFile[count]; 37 28 } 38 29 39 public byte[] LoadTile (int zoomlevel, string filename) 40 { 30 public byte[] LoadTile (int zoomlevel, string filename) { 41 31 try { 42 32 lock (cache) { … … 51 41 cache [zoomlevel].data = File.ReadAllBytes (filename); 52 42 } 43 53 44 return cache [zoomlevel].data; 54 45 } … … 56 47 Log.Out ("Error in MapTileCache.LoadTile: " + e); 57 48 } 49 58 50 return null; 59 51 } 60 52 61 public void SaveTile (int zoomlevel, byte[] content) 62 { 53 public void SaveTile (int zoomlevel, byte[] content) { 63 54 try { 64 55 lock (cache) { … … 73 64 } 74 65 75 public override byte[] GetFileContent (string filename) 76 { 66 public override byte[] GetFileContent (string filename) { 77 67 try { 78 68 lock (cache) { 79 69 foreach (CurrentZoomFile czf in cache) { 80 if (czf.filename != null && czf.filename.Equals (filename)) 70 if (czf.filename != null && czf.filename.Equals (filename)) { 81 71 return czf.data; 72 } 82 73 } 83 74 … … 85 76 return transparentTile; 86 77 } 78 87 79 return File.ReadAllBytes (filename); 88 80 } … … 90 82 Log.Out ("Error in MapTileCache.GetFileContent: " + e); 91 83 } 84 92 85 return null; 93 86 } 94 87 88 private struct CurrentZoomFile { 89 public string filename; 90 public byte[] data; 91 } 95 92 } 96 93 } 97 -
binary-improvements/7dtd-server-fixes/src/FileCache/SimpleCache.cs
r199 r325 3 3 using System.IO; 4 4 5 namespace AllocsFixes.FileCache 6 { 5 namespace AllocsFixes.FileCache { 7 6 // Caching all files, useful for completely static folders only 8 public class SimpleCache : AbstractCache 9 {7 public class SimpleCache : AbstractCache { 8 private readonly Dictionary<string, byte[]> fileCache = new Dictionary<string, byte[]> (); 10 9 11 private Dictionary<string, byte[]> fileCache = new Dictionary<string, byte[]> (); 12 13 public SimpleCache () 14 { 15 } 16 17 public override byte[] GetFileContent (string filename) 18 { 10 public override byte[] GetFileContent (string filename) { 19 11 try { 20 12 lock (fileCache) { … … 32 24 Log.Out ("Error in SimpleCache.GetFileContent: " + e); 33 25 } 26 34 27 return null; 35 28 } 36 37 29 } 38 30 } 39 -
binary-improvements/7dtd-server-fixes/src/JSON/JSONArray.cs
r315 r325 1 using System;2 1 using System.Collections.Generic; 3 2 using System.Text; 4 3 5 namespace AllocsFixes.JSON 6 { 7 public class JSONArray : JSONNode 8 { 9 private List<JSONNode> nodes = new List<JSONNode> (); 4 namespace AllocsFixes.JSON { 5 public class JSONArray : JSONNode { 6 private readonly List<JSONNode> nodes = new List<JSONNode> (); 10 7 11 8 public JSONNode this [int index] { … … 18 15 } 19 16 20 public void Add (JSONNode node) 21 { 17 public void Add (JSONNode node) { 22 18 nodes.Add (node); 23 19 } 24 20 25 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0) 26 { 21 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0) { 27 22 stringBuilder.Append ("["); 28 if (prettyPrint) 23 if (prettyPrint) { 29 24 stringBuilder.Append ('\n'); 25 } 26 30 27 foreach (JSONNode n in nodes) { 31 if (prettyPrint) 32 stringBuilder.Append (new String ('\t', currentLevel + 1)); 28 if (prettyPrint) { 29 stringBuilder.Append (new string ('\t', currentLevel + 1)); 30 } 31 33 32 n.ToString (stringBuilder, prettyPrint, currentLevel + 1); 34 33 stringBuilder.Append (","); 35 if (prettyPrint) 34 if (prettyPrint) { 36 35 stringBuilder.Append ('\n'); 36 } 37 37 } 38 if (nodes.Count > 0) 38 39 if (nodes.Count > 0) { 39 40 stringBuilder.Remove (stringBuilder.Length - (prettyPrint ? 2 : 1), 1); 40 if (prettyPrint) 41 stringBuilder.Append (new String ('\t', currentLevel)); 41 } 42 43 if (prettyPrint) { 44 stringBuilder.Append (new string ('\t', currentLevel)); 45 } 46 42 47 stringBuilder.Append ("]"); 43 48 } 44 49 45 public static JSONArray Parse (string json, ref int offset) 46 { 50 public static JSONArray Parse (string json, ref int offset) { 47 51 //Log.Out ("ParseArray enter (" + offset + ")"); 48 52 JSONArray arr = new JSONArray (); … … 58 62 nextElemAllowed = true; 59 63 offset++; 60 } else 61 throw new MalformedJSONException ("Could not parse array, found a comma without a value first"); 64 } else { 65 throw new MalformedJSONException ( 66 "Could not parse array, found a comma without a value first"); 67 } 68 62 69 break; 63 70 case ']': 64 71 offset++; 72 65 73 //Log.Out ("JSON:Parsed Array: " + arr.ToString ()); 66 74 return arr; … … 72 80 } 73 81 } 74 75 82 } 76 83 } 77 -
binary-improvements/7dtd-server-fixes/src/JSON/JSONBoolean.cs
r309 r325 1 using System;2 1 using System.Text; 3 2 4 namespace AllocsFixes.JSON 5 { 6 public class JSONBoolean : JSONValue 7 { 8 private bool value; 3 namespace AllocsFixes.JSON { 4 public class JSONBoolean : JSONValue { 5 private readonly bool value; 9 6 10 public JSONBoolean (bool value) 11 { 7 public JSONBoolean (bool value) { 12 8 this.value = value; 13 9 } 14 10 15 public bool GetBool () 16 { 11 public bool GetBool () { 17 12 return value; 18 13 } 19 14 20 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0) 21 { 15 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0) { 22 16 stringBuilder.Append (value ? "true" : "false"); 23 17 } 24 18 25 public static JSONBoolean Parse (string json, ref int offset) 26 { 19 public static JSONBoolean Parse (string json, ref int offset) { 27 20 //Log.Out ("ParseBool enter (" + offset + ")"); 28 21 … … 31 24 offset += 4; 32 25 return new JSONBoolean (true); 33 } else if (json.Substring (offset, 5).Equals ("false")) { 26 } 27 28 if (json.Substring (offset, 5).Equals ("false")) { 34 29 //Log.Out ("JSON:Parsed Bool: false"); 35 30 offset += 5; 36 31 return new JSONBoolean (false); 37 } else {38 throw new MalformedJSONException ("No valid boolean found");39 32 } 33 34 throw new MalformedJSONException ("No valid boolean found"); 40 35 } 41 42 36 } 43 37 } 44 -
binary-improvements/7dtd-server-fixes/src/JSON/JSONNode.cs
r309 r325 1 using System;2 1 using System.Text; 3 2 4 namespace AllocsFixes.JSON 5 { 6 public abstract class JSONNode 7 { 8 public abstract void ToString(StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0); 3 namespace AllocsFixes.JSON { 4 public abstract class JSONNode { 5 public abstract void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0); 9 6 10 7 public override string ToString () { -
binary-improvements/7dtd-server-fixes/src/JSON/JSONNull.cs
r309 r325 1 using System;2 1 using System.Text; 3 2 4 namespace AllocsFixes.JSON 5 { 6 public class JSONNull : JSONValue 7 { 8 public JSONNull () 9 { 10 } 11 12 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0) 13 { 3 namespace AllocsFixes.JSON { 4 public class JSONNull : JSONValue { 5 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0) { 14 6 stringBuilder.Append ("null"); 15 7 } 16 8 17 public static JSONNull Parse (string json, ref int offset) 18 { 9 public static JSONNull Parse (string json, ref int offset) { 19 10 //Log.Out ("ParseNull enter (" + offset + ")"); 20 11 … … 23 14 offset += 4; 24 15 return new JSONNull (); 25 } else {26 throw new MalformedJSONException ("No valid null value found");27 16 } 17 18 throw new MalformedJSONException ("No valid null value found"); 28 19 } 29 30 20 } 31 21 } 32 -
binary-improvements/7dtd-server-fixes/src/JSON/JSONNumber.cs
r324 r325 2 2 using System.Text; 3 3 4 namespace AllocsFixes.JSON 5 { 6 public class JSONNumber : JSONValue 7 { 8 private double value; 4 namespace AllocsFixes.JSON { 5 public class JSONNumber : JSONValue { 6 private readonly double value; 9 7 10 public JSONNumber (double value) 11 { 8 public JSONNumber (double value) { 12 9 this.value = value; 13 10 } 14 11 15 public double GetDouble () 16 { 12 public double GetDouble () { 17 13 return value; 18 14 } 19 15 20 public int GetInt () 21 { 22 return (int)Math.Round(value); 16 public int GetInt () { 17 return (int) Math.Round (value); 23 18 } 24 19 25 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0) 26 { 20 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0) { 27 21 stringBuilder.Append (value.ToCultureInvariantString ()); 28 22 } 29 23 30 public static JSONNumber Parse (string json, ref int offset) 31 { 24 public static JSONNumber Parse (string json, ref int offset) { 32 25 //Log.Out ("ParseNumber enter (" + offset + ")"); 33 26 StringBuilder sbNum = new StringBuilder (); … … 37 30 while (offset < json.Length) { 38 31 if (json [offset] >= '0' && json [offset] <= '9') { 39 if (hasExp) 32 if (hasExp) { 40 33 sbExp.Append (json [offset]); 41 else34 } else { 42 35 sbNum.Append (json [offset]); 36 } 43 37 } else if (json [offset] == '.') { 44 38 if (hasExp) { 45 39 throw new MalformedJSONException ("Decimal separator in exponent"); 40 } 41 42 if (hasDec) { 43 throw new MalformedJSONException ("Multiple decimal separators in number found"); 44 } 45 46 if (sbNum.Length == 0) { 47 throw new MalformedJSONException ("No leading digits before decimal separator found"); 48 } 49 50 sbNum.Append ('.'); 51 hasDec = true; 52 } else if (json [offset] == '-') { 53 if (hasExp) { 54 if (sbExp.Length > 0) { 55 throw new MalformedJSONException ("Negative sign in exponent after digits"); 56 } 57 58 sbExp.Append (json [offset]); 46 59 } else { 47 if (hasDec) 48 throw new MalformedJSONException ("Multiple decimal separators in number found"); 49 else if (sbNum.Length == 0) { 50 throw new MalformedJSONException ("No leading digits before decimal separator found"); 51 } else { 52 sbNum.Append ('.'); 53 hasDec = true; 60 if (sbNum.Length > 0) { 61 throw new MalformedJSONException ("Negative sign in mantissa after digits"); 54 62 } 55 } 56 } else if (json [offset] == '-') { 57 if (hasExp) { 58 if (sbExp.Length > 0) 59 throw new MalformedJSONException ("Negative sign in exponent after digits"); 60 else 61 sbExp.Append (json [offset]); 62 } else { 63 if (sbNum.Length > 0) 64 throw new MalformedJSONException ("Negative sign in mantissa after digits"); 65 else 66 sbNum.Append (json [offset]); 63 64 sbNum.Append (json [offset]); 67 65 } 68 66 } else if (json [offset] == 'e' || json [offset] == 'E') { 69 if (hasExp) 67 if (hasExp) { 70 68 throw new MalformedJSONException ("Multiple exponential markers in number found"); 71 else if (sbNum.Length == 0) { 69 } 70 71 if (sbNum.Length == 0) { 72 72 throw new MalformedJSONException ("No leading digits before exponential marker found"); 73 } else {74 sbExp = new StringBuilder ();75 hasExp = true;76 73 } 74 75 sbExp = new StringBuilder (); 76 hasExp = true; 77 77 } else if (json [offset] == '+') { 78 78 if (hasExp) { 79 if (sbExp.Length > 0) 79 if (sbExp.Length > 0) { 80 80 throw new MalformedJSONException ("Positive sign in exponent after digits"); 81 else 82 sbExp.Append (json [offset]); 81 } 82 83 sbExp.Append (json [offset]); 83 84 } else { 84 85 throw new MalformedJSONException ("Positive sign in mantissa found"); … … 86 87 } else { 87 88 double number; 88 if (!StringParsers.TryParseDouble (sbNum.ToString (), out number)) {89 throw new MalformedJSONException ("Mantissa is not a valid decimal (\"" + sbNum .ToString ()+ "\")");89 if (!StringParsers.TryParseDouble (sbNum.ToString (), out number)) { 90 throw new MalformedJSONException ("Mantissa is not a valid decimal (\"" + sbNum + "\")"); 90 91 } 91 92 … … 93 94 int exp; 94 95 if (!int.TryParse (sbExp.ToString (), out exp)) { 95 throw new MalformedJSONException ("Exponent is not a valid integer (\"" + sbExp .ToString ()+ "\")");96 throw new MalformedJSONException ("Exponent is not a valid integer (\"" + sbExp + "\")"); 96 97 } 97 98 … … 102 103 return new JSONNumber (number); 103 104 } 105 104 106 offset++; 105 107 } 108 106 109 throw new MalformedJSONException ("End of JSON reached before parsing number finished"); 107 110 } 108 109 111 } 110 112 } 111 -
binary-improvements/7dtd-server-fixes/src/JSON/JSONObject.cs
r315 r325 1 using System;2 1 using System.Collections.Generic; 3 2 using System.Text; 4 3 5 namespace AllocsFixes.JSON 6 { 7 public class JSONObject : JSONNode 8 { 9 private Dictionary<string, JSONNode> nodes = new Dictionary<string, JSONNode> (); 4 namespace AllocsFixes.JSON { 5 public class JSONObject : JSONNode { 6 private readonly Dictionary<string, JSONNode> nodes = new Dictionary<string, JSONNode> (); 10 7 11 8 public JSONNode this [string name] { … … 22 19 } 23 20 24 public bool ContainsKey (string name) 25 { 21 public bool ContainsKey (string name) { 26 22 return nodes.ContainsKey (name); 27 23 } 28 24 29 public void Add (string name, JSONNode node) 30 { 25 public void Add (string name, JSONNode node) { 31 26 nodes.Add (name, node); 32 27 } 33 28 34 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0) 35 { 29 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0) { 36 30 stringBuilder.Append ("{"); 37 if (prettyPrint) 31 if (prettyPrint) { 38 32 stringBuilder.Append ('\n'); 33 } 34 39 35 foreach (KeyValuePair<string, JSONNode> kvp in nodes) { 40 if (prettyPrint) 41 stringBuilder.Append (new String ('\t', currentLevel + 1)); 42 stringBuilder.Append (String.Format ("\"{0}\":", kvp.Key)); 43 if (prettyPrint) 36 if (prettyPrint) { 37 stringBuilder.Append (new string ('\t', currentLevel + 1)); 38 } 39 40 stringBuilder.Append (string.Format ("\"{0}\":", kvp.Key)); 41 if (prettyPrint) { 44 42 stringBuilder.Append (" "); 43 } 44 45 45 kvp.Value.ToString (stringBuilder, prettyPrint, currentLevel + 1); 46 46 stringBuilder.Append (","); 47 if (prettyPrint) 47 if (prettyPrint) { 48 48 stringBuilder.Append ('\n'); 49 } 49 50 } 50 if (nodes.Count > 0) 51 52 if (nodes.Count > 0) { 51 53 stringBuilder.Remove (stringBuilder.Length - (prettyPrint ? 2 : 1), 1); 52 if (prettyPrint) 53 stringBuilder.Append (new String ('\t', currentLevel)); 54 } 55 56 if (prettyPrint) { 57 stringBuilder.Append (new string ('\t', currentLevel)); 58 } 59 54 60 stringBuilder.Append ("}"); 55 61 } 56 62 57 public static JSONObject Parse (string json, ref int offset) 58 { 63 public static JSONObject Parse (string json, ref int offset) { 59 64 //Log.Out ("ParseObject enter (" + offset + ")"); 60 65 JSONObject obj = new JSONObject (); … … 70 75 Parser.SkipWhitespace (json, ref offset); 71 76 if (json [offset] != ':') { 72 throw new MalformedJSONException ("Could not parse object, missing colon (\":\") after key"); 77 throw new MalformedJSONException ( 78 "Could not parse object, missing colon (\":\") after key"); 73 79 } 80 74 81 offset++; 75 82 JSONNode val = Parser.ParseInternal (json, ref offset); … … 77 84 nextElemAllowed = false; 78 85 } else { 79 throw new MalformedJSONException ("Could not parse object, found new key without a separating comma"); 86 throw new MalformedJSONException ( 87 "Could not parse object, found new key without a separating comma"); 80 88 } 89 81 90 break; 82 91 case ',': … … 84 93 nextElemAllowed = true; 85 94 offset++; 86 } else 87 throw new MalformedJSONException ("Could not parse object, found a comma without a key/value pair first"); 95 } else { 96 throw new MalformedJSONException ( 97 "Could not parse object, found a comma without a key/value pair first"); 98 } 99 88 100 break; 89 101 case '}': 90 102 offset++; 103 91 104 //Log.Out ("JSON:Parsed Object: " + obj.ToString ()); 92 105 return obj; … … 94 107 } 95 108 } 96 97 109 } 98 110 } 99 -
binary-improvements/7dtd-server-fixes/src/JSON/JSONString.cs
r309 r325 1 using System;2 1 using System.Text; 3 2 4 namespace AllocsFixes.JSON 5 { 6 public class JSONString : JSONValue 7 { 8 private string value; 3 namespace AllocsFixes.JSON { 4 public class JSONString : JSONValue { 5 private readonly string value; 9 6 10 public JSONString (string value) 11 { 7 public JSONString (string value) { 12 8 this.value = value; 13 9 } 14 10 15 public string GetString () 16 { 11 public string GetString () { 17 12 return value; 18 13 } 19 14 20 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0) 21 { 15 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0) { 22 16 if (value == null || value.Length == 0) { 23 17 stringBuilder.Append ("\"\""); … … 27 21 int len = value.Length; 28 22 29 stringBuilder.EnsureCapacity (stringBuilder.Length + 2*len); 30 String t; 23 stringBuilder.EnsureCapacity (stringBuilder.Length + 2 * len); 31 24 32 25 stringBuilder.Append ('"'); … … 36 29 case '\\': 37 30 case '"': 31 38 32 // case '/': 39 33 stringBuilder.Append ('\\'); … … 58 52 if (c < ' ') { 59 53 stringBuilder.Append ("\\u"); 60 stringBuilder.Append (((int) c).ToString ("X4"));54 stringBuilder.Append (((int) c).ToString ("X4")); 61 55 } else { 62 56 stringBuilder.Append (c); 63 57 } 58 64 59 break; 65 60 } … … 69 64 } 70 65 71 public static JSONString Parse (string json, ref int offset) 72 { 66 public static JSONString Parse (string json, ref int offset) { 73 67 //Log.Out ("ParseString enter (" + offset + ")"); 74 68 StringBuilder sb = new StringBuilder (); … … 103 97 break; 104 98 } 99 105 100 offset++; 106 101 break; 107 102 case '"': 108 103 offset++; 104 109 105 //Log.Out ("JSON:Parsed String: " + sb.ToString ()); 110 106 return new JSONString (sb.ToString ()); … … 115 111 } 116 112 } 113 117 114 throw new MalformedJSONException ("End of JSON reached before parsing string finished"); 118 115 } 119 120 116 } 121 117 } 122 -
binary-improvements/7dtd-server-fixes/src/JSON/JSONValue.cs
r279 r325 1 using System; 2 3 namespace AllocsFixes.JSON 4 { 1 namespace AllocsFixes.JSON { 5 2 public abstract class JSONValue : JSONNode { 6 3 } 7 4 } 8 -
binary-improvements/7dtd-server-fixes/src/JSON/MalformedJSONException.cs
r188 r325 2 2 using System.Runtime.Serialization; 3 3 4 namespace AllocsFixes.JSON 5 { 6 public class MalformedJSONException : ApplicationException 7 { 8 public MalformedJSONException () 9 { 4 namespace AllocsFixes.JSON { 5 public class MalformedJSONException : ApplicationException { 6 public MalformedJSONException () { 10 7 } 11 8 12 public MalformedJSONException (string message) : base(message) 13 { 9 public MalformedJSONException (string message) : base (message) { 14 10 } 15 11 16 public MalformedJSONException (string message, System.Exception inner) : base(message, inner) 17 { 12 public MalformedJSONException (string message, Exception inner) : base (message, inner) { 18 13 } 19 20 protected MalformedJSONException (SerializationInfo info, StreamingContext context) : base(info, context) 21 { 14 15 protected MalformedJSONException (SerializationInfo info, StreamingContext context) : base (info, context) { 22 16 } 23 17 } 24 18 } 25 -
binary-improvements/7dtd-server-fixes/src/JSON/Parser.cs
r188 r325 1 using System; 2 using System.Text; 3 4 namespace AllocsFixes.JSON 5 { 6 public class Parser 7 { 8 9 public static JSONNode Parse (string json) 10 { 1 namespace AllocsFixes.JSON { 2 public class Parser { 3 public static JSONNode Parse (string json) { 11 4 int offset = 0; 12 5 return ParseInternal (json, ref offset); 13 6 } 14 7 15 public static JSONNode ParseInternal (string json, ref int offset) 16 { 8 public static JSONNode ParseInternal (string json, ref int offset) { 17 9 SkipWhitespace (json, ref offset); 10 18 11 //Log.Out ("ParseInternal (" + offset + "): Decide on: '" + json [offset] + "'"); 19 12 switch (json [offset]) { … … 34 27 } 35 28 36 public static void SkipWhitespace (string json, ref int offset) 37 { 29 public static void SkipWhitespace (string json, ref int offset) { 38 30 //Log.Out ("SkipWhitespace (" + offset + "): '" + json [offset] + "'"); 39 31 while (offset < json.Length) { … … 49 41 } 50 42 } 43 51 44 throw new MalformedJSONException ("End of JSON reached before parsing finished"); 52 45 } 53 54 55 46 } 56 47 } 57 -
binary-improvements/7dtd-server-fixes/src/LandClaimList.cs
r253 r325 1 1 using System; 2 2 using System.Collections.Generic; 3 4 3 using AllocsFixes.PersistentData; 5 4 6 namespace AllocsFixes 7 { 5 namespace AllocsFixes { 8 6 public class LandClaimList { 9 7 public delegate bool OwnerFilter (Player owner); … … 11 9 public delegate bool PositionFilter (Vector3i position); 12 10 13 public static Dictionary<Player, List<Vector3i>> GetLandClaims (OwnerFilter[] _ownerFilters, PositionFilter[] _positionFilters) { 11 public static Dictionary<Player, List<Vector3i>> GetLandClaims (OwnerFilter[] _ownerFilters, 12 PositionFilter[] _positionFilters) { 14 13 Dictionary<Vector3i, PersistentPlayerData> d = GameManager.Instance.GetPersistentPlayerList ().m_lpBlockMap; 15 14 Dictionary<Player, List<Vector3i>> result = new Dictionary<Player, List<Vector3i>> (); 16 15 17 16 if (d != null) { 18 Dictionary<PersistentPlayerData, List<Vector3i>> owners = new Dictionary<PersistentPlayerData, List<Vector3i>> (); 17 Dictionary<PersistentPlayerData, List<Vector3i>> owners = 18 new Dictionary<PersistentPlayerData, List<Vector3i>> (); 19 19 foreach (KeyValuePair<Vector3i, PersistentPlayerData> kvp in d) { 20 20 bool allowed = true; … … 27 27 } 28 28 } 29 29 30 if (allowed) { 30 31 if (!owners.ContainsKey (kvp.Value)) { 31 32 owners.Add (kvp.Value, new List<Vector3i> ()); 32 33 } 34 33 35 owners [kvp.Value].Add (kvp.Key); 34 36 } … … 36 38 37 39 foreach (KeyValuePair<PersistentPlayerData, List<Vector3i>> kvp in owners) { 38 Player p = Persistent Data.PersistentContainer.Instance.Players [kvp.Key.PlayerId, false];40 Player p = PersistentContainer.Instance.Players [kvp.Key.PlayerId, false]; 39 41 if (p == null) { 40 42 p = new Player (kvp.Key.PlayerId); … … 59 61 } 60 62 } 63 61 64 return result; 62 65 } … … 73 76 return p => _f1 (p) || _f2 (p); 74 77 } 75 76 78 } 77 79 } 78 -
binary-improvements/7dtd-server-fixes/src/LiveData/Animals.cs
r312 r325 1 using System; 2 using System.Collections.Generic; 3 4 namespace AllocsFixes.LiveData 5 { 6 public class Animals : EntityFilterList<EntityAnimal> 7 { 8 1 namespace AllocsFixes.LiveData { 2 public class Animals : EntityFilterList<EntityAnimal> { 9 3 public static readonly Animals Instance = new Animals (); 10 4 11 5 protected override EntityAnimal predicate (Entity _e) { 12 6 if (_e is EntityAnimal) { 13 EntityAnimal ea = (EntityAnimal) _e;7 EntityAnimal ea = (EntityAnimal) _e; 14 8 15 9 if (ea.IsAlive ()) { … … 17 11 } 18 12 } 13 19 14 return null; 20 15 } 21 22 } 16 } 23 17 } 24 -
binary-improvements/7dtd-server-fixes/src/LiveData/EntityFilterList.cs
r312 r325 2 2 using System.Collections.Generic; 3 3 4 namespace AllocsFixes.LiveData 5 { 6 public abstract class EntityFilterList<T> where T: Entity 7 { 4 namespace AllocsFixes.LiveData { 5 public abstract class EntityFilterList<T> where T : Entity { 8 6 public void Get (List<T> _list) { 9 7 _list.Clear (); … … 18 16 } 19 17 } 20 } 21 catch (Exception e) { 18 } catch (Exception e) { 22 19 Log.Exception (e); 23 20 } … … 35 32 } 36 33 } 37 } 38 catch (Exception e) { 34 } catch (Exception e) { 39 35 Log.Exception (e); 40 36 } 37 41 38 return count; 42 39 } 43 40 44 41 protected abstract T predicate (Entity _e); 45 46 } 42 } 47 43 } 48 -
binary-improvements/7dtd-server-fixes/src/LiveData/Hostiles.cs
r312 r325 1 using System; 2 using System.Collections.Generic; 3 4 namespace AllocsFixes.LiveData 5 { 6 public class Hostiles : EntityFilterList<EntityEnemy> 7 { 8 1 namespace AllocsFixes.LiveData { 2 public class Hostiles : EntityFilterList<EntityEnemy> { 9 3 public static readonly Hostiles Instance = new Hostiles (); 10 4 11 override protectedEntityEnemy predicate (Entity _e) {5 protected override EntityEnemy predicate (Entity _e) { 12 6 if (_e is EntityEnemy) { 13 7 if (_e.IsAlive ()) { … … 15 9 } 16 10 } 11 17 12 return null; 18 13 } 19 20 14 } 21 15 } 22 -
binary-improvements/7dtd-server-fixes/src/PersistentData/Attributes.cs
r273 r325 1 1 using System; 2 using System.Collections.Generic;3 using System.Runtime.Serialization;4 using System.Text.RegularExpressions;5 2 6 namespace AllocsFixes.PersistentData 7 { 3 namespace AllocsFixes.PersistentData { 8 4 [Serializable] 9 public class Attributes 10 { 5 public class Attributes { 11 6 private bool hideChatCommands; 12 7 private String hideChatCommandPrefix; 13 8 14 9 public bool HideChatCommands { 15 get { 16 return hideChatCommands; 17 } 18 set { 19 hideChatCommands = value; 20 } 10 get { return hideChatCommands; } 11 set { hideChatCommands = value; } 21 12 } 22 13 … … 26 17 hideChatCommandPrefix = ""; 27 18 } 19 28 20 return hideChatCommandPrefix; 29 21 } 30 set { 31 hideChatCommandPrefix = value; 32 } 22 set { hideChatCommandPrefix = value; } 33 23 } 34 35 24 } 36 25 } 37 -
binary-improvements/7dtd-server-fixes/src/PersistentData/InvItem.cs
r287 r325 2 2 using System.Runtime.Serialization; 3 3 4 namespace AllocsFixes.PersistentData 5 { 4 namespace AllocsFixes.PersistentData { 6 5 [Serializable] 7 6 public class InvItem { … … 26 25 } 27 26 } 28 -
binary-improvements/7dtd-server-fixes/src/PersistentData/Inventory.cs
r324 r325 3 3 4 4 namespace AllocsFixes.PersistentData { 5 6 7 8 9 5 [Serializable] 6 public class Inventory { 7 public List<InvItem> bag; 8 public List<InvItem> belt; 9 public InvItem[] equipment; 10 10 11 12 13 14 15 11 public Inventory () { 12 bag = new List<InvItem> (); 13 belt = new List<InvItem> (); 14 equipment = null; 15 } 16 16 17 18 19 20 21 22 23 24 17 public void Update (PlayerDataFile pdf) { 18 lock (this) { 19 //Log.Out ("Updating player inventory - player id: " + pdf.id); 20 ProcessInv (bag, pdf.bag, pdf.id); 21 ProcessInv (belt, pdf.inventory, pdf.id); 22 ProcessEqu (pdf.equipment, pdf.id); 23 } 24 } 25 25 26 27 28 29 30 31 32 26 private void ProcessInv (List<InvItem> target, ItemStack[] sourceFields, int id) { 27 target.Clear (); 28 for (int i = 0; i < sourceFields.Length; i++) { 29 InvItem item = CreateInvItem (sourceFields [i].itemValue, sourceFields [i].count, id); 30 if (item != null && sourceFields [i].itemValue.Modifications != null) { 31 ProcessParts (sourceFields [i].itemValue.Modifications, item, id); 32 } 33 33 34 35 36 34 target.Add (item); 35 } 36 } 37 37 38 39 40 41 42 43 38 private void ProcessEqu (Equipment sourceEquipment, int _playerId) { 39 equipment = new InvItem[sourceEquipment.GetSlotCount ()]; 40 for (int i = 0; i < sourceEquipment.GetSlotCount (); i++) { 41 equipment [i] = CreateInvItem (sourceEquipment.GetSlotItem (i), 1, _playerId); 42 } 43 } 44 44 45 46 47 48 49 50 51 45 private void ProcessParts (ItemValue[] _parts, InvItem _item, int _playerId) { 46 InvItem[] itemParts = new InvItem[_parts.Length]; 47 for (int i = 0; i < _parts.Length; i++) { 48 InvItem partItem = CreateInvItem (_parts [i], 1, _playerId); 49 if (partItem != null && _parts [i].Modifications != null) { 50 ProcessParts (_parts [i].Modifications, partItem, _playerId); 51 } 52 52 53 54 53 itemParts [i] = partItem; 54 } 55 55 56 57 56 _item.parts = itemParts; 57 } 58 58 59 60 61 62 63 59 private InvItem CreateInvItem (ItemValue _itemValue, int _count, int _playerId) { 60 if (_count > 0 && _itemValue != null && !_itemValue.Equals (ItemValue.None)) { 61 ItemClass itemClass = ItemClass.list [_itemValue.type]; 62 int maxAllowed = itemClass.Stacknumber.Value; 63 string name = itemClass.GetItemName (); 64 64 65 66 67 68 65 if (_count > maxAllowed) { 66 Log.Out ("Player with ID " + _playerId + " has stack for \"" + name + "\" greater than allowed (" + 67 _count + " > " + maxAllowed + ")"); 68 } 69 69 70 71 72 73 74 75 70 InvItem item = null; 71 if (_itemValue.HasQuality) { 72 item = new InvItem (name, _count, _itemValue.Quality, _itemValue.MaxUseTimes, _itemValue.UseTimes); 73 } else { 74 item = new InvItem (name, _count, -1, _itemValue.MaxUseTimes, _itemValue.UseTimes); 75 } 76 76 77 77 item.icon = itemClass.GetIconName (); 78 78 79 79 item.iconcolor = AllocsUtils.ColorToHex (itemClass.GetIconTint ()); 80 80 81 82 } else { 83 return null; 84 } 85 86 81 return item; 82 } 83 84 return null; 85 } 86 } 87 87 } -
binary-improvements/7dtd-server-fixes/src/PersistentData/PersistentContainer.cs
r273 r325 4 4 using System.Runtime.Serialization.Formatters.Binary; 5 5 6 namespace AllocsFixes.PersistentData 7 { 6 namespace AllocsFixes.PersistentData { 8 7 [Serializable] 9 public class PersistentContainer 10 { 8 public class PersistentContainer { 11 9 private Players players; 12 [OptionalField] 13 private Attributes attributes; 10 [OptionalField] private Attributes attributes; 14 11 15 12 public Players Players { 16 13 get { 17 if (players == null) 14 if (players == null) { 18 15 players = new Players (); 16 } 17 19 18 return players; 20 19 } 21 20 } 22 21 23 public Attributes Attributes 24 { 22 public Attributes Attributes { 25 23 get { 26 24 if (attributes == null) { 27 attributes = new Attributes ();25 attributes = new Attributes (); 28 26 } 27 29 28 return attributes; 30 29 } … … 38 37 instance = new PersistentContainer (); 39 38 } 39 40 40 return instance; 41 41 } 42 42 } 43 43 44 private PersistentContainer () 45 { 44 private PersistentContainer () { 46 45 } 47 46 48 public void Save () 49 { 47 public void Save () { 50 48 Stream stream = File.Open (GameUtils.GetSaveGameDir () + "/AllocsPeristentData.bin", FileMode.Create); 51 49 BinaryFormatter bFormatter = new BinaryFormatter (); … … 54 52 } 55 53 56 public static bool Load () 57 { 54 public static bool Load () { 58 55 if (File.Exists (GameUtils.GetSaveGameDir () + "/AllocsPeristentData.bin")) { 59 56 try { … … 61 58 Stream stream = File.Open (GameUtils.GetSaveGameDir () + "/AllocsPeristentData.bin", FileMode.Open); 62 59 BinaryFormatter bFormatter = new BinaryFormatter (); 63 obj = (PersistentContainer) bFormatter.Deserialize (stream);60 obj = (PersistentContainer) bFormatter.Deserialize (stream); 64 61 stream.Close (); 65 62 instance = obj; … … 70 67 } 71 68 } 69 72 70 return false; 73 71 } 74 75 72 } 76 73 } 77 -
binary-improvements/7dtd-server-fixes/src/PersistentData/Player.cs
r324 r325 4 4 5 5 namespace AllocsFixes.PersistentData { 6 [Serializable] 7 public class Player { 8 private readonly string steamId; 9 private int entityId; 10 private string name; 11 private string ip; 12 private long totalPlayTime; 13 14 [OptionalField] private DateTime 15 lastOnline; 16 17 private Inventory inventory; 18 19 [OptionalField] private int 20 lastPositionX, lastPositionY, lastPositionZ; 21 22 [OptionalField] [Obsolete ("experience no longer available, use level and expToNextLevel instead")] 23 private uint experience; 24 25 [OptionalField] private bool chatMuted; 26 [OptionalField] private int maxChatLength; 27 [OptionalField] private string chatColor; 28 [OptionalField] private bool chatName; 29 [OptionalField] private uint expToNextLevel; 30 [OptionalField] private int level; 31 32 [NonSerialized] private ClientInfo 33 clientInfo; 34 35 public string SteamID { 36 get { return steamId; } 37 } 6 [Serializable] 7 public class Player { 8 private readonly string steamId; 9 private int entityId; 10 private string name; 11 private string ip; 12 private long totalPlayTime; 13 14 [OptionalField] private DateTime lastOnline; 15 16 private Inventory inventory; 17 18 [OptionalField] private int lastPositionX, lastPositionY, lastPositionZ; 19 20 [OptionalField] [Obsolete ("experience no longer available, use level and expToNextLevel instead")] 21 private uint experience; 22 23 [OptionalField] private bool chatMuted; 24 [OptionalField] private int maxChatLength; 25 [OptionalField] private string chatColor; 26 [OptionalField] private bool chatName; 27 [OptionalField] private uint expToNextLevel; 28 [OptionalField] private int level; 29 30 [NonSerialized] private ClientInfo clientInfo; 31 32 public string SteamID { 33 get { return steamId; } 34 } 38 35 39 36 public int EntityID { … … 41 38 } 42 39 43 public string Name { 44 get { return name == null ? string.Empty : name; } 45 } 46 47 public string IP { 48 get { return ip == null ? string.Empty : ip; } 49 } 50 51 public Inventory Inventory { 52 get { 53 if (inventory == null) 54 inventory = new Inventory (); 55 return inventory; 56 } 57 } 58 59 public bool IsOnline { 60 get { return clientInfo != null; } 61 } 62 63 public ClientInfo ClientInfo { 64 get { return clientInfo; } 65 } 66 67 public EntityPlayer Entity { 68 get { 69 if (IsOnline) { 70 return GameManager.Instance.World.Players.dict [clientInfo.entityId]; 71 } else { 72 return null; 73 } 74 } 75 } 76 77 public long TotalPlayTime { 78 get { 79 if (IsOnline) { 80 return totalPlayTime + (long) (DateTime.Now - lastOnline).TotalSeconds; 81 } else { 82 return totalPlayTime; 83 } 84 } 85 } 86 87 public DateTime LastOnline { 88 get { 89 if (IsOnline) 90 return DateTime.Now; 91 else 92 return lastOnline; 93 } 94 } 95 96 public Vector3i LastPosition { 97 get { 98 if (IsOnline) 99 return new Vector3i (Entity.GetPosition ()); 100 else 101 return new Vector3i (lastPositionX, lastPositionY, lastPositionZ); 102 } 103 } 104 105 public bool LandProtectionActive { 106 get { 107 return GameManager.Instance.World.IsLandProtectionValidForPlayer (GameManager.Instance 108 .GetPersistentPlayerList ().GetPlayerData (SteamID)); 109 } 110 } 111 112 public float LandProtectionMultiplier { 113 get { 114 return GameManager.Instance.World.GetLandProtectionHardnessModifierForPlayer (GameManager.Instance 115 .GetPersistentPlayerList ().GetPlayerData (SteamID)); 116 } 117 } 118 119 120 [Obsolete ("Experience no longer available, use Level instead")] 121 public uint Experience { 122 get { return 0; } 123 } 124 125 public float Level { 126 get { 127 float expForNextLevel = 128 (int) Math.Min ((Progression.BaseExpToLevel * Mathf.Pow (Progression.ExpMultiplier, level + 1)), 129 int.MaxValue); 130 float fLevel = level + 1f - ((float) expToNextLevel / expForNextLevel); 131 return fLevel; 132 } 133 } 134 135 public bool IsChatMuted { 136 get { return chatMuted; } 137 set { chatMuted = value; } 138 } 139 140 public int MaxChatLength { 141 get { 142 if (maxChatLength == 0) { 143 maxChatLength = 255; 144 } 145 146 return maxChatLength; 147 } 148 set { maxChatLength = value; } 149 } 150 151 public string ChatColor { 152 get { 153 if (chatColor == null || chatColor == "") { 154 chatColor = ""; 155 } 156 157 return chatColor; 158 } 159 160 set { chatColor = value; } 161 } 162 163 public bool ChatName { 164 get { return chatName; } 165 166 set { chatName = value; } 167 } 168 169 public void SetOffline () { 170 if (clientInfo != null) { 171 Log.Out ("Player set to offline: " + steamId); 172 lastOnline = DateTime.Now; 173 try { 174 Vector3i lastPos = new Vector3i (Entity.GetPosition ()); 175 lastPositionX = lastPos.x; 176 lastPositionY = lastPos.y; 177 lastPositionZ = lastPos.z; 178 totalPlayTime += (long) (Time.timeSinceLevelLoad - Entity.CreationTimeSinceLevelLoad); 179 } catch (NullReferenceException) { 180 Log.Out ("Entity not available. Something seems to be wrong here..."); 181 } 182 183 clientInfo = null; 184 } 185 } 186 187 public void SetOnline (ClientInfo ci) { 188 Log.Out ("Player set to online: " + steamId); 189 clientInfo = ci; 40 public string Name { 41 get { return name == null ? string.Empty : name; } 42 } 43 44 public string IP { 45 get { return ip == null ? string.Empty : ip; } 46 } 47 48 public Inventory Inventory { 49 get { 50 if (inventory == null) { 51 inventory = new Inventory (); 52 } 53 54 return inventory; 55 } 56 } 57 58 public bool IsOnline { 59 get { return clientInfo != null; } 60 } 61 62 public ClientInfo ClientInfo { 63 get { return clientInfo; } 64 } 65 66 public EntityPlayer Entity { 67 get { 68 if (IsOnline) { 69 return GameManager.Instance.World.Players.dict [clientInfo.entityId]; 70 } 71 72 return null; 73 } 74 } 75 76 public long TotalPlayTime { 77 get { 78 if (IsOnline) { 79 return totalPlayTime + (long) (DateTime.Now - lastOnline).TotalSeconds; 80 } 81 82 return totalPlayTime; 83 } 84 } 85 86 public DateTime LastOnline { 87 get { 88 if (IsOnline) { 89 return DateTime.Now; 90 } 91 92 return lastOnline; 93 } 94 } 95 96 public Vector3i LastPosition { 97 get { 98 if (IsOnline) { 99 return new Vector3i (Entity.GetPosition ()); 100 } 101 102 return new Vector3i (lastPositionX, lastPositionY, lastPositionZ); 103 } 104 } 105 106 public bool LandProtectionActive { 107 get { 108 return GameManager.Instance.World.IsLandProtectionValidForPlayer (GameManager.Instance 109 .GetPersistentPlayerList ().GetPlayerData (SteamID)); 110 } 111 } 112 113 public float LandProtectionMultiplier { 114 get { 115 return GameManager.Instance.World.GetLandProtectionHardnessModifierForPlayer (GameManager.Instance 116 .GetPersistentPlayerList ().GetPlayerData (SteamID)); 117 } 118 } 119 120 121 [Obsolete ("Experience no longer available, use Level instead")] 122 public uint Experience { 123 get { return 0; } 124 } 125 126 public float Level { 127 get { 128 float expForNextLevel = 129 (int) Math.Min (Progression.BaseExpToLevel * Mathf.Pow (Progression.ExpMultiplier, level + 1), 130 int.MaxValue); 131 float fLevel = level + 1f - expToNextLevel / expForNextLevel; 132 return fLevel; 133 } 134 } 135 136 public bool IsChatMuted { 137 get { return chatMuted; } 138 set { chatMuted = value; } 139 } 140 141 public int MaxChatLength { 142 get { 143 if (maxChatLength == 0) { 144 maxChatLength = 255; 145 } 146 147 return maxChatLength; 148 } 149 set { maxChatLength = value; } 150 } 151 152 public string ChatColor { 153 get { 154 if (chatColor == null || chatColor == "") { 155 chatColor = ""; 156 } 157 158 return chatColor; 159 } 160 161 set { chatColor = value; } 162 } 163 164 public bool ChatName { 165 get { return chatName; } 166 167 set { chatName = value; } 168 } 169 170 public Player (string steamId) { 171 this.steamId = steamId; 172 inventory = new Inventory (); 173 } 174 175 public void SetOffline () { 176 if (clientInfo != null) { 177 Log.Out ("Player set to offline: " + steamId); 178 lastOnline = DateTime.Now; 179 try { 180 Vector3i lastPos = new Vector3i (Entity.GetPosition ()); 181 lastPositionX = lastPos.x; 182 lastPositionY = lastPos.y; 183 lastPositionZ = lastPos.z; 184 totalPlayTime += (long) (Time.timeSinceLevelLoad - Entity.CreationTimeSinceLevelLoad); 185 } catch (NullReferenceException) { 186 Log.Out ("Entity not available. Something seems to be wrong here..."); 187 } 188 189 clientInfo = null; 190 } 191 } 192 193 public void SetOnline (ClientInfo ci) { 194 Log.Out ("Player set to online: " + steamId); 195 clientInfo = ci; 190 196 entityId = ci.entityId; 191 name = ci.playerName; 192 ip = ci.ip; 193 lastOnline = DateTime.Now; 194 } 195 196 public void Update (PlayerDataFile _pdf) { 197 UpdateProgression (_pdf); 198 inventory.Update (_pdf); 199 } 200 201 private void UpdateProgression (PlayerDataFile _pdf) { 202 if (_pdf.progressionData.Length > 0) { 203 using (PooledBinaryReader pbr = MemoryPools.poolBinaryReader.AllocSync (false)) { 204 pbr.SetBaseStream (_pdf.progressionData); 205 Progression p = Progression.Read (pbr, null); 206 expToNextLevel = (uint) p.ExpToNextLevel; 207 level = p.Level; 208 } 209 } 210 } 211 212 public Player (string steamId) { 213 this.steamId = steamId; 214 this.inventory = new Inventory (); 215 } 216 } 197 name = ci.playerName; 198 ip = ci.ip; 199 lastOnline = DateTime.Now; 200 } 201 202 public void Update (PlayerDataFile _pdf) { 203 UpdateProgression (_pdf); 204 inventory.Update (_pdf); 205 } 206 207 private void UpdateProgression (PlayerDataFile _pdf) { 208 if (_pdf.progressionData.Length > 0) { 209 using (PooledBinaryReader pbr = MemoryPools.poolBinaryReader.AllocSync (false)) { 210 pbr.SetBaseStream (_pdf.progressionData); 211 Progression p = Progression.Read (pbr, null); 212 expToNextLevel = (uint) p.ExpToNextLevel; 213 level = p.Level; 214 } 215 } 216 } 217 } 217 218 } -
binary-improvements/7dtd-server-fixes/src/PersistentData/Players.cs
r276 r325 1 1 using System; 2 2 using System.Collections.Generic; 3 using System.Runtime.Serialization;4 3 using System.Text.RegularExpressions; 5 4 6 namespace AllocsFixes.PersistentData 7 { 5 namespace AllocsFixes.PersistentData { 8 6 [Serializable] 9 7 public class Players { 10 private Dictionary<string, Player> players = new Dictionary<string, Player> ();8 private readonly Dictionary<string, Player> players = new Dictionary<string, Player> (); 11 9 12 10 public Player this [string steamId, bool create] { … … 14 12 if (string.IsNullOrEmpty (steamId)) { 15 13 return null; 16 } else if (players.ContainsKey (steamId)) { 14 } 15 16 if (players.ContainsKey (steamId)) { 17 17 return players [steamId]; 18 } else {19 if (create && steamId != null && steamId.Length == 17) {20 Log.Out ("Created new player entry for ID: " + steamId);21 Player p = new Player (steamId);22 players.Add (steamId, p);23 return p;24 }25 return null;26 18 } 19 20 if (create && steamId != null && steamId.Length == 17) { 21 Log.Out ("Created new player entry for ID: " + steamId); 22 Player p = new Player (steamId); 23 players.Add (steamId, p); 24 return p; 25 } 26 27 return null; 27 28 } 28 29 } … … 53 54 if (_nameOrId.Length == 17 && long.TryParse (_nameOrId, out tempLong)) { 54 55 return _nameOrId; 55 } else { 56 int entityId = -1; 57 if (int.TryParse (_nameOrId, out entityId)) { 58 foreach (KeyValuePair<string, Player> kvp in players) { 59 if (kvp.Value.IsOnline && kvp.Value.EntityID == entityId) { 60 return kvp.Key; 61 } 62 } 63 } 56 } 64 57 65 _nameOrId = _nameOrId.ToLower (); 58 int entityId = -1; 59 if (int.TryParse (_nameOrId, out entityId)) { 66 60 foreach (KeyValuePair<string, Player> kvp in players) { 67 string name = kvp.Value.Name.ToLower (); 68 if (_ignoreColorCodes) { 69 name = Regex.Replace (name, "\\[[0-9a-fA-F]{6}\\]", ""); 70 } 71 if (kvp.Value.IsOnline && name.Equals (_nameOrId)) { 61 if (kvp.Value.IsOnline && kvp.Value.EntityID == entityId) { 72 62 return kvp.Key; 73 63 } 74 64 } 75 65 } 66 67 _nameOrId = _nameOrId.ToLower (); 68 foreach (KeyValuePair<string, Player> kvp in players) { 69 string name = kvp.Value.Name.ToLower (); 70 if (_ignoreColorCodes) { 71 name = Regex.Replace (name, "\\[[0-9a-fA-F]{6}\\]", ""); 72 } 73 74 if (kvp.Value.IsOnline && name.Equals (_nameOrId)) { 75 return kvp.Key; 76 } 77 } 78 76 79 return null; 77 80 } 78 81 } 79 82 } 80 -
binary-improvements/7dtd-server-fixes/src/PlayerDataStuff.cs
r233 r325 1 using System; 1 2 using AllocsFixes.PersistentData; 2 using System;3 using System.Collections.Generic;4 3 5 namespace AllocsFixes 6 { 7 public class PlayerDataStuff 8 { 9 10 public static void GM_SavePlayerData (ClientInfo _cInfo, PlayerDataFile _playerDataFile) 11 { 4 namespace AllocsFixes { 5 public class PlayerDataStuff { 6 public static void GM_SavePlayerData (ClientInfo _cInfo, PlayerDataFile _playerDataFile) { 12 7 try { 13 PersistentContainer.Instance.Players [_cInfo.playerId, true].Update (_playerDataFile);8 PersistentContainer.Instance.Players [_cInfo.playerId, true].Update (_playerDataFile); 14 9 } catch (Exception e) { 15 10 Log.Out ("Error in GM_SavePlayerData: " + e); 16 11 } 17 12 } 18 19 20 13 } 21 14 } -
binary-improvements/7dtd-server-fixes/src/StateManager.cs
r306 r325 1 1 using System; 2 using System.Reflection;2 using AllocsFixes.PersistentData; 3 3 4 namespace AllocsFixes 5 { 6 public class StateManager 7 { 8 public static void Awake () 9 { 4 namespace AllocsFixes { 5 public class StateManager { 6 public static void Awake () { 10 7 try { 11 Persistent Data.PersistentContainer.Load ();8 PersistentContainer.Load (); 12 9 } catch (Exception e) { 13 10 Log.Out ("Error in StateManager.Awake: " + e); … … 15 12 } 16 13 17 public static void Shutdown () 18 { 14 public static void Shutdown () { 19 15 try { 20 16 Log.Out ("Server shutting down!"); 21 Persistent Data.PersistentContainer.Instance.Save ();17 PersistentContainer.Instance.Save (); 22 18 } catch (Exception e) { 23 19 Log.Out ("Error in StateManager.Shutdown: " + e); … … 26 22 } 27 23 } 28 -
binary-improvements/AllocsCommands/AssemblyInfo.cs
r232 r325 1 1 using System.Reflection; 2 using System.Runtime.CompilerServices;3 2 4 3 // Information about this assembly is defined by the following attributes. 5 4 // Change them to the values specific to your project. 6 5 7 [assembly: AssemblyTitle ("AllocsCommands")]8 [assembly: AssemblyDescription ("")]9 [assembly: AssemblyConfiguration ("")]10 [assembly: AssemblyCompany ("")]11 [assembly: AssemblyProduct ("")]12 [assembly: AssemblyCopyright ("ci")]13 [assembly: AssemblyTrademark ("")]14 [assembly: AssemblyCulture ("")]6 [assembly: AssemblyTitle ("AllocsCommands")] 7 [assembly: AssemblyDescription ("")] 8 [assembly: AssemblyConfiguration ("")] 9 [assembly: AssemblyCompany ("")] 10 [assembly: AssemblyProduct ("")] 11 [assembly: AssemblyCopyright ("ci")] 12 [assembly: AssemblyTrademark ("")] 13 [assembly: AssemblyCulture ("")] 15 14 16 15 // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". … … 18 17 // and "{Major}.{Minor}.{Build}.*" will update just the revision. 19 18 20 [assembly: AssemblyVersion ("0.0.0.0")]19 [assembly: AssemblyVersion ("0.0.0.0")] 21 20 22 21 // The following attributes are used to specify the signing key for the assembly, … … 25 24 //[assembly: AssemblyDelaySign(false)] 26 25 //[assembly: AssemblyKeyFile("")] 27 -
binary-improvements/AllocsCommands/Chat.cs
r267 r325 1 using System; 2 3 namespace AllocsFixes.CustomCommands 4 { 1 namespace AllocsFixes.CustomCommands { 5 2 public class Chat { 6 7 3 public static void SendMessage (ClientInfo _receiver, ClientInfo _sender, string _message) { 8 4 string senderName; … … 13 9 senderName = "Server"; 14 10 } 15 _receiver.SendPackage (new NetPackageGameMessage (EnumGameMessages.Chat, _message, senderName + " (PM)", false, "", false)); 11 12 _receiver.SendPackage (new NetPackageGameMessage (EnumGameMessages.Chat, _message, senderName + " (PM)", 13 false, "", false)); 16 14 string receiverName = _receiver.playerName; 17 SdtdConsole.Instance.Output ("Message to player " + (receiverName != null ? "\"" + receiverName + "\"" : "unknownName") + " sent with sender \"" + senderName + "\""); 15 SdtdConsole.Instance.Output ("Message to player " + 16 (receiverName != null ? "\"" + receiverName + "\"" : "unknownName") + 17 " sent with sender \"" + senderName + "\""); 18 18 } 19 20 21 19 } 22 20 } 23 -
binary-improvements/AllocsCommands/Commands/Give.cs
r324 r325 3 3 using UnityEngine; 4 4 5 namespace AllocsFixes.CustomCommands 6 { 5 namespace AllocsFixes.CustomCommands { 7 6 public class Give : ConsoleCmdAbstract { 8 7 public override string GetDescription () { … … 12 11 public override string GetHelp () { 13 12 return "Give an item to a player by dropping it in front of that player\n" + 14 15 16 17 18 19 20 13 "Usage:\n" + 14 " give <name / entity id> <item name> <amount>\n" + 15 " give <name / entity id> <item name> <amount> <quality>\n" + 16 "Either pass the full name of a player or his entity id (given by e.g. \"lpi\").\n" + 17 "Item name has to be the exact name of an item as listed by \"listitems\".\n" + 18 "Amount is the number of instances of this item to drop (as a single stack).\n" + 19 "Quality is the quality of the dropped items for items that have a quality."; 21 20 } 22 21 23 22 public override string[] GetCommands () { 24 return new string[] { "give", string.Empty};23 return new[] {"give", string.Empty}; 25 24 } 26 25 … … 28 27 try { 29 28 if (_params.Count != 3 && _params.Count != 4) { 30 SdtdConsole.Instance.Output ("Wrong number of arguments, expected 3 or 4, found " + _params.Count + "."); 29 SdtdConsole.Instance.Output ("Wrong number of arguments, expected 3 or 4, found " + _params.Count + 30 "."); 31 31 return; 32 32 } … … 56 56 57 57 if (_params.Count == 4) { 58 if (!int.TryParse(_params [1], out quality) || quality <= 0) {58 if (!int.TryParse (_params [1], out quality) || quality <= 0) { 59 59 SdtdConsole.Instance.Output ("Quality is not an integer or not greater than zero."); 60 60 return; … … 64 64 if (ItemClass.list [iv.type].HasSubItems) { 65 65 for (int i = 0; i < iv.Modifications.Length; i++) { 66 ItemValue tmp = iv.Modifications [i];66 ItemValue tmp = iv.Modifications [i]; 67 67 tmp.Quality = quality; 68 iv.Modifications [i] = tmp;68 iv.Modifications [i] = tmp; 69 69 } 70 70 } else if (ItemClass.list [iv.type].HasQuality) { -
binary-improvements/AllocsCommands/Commands/ListItems.cs
r306 r325 2 2 using System.Collections.Generic; 3 3 4 namespace AllocsFixes.CustomCommands 5 { 6 public class ListItems : ConsoleCmdAbstract 7 { 8 public override string GetDescription () 9 { 4 namespace AllocsFixes.CustomCommands { 5 public class ListItems : ConsoleCmdAbstract { 6 public override string GetDescription () { 10 7 return "lists all items that contain the given substring"; 11 8 } 12 9 13 public override string[] GetCommands () 14 { 15 return new string[] { "listitems", "li" }; 10 public override string[] GetCommands () { 11 return new[] {"listitems", "li"}; 16 12 } 17 13 18 14 public override string GetHelp () { 19 15 return "List all available item names\n" + 20 21 22 23 24 16 "Usage:\n" + 17 " 1. listitems <searchString>\n" + 18 " 2. listitems *\n" + 19 "1. List only names that contain the given string.\n" + 20 "2. List all names."; 25 21 } 26 22 27 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) 28 { 23 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) { 29 24 try { 30 25 if (_params.Count != 1 || _params [0].Length == 0) { … … 34 29 35 30 int count = ItemClass.ItemNames.Count; 36 bool showAll = _params [0].Trim().Equals("*");31 bool showAll = _params [0].Trim ().Equals ("*"); 37 32 38 33 int listed = 0; -
binary-improvements/AllocsCommands/Commands/ListKnownPlayers.cs
r284 r325 1 using AllocsFixes.PersistentData;2 1 using System; 3 2 using System.Collections.Generic; 3 using AllocsFixes.PersistentData; 4 4 5 namespace AllocsFixes.CustomCommands 6 { 7 public class ListKnownPlayers : ConsoleCmdAbstract 8 { 9 public override string GetDescription () 10 { 5 namespace AllocsFixes.CustomCommands { 6 public class ListKnownPlayers : ConsoleCmdAbstract { 7 public override string GetDescription () { 11 8 return "lists all players that were ever online"; 12 9 } … … 14 11 public override string GetHelp () { 15 12 return "Usage:\n" + 16 17 18 19 20 21 22 23 13 " 1. listknownplayers\n" + 14 " 2. listknownplayers -online\n" + 15 " 3. listknownplayers -notbanned\n" + 16 " 4. listknownplayers <player name / steamid>\n" + 17 "1. Lists all players that have ever been online\n" + 18 "2. Lists only the players that are currently online\n" + 19 "3. Lists only the players that are not banned\n" + 20 "4. Lists all players whose name contains the given string or matches the given SteamID"; 24 21 } 25 22 26 public override string[] GetCommands () 27 { 28 return new string[] { "listknownplayers", "lkp" }; 23 public override string[] GetCommands () { 24 return new[] {"listknownplayers", "lkp"}; 29 25 } 30 26 31 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) 32 { 27 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) { 33 28 try { 34 29 AdminTools admTools = GameManager.Instance.adminTools; … … 56 51 57 52 if (p != null) { 58 SdtdConsole.Instance.Output (String.Format ("{0}. {1}, id={2}, steamid={3}, online={4}, ip={5}, playtime={6} m, seen={7}", 53 SdtdConsole.Instance.Output (string.Format ( 54 "{0}. {1}, id={2}, steamid={3}, online={4}, ip={5}, playtime={6} m, seen={7}", 59 55 0, p.Name, p.EntityID, nameFilter, p.IsOnline, p.IP, 60 56 p.TotalPlayTime / 60, … … 62 58 ); 63 59 } else { 64 SdtdConsole.Instance.Output ( String.Format ("SteamID {0} unknown!", nameFilter));60 SdtdConsole.Instance.Output (string.Format ("SteamID {0} unknown!", nameFilter)); 65 61 } 66 62 } else { … … 74 70 && (nameFilter.Length == 0 || p.Name.ToLower ().Contains (nameFilter)) 75 71 ) { 76 SdtdConsole.Instance.Output (String.Format ("{0}. {1}, id={2}, steamid={3}, online={4}, ip={5}, playtime={6} m, seen={7}", 77 ++num, p.Name, p.EntityID, sid, p.IsOnline, p.IP, 78 p.TotalPlayTime / 60, 79 p.LastOnline.ToString ("yyyy-MM-dd HH:mm")) 72 SdtdConsole.Instance.Output (string.Format ( 73 "{0}. {1}, id={2}, steamid={3}, online={4}, ip={5}, playtime={6} m, seen={7}", 74 ++num, p.Name, p.EntityID, sid, p.IsOnline, p.IP, 75 p.TotalPlayTime / 60, 76 p.LastOnline.ToString ("yyyy-MM-dd HH:mm")) 80 77 ); 81 78 } 82 79 } 80 83 81 SdtdConsole.Instance.Output ("Total of " + PersistentContainer.Instance.Players.Count + " known"); 84 82 } -
binary-improvements/AllocsCommands/Commands/ListLandProtection.cs
r273 r325 1 1 using System; 2 2 using System.Collections.Generic; 3 using AllocsFixes.PersistentData; 3 4 4 namespace AllocsFixes.CustomCommands 5 { 6 public class ListLandProtection : ConsoleCmdAbstract 7 { 8 public override string GetDescription () 9 { 5 namespace AllocsFixes.CustomCommands { 6 public class ListLandProtection : ConsoleCmdAbstract { 7 public override string GetDescription () { 10 8 return "lists all land protection blocks and owners"; 11 9 } … … 13 11 public override string GetHelp () { 14 12 return "Usage:\n" + 15 " 1. listlandprotection summary\n" +16 " 2. listlandprotection <steam id / player name / entity id> [parseable]\n" +17 " 3. listlandprotection nearby [length]\n" +18 "1. Lists only players that own claimstones, the number they own and the protection status\n" +19 "2. Lists only the claims of the player given by his SteamID / entity id / playername, including the individual claim positions.\n" +20 " If \"parseable\" is specified the output of the individual claims will be in a format better suited for programmatical readout.\n" +21 "3. Lists claims in a square with edge length of 64 (or the optionally specified size) around the executing player\n";13 " 1. listlandprotection summary\n" + 14 " 2. listlandprotection <steam id / player name / entity id> [parseable]\n" + 15 " 3. listlandprotection nearby [length]\n" + 16 "1. Lists only players that own claimstones, the number they own and the protection status\n" + 17 "2. Lists only the claims of the player given by his SteamID / entity id / playername, including the individual claim positions.\n" + 18 " If \"parseable\" is specified the output of the individual claims will be in a format better suited for programmatical readout.\n" + 19 "3. Lists claims in a square with edge length of 64 (or the optionally specified size) around the executing player\n"; 22 20 } 23 21 24 public override string[] GetCommands () 25 { 26 return new string[] { "listlandprotection", "llp" }; 22 public override string[] GetCommands () { 23 return new[] {"listlandprotection", "llp"}; 27 24 } 28 25 29 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) 30 { 26 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) { 31 27 try { 32 28 if (_senderInfo.RemoteClientInfo != null) { … … 41 37 bool summaryOnly = false; 42 38 string steamIdFilter = string.Empty; 43 Vector3i closeTo = default (Vector3i);39 Vector3i closeTo = default (Vector3i); 44 40 bool onlyCloseToPlayer = false; 45 41 int closeToDistance = 32; … … 71 67 try { 72 68 if (_params.Count == 3) { 73 if (!int.TryParse (_params [1], out closeToDistance)) {69 if (!int.TryParse (_params [1], out closeToDistance)) { 74 70 SdtdConsole.Instance.Output ("Given length is not an integer!"); 75 71 return; 76 72 } 73 77 74 closeToDistance /= 2; 78 75 } 76 79 77 ClientInfo ci = ConsoleHelper.ParseParamSteamIdOnline (_params [_params.Count - 1]); 80 78 EntityPlayer ep = w.Players.dict [ci.entityId]; … … 95 93 LandClaimList.OwnerFilter[] ownerFilters = null; 96 94 if (!string.IsNullOrEmpty (steamIdFilter)) { 97 ownerFilters = new LandClaimList.OwnerFilter[] { LandClaimList.SteamIdFilter (steamIdFilter)};95 ownerFilters = new[] {LandClaimList.SteamIdFilter (steamIdFilter)}; 98 96 } 97 99 98 LandClaimList.PositionFilter[] posFilters = null; 100 99 if (onlyCloseToPlayer) { 101 posFilters = new LandClaimList.PositionFilter[] { LandClaimList.CloseToFilter2dRect (closeTo, closeToDistance)};100 posFilters = new[] {LandClaimList.CloseToFilter2dRect (closeTo, closeToDistance)}; 102 101 } 103 102 104 Dictionary<P ersistentData.Player, List<Vector3i>> claims = LandClaimList.GetLandClaims (ownerFilters, posFilters);103 Dictionary<Player, List<Vector3i>> claims = LandClaimList.GetLandClaims (ownerFilters, posFilters); 105 104 106 foreach (KeyValuePair<P ersistentData.Player, List<Vector3i>> kvp in claims) {107 SdtdConsole.Instance.Output ( String.Format (105 foreach (KeyValuePair<Player, List<Vector3i>> kvp in claims) { 106 SdtdConsole.Instance.Output (string.Format ( 108 107 "Player \"{0} ({1})\" owns {4} keystones (protected: {2}, current hardness multiplier: {3})", 109 108 kvp.Key.Name, … … 115 114 foreach (Vector3i v in kvp.Value) { 116 115 if (parseableOutput) { 117 SdtdConsole.Instance.Output ("LandProtectionOf: id=" + kvp.Key.SteamID + ", playerName=" + kvp.Key.Name + ", location=" + v.ToString ()); 116 SdtdConsole.Instance.Output ("LandProtectionOf: id=" + kvp.Key.SteamID + 117 ", playerName=" + kvp.Key.Name + ", location=" + v); 118 118 } else { 119 SdtdConsole.Instance.Output (" (" + v .ToString ()+ ")");119 SdtdConsole.Instance.Output (" (" + v + ")"); 120 120 } 121 121 } … … 123 123 } 124 124 125 if (steamIdFilter.Length == 0) 125 if (steamIdFilter.Length == 0) { 126 126 SdtdConsole.Instance.Output ("Total of " + ppl.m_lpBlockMap.Count + " keystones in the game"); 127 } 127 128 } catch (Exception e) { 128 129 Log.Out ("Error in ListLandProtection.Run: " + e); -
binary-improvements/AllocsCommands/Commands/RemoveLandProtection.cs
r306 r325 1 1 using System; 2 2 using System.Collections.Generic; 3 using AllocsFixes.PersistentData; 3 4 4 namespace AllocsFixes.CustomCommands 5 { 6 public class RemoveLandProtection : ConsoleCmdAbstract 7 { 8 public override string GetDescription () 9 { 5 namespace AllocsFixes.CustomCommands { 6 public class RemoveLandProtection : ConsoleCmdAbstract { 7 public override string GetDescription () { 10 8 return "removes the association of a land protection block to the owner"; 11 9 } … … 13 11 public override string GetHelp () { 14 12 return "Usage:" + 15 16 17 18 19 20 13 " 1. removelandprotection <steamid>\n" + 14 " 2. removelandprotection <x> <y> <z>\n" + 15 " 3. removelandprotection nearby [length]\n" + 16 "1. Remove all land claims owned by the user with the given SteamID\n" + 17 "2. Remove only the claim block on the exactly given block position\n" + 18 "3. Remove all claims in a square with edge length of 64 (or the optionally specified size) around the executing player"; 21 19 } 22 20 23 public override string[] GetCommands () 24 { 25 return new string[] { "removelandprotection", "rlp" }; 21 public override string[] GetCommands () { 22 return new[] {"removelandprotection", "rlp"}; 26 23 } 27 24 28 private void removeById (string _id) 29 { 25 private void removeById (string _id) { 30 26 try { 31 27 PersistentPlayerList ppl = GameManager.Instance.GetPersistentPlayerList (); 32 28 33 29 if (_id.Length < 1 || !ppl.Players.ContainsKey (_id)) { 34 SdtdConsole.Instance.Output ("Not a valid Steam ID or user has never logged on. Use \"listlandprotection\" to get a list of keystones."); 30 SdtdConsole.Instance.Output ( 31 "Not a valid Steam ID or user has never logged on. Use \"listlandprotection\" to get a list of keystones."); 35 32 return; 36 33 } 34 37 35 if (ppl.Players [_id].LPBlocks == null || ppl.Players [_id].LPBlocks.Count == 0) { 38 SdtdConsole.Instance.Output ("Player does not own any keystones. Use \"listlandprotection\" to get a list of keystones."); 36 SdtdConsole.Instance.Output ( 37 "Player does not own any keystones. Use \"listlandprotection\" to get a list of keystones."); 39 38 return; 40 39 } 41 40 42 41 List<BlockChangeInfo> changes = new List<BlockChangeInfo> (); 43 foreach (Vector3i pos in ppl.Players [_id].LPBlocks) {42 foreach (Vector3i pos in ppl.Players [_id].LPBlocks) { 44 43 BlockChangeInfo bci = new BlockChangeInfo (pos, new BlockValue (0), true, false); 45 44 changes.Add (bci); 46 45 } 46 47 47 GameManager.Instance.SetBlocksRPC (changes); 48 48 49 SdtdConsole.Instance.Output ("Tried to remove #" + changes.Count + " land protection blocks for player \"" + _id + "\". Note "+ 50 "that only blocks in chunks that are currently loaded (close to any player) could be removed. "+ 51 "Please check for remaining blocks by running:"); 52 SdtdConsole.Instance.Output(" listlandprotection " + _id); 49 SdtdConsole.Instance.Output ("Tried to remove #" + changes.Count + 50 " land protection blocks for player \"" + _id + "\". Note " + 51 "that only blocks in chunks that are currently loaded (close to any player) could be removed. " + 52 "Please check for remaining blocks by running:"); 53 SdtdConsole.Instance.Output (" listlandprotection " + _id); 53 54 } catch (Exception e) { 54 55 Log.Out ("Error in RemoveLandProtection.removeById: " + e); … … 56 57 } 57 58 58 private void removeByPosition (List<string> _coords) 59 { 59 private void removeByPosition (List<string> _coords) { 60 60 try { 61 61 int x = int.MinValue; … … 77 77 Dictionary<Vector3i, PersistentPlayerData> d = ppl.m_lpBlockMap; 78 78 if (d == null || !d.ContainsKey (v)) { 79 SdtdConsole.Instance.Output ("No land protection block at the given position or not a valid position. Use \"listlandprotection\" to get a list of keystones."); 79 SdtdConsole.Instance.Output ( 80 "No land protection block at the given position or not a valid position. Use \"listlandprotection\" to get a list of keystones."); 80 81 return; 81 82 } … … 88 89 GameManager.Instance.SetBlocksRPC (changes); 89 90 90 SdtdConsole.Instance.Output ("Land protection block at (" + v .ToString ()+ ") removed");91 SdtdConsole.Instance.Output ("Land protection block at (" + v + ") removed"); 91 92 } catch (Exception e) { 92 93 Log.Out ("Error in RemoveLandProtection.removeByPosition: " + e); … … 94 95 } 95 96 96 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) 97 { 97 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) { 98 98 try { 99 99 if (_senderInfo.RemoteClientInfo != null) { … … 107 107 int closeToDistance = 32; 108 108 if (_params.Count == 3) { 109 if (!int.TryParse (_params [1], out closeToDistance)) {109 if (!int.TryParse (_params [1], out closeToDistance)) { 110 110 SdtdConsole.Instance.Output ("Given length is not an integer!"); 111 111 return; 112 112 } 113 113 114 closeToDistance /= 2; 114 115 } 116 115 117 ClientInfo ci = ConsoleHelper.ParseParamSteamIdOnline (_params [_params.Count - 1]); 116 118 EntityPlayer ep = GameManager.Instance.World.Players.dict [ci.entityId]; 117 119 Vector3i closeTo = new Vector3i (ep.GetPosition ()); 118 LandClaimList.PositionFilter[] posFilters = new LandClaimList.PositionFilter[] { LandClaimList.CloseToFilter2dRect (closeTo, closeToDistance) }; 119 Dictionary<PersistentData.Player, List<Vector3i>> claims = LandClaimList.GetLandClaims (null, posFilters); 120 LandClaimList.PositionFilter[] posFilters = 121 {LandClaimList.CloseToFilter2dRect (closeTo, closeToDistance)}; 122 Dictionary<Player, List<Vector3i>> claims = LandClaimList.GetLandClaims (null, posFilters); 120 123 121 124 try { 122 125 List<BlockChangeInfo> changes = new List<BlockChangeInfo> (); 123 foreach (KeyValuePair<P ersistentData.Player, List<Vector3i>> kvp in claims) {126 foreach (KeyValuePair<Player, List<Vector3i>> kvp in claims) { 124 127 foreach (Vector3i v in kvp.Value) { 125 128 BlockChangeInfo bci = new BlockChangeInfo (v, new BlockValue (0), true, false); … … 127 130 } 128 131 } 132 129 133 GameManager.Instance.SetBlocksRPC (changes); 130 134 } catch (Exception e) { 131 135 SdtdConsole.Instance.Output ("Error removing claims"); 132 136 Log.Out ("Error in RemoveLandProtection.Run: " + e); 133 return;134 137 } 135 138 } catch (Exception e) { 136 139 SdtdConsole.Instance.Output ("Error getting current player's position"); 137 140 Log.Out ("Error in RemoveLandProtection.Run: " + e); 138 return;139 141 } 140 142 } else if (_params.Count == 1) { -
binary-improvements/AllocsCommands/Commands/Reply.cs
r309 r325 1 using System;2 1 using System.Collections.Generic; 3 2 4 namespace AllocsFixes.CustomCommands 5 { 6 public class Reply : ConsoleCmdAbstract 7 { 8 public override string GetDescription () 9 { 3 namespace AllocsFixes.CustomCommands { 4 public class Reply : ConsoleCmdAbstract { 5 public override string GetDescription () { 10 6 return "send a message to the player who last sent you a PM"; 11 7 } … … 13 9 public override string GetHelp () { 14 10 return "Usage:\n" + 15 16 11 " reply <message>\n" + 12 "Send the given message to the user you last received a PM from."; 17 13 } 18 14 19 public override string[] GetCommands () 20 { 21 return new string[] { "reply", "re" }; 15 public override string[] GetCommands () { 16 return new[] {"reply", "re"}; 22 17 } 23 18 24 private void RunInternal (ClientInfo _sender, List<string> _params) 25 { 19 private void RunInternal (ClientInfo _sender, List<string> _params) { 26 20 if (_params.Count < 1) { 27 21 SdtdConsole.Instance.Output ("Usage: reply <message>"); … … 35 29 Chat.SendMessage (receiver, _sender, message); 36 30 } else { 37 SdtdConsole.Instance.Output ("You have not received a PM so far or sender of last received PM is no longer online."); 31 SdtdConsole.Instance.Output ( 32 "You have not received a PM so far or sender of last received PM is no longer online."); 38 33 } 39 34 } -
binary-improvements/AllocsCommands/Commands/SayToPlayer.cs
r238 r325 2 2 using System.Collections.Generic; 3 3 4 namespace AllocsFixes.CustomCommands 5 { 6 public class SayToPlayer : ConsoleCmdAbstract 7 { 8 public override string GetDescription () 9 { 4 namespace AllocsFixes.CustomCommands { 5 public class SayToPlayer : ConsoleCmdAbstract { 6 public override string GetDescription () { 10 7 return "send a message to a single player"; 11 8 } … … 13 10 public override string GetHelp () { 14 11 return "Usage:\n" + 15 16 12 " pm <player name / steam id / entity id> <message>\n" + 13 "Send a PM to the player given by the player name or entity id (as given by e.g. \"lpi\")."; 17 14 } 18 15 19 public override string[] GetCommands () 20 { 21 return new string[] { "sayplayer", "pm" }; 16 public override string[] GetCommands () { 17 return new[] {"sayplayer", "pm"}; 22 18 } 23 19 24 private void RunInternal (ClientInfo _sender, List<string> _params) 25 { 20 private void RunInternal (ClientInfo _sender, List<string> _params) { 26 21 if (_params.Count < 2) { 27 22 SdtdConsole.Instance.Output ("Usage: sayplayer <playername|entityid> <message>"); … … 39 34 } 40 35 41 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) 42 { 36 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) { 43 37 try { 44 38 if (_senderInfo.RemoteClientInfo != null) { -
binary-improvements/AllocsCommands/Commands/ShowInventory.cs
r297 r325 1 using AllocsFixes.PersistentData;2 1 using System; 3 2 using System.Collections.Generic; 3 using AllocsFixes.PersistentData; 4 4 5 namespace AllocsFixes.CustomCommands 6 { 7 public class ShowInventory : ConsoleCmdAbstract 8 { 9 10 public override string GetDescription () 11 { 5 namespace AllocsFixes.CustomCommands { 6 public class ShowInventory : ConsoleCmdAbstract { 7 public override string GetDescription () { 12 8 return "list inventory of a given player"; 13 9 } 14 10 15 public override string GetHelp () 16 { 11 public override string GetHelp () { 17 12 return "Usage:\n" + 18 " showinventory <steam id / player name / entity id> [tag]\n" +19 "Show the inventory of the player given by his SteamID, player name or\n" +20 "entity id (as given by e.g. \"lpi\").\n" +21 "Optionally specify a tag that is included in each line of the output. In\n" +22 "this case output is designed to be easily parseable by tools.\n" +23 "Note: This only shows the player's inventory after it was first sent to\n" +24 "the server which happens at least every 30 seconds.";13 " showinventory <steam id / player name / entity id> [tag]\n" + 14 "Show the inventory of the player given by his SteamID, player name or\n" + 15 "entity id (as given by e.g. \"lpi\").\n" + 16 "Optionally specify a tag that is included in each line of the output. In\n" + 17 "this case output is designed to be easily parseable by tools.\n" + 18 "Note: This only shows the player's inventory after it was first sent to\n" + 19 "the server which happens at least every 30 seconds."; 25 20 } 26 21 27 public override string[] GetCommands () 28 { 29 return new string[] { "showinventory", "si" }; 22 public override string[] GetCommands () { 23 return new[] {"showinventory", "si"}; 30 24 } 31 25 32 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) 33 { 26 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) { 34 27 try { 35 28 if (_params.Count < 1) { … … 40 33 string steamid = PersistentContainer.Instance.Players.GetSteamID (_params [0], true); 41 34 if (steamid == null) { 42 SdtdConsole.Instance.Output ("Playername or entity/steamid id not found or no inventory saved (first saved after a player has been online for 30s)."); 35 SdtdConsole.Instance.Output ( 36 "Playername or entity/steamid id not found or no inventory saved (first saved after a player has been online for 30s)."); 43 37 return; 44 38 } … … 52 46 PersistentData.Inventory inv = p.Inventory; 53 47 54 if (tag == null) 48 if (tag == null) { 55 49 SdtdConsole.Instance.Output ("Belt of player " + p.Name + ":"); 50 } 51 56 52 PrintInv (inv.belt, p.EntityID, "belt", tag); 57 if (tag == null) 53 if (tag == null) { 58 54 SdtdConsole.Instance.Output (string.Empty); 55 } 59 56 60 if (tag == null) 57 if (tag == null) { 61 58 SdtdConsole.Instance.Output ("Bagpack of player " + p.Name + ":"); 59 } 60 62 61 PrintInv (inv.bag, p.EntityID, "backpack", tag); 63 if (tag == null) 62 if (tag == null) { 64 63 SdtdConsole.Instance.Output (string.Empty); 64 } 65 65 66 if (tag == null) 66 if (tag == null) { 67 67 SdtdConsole.Instance.Output ("Equipment of player " + p.Name + ":"); 68 } 69 68 70 PrintEquipment (inv.equipment, p.EntityID, "equipment", tag); 69 71 70 if (tag != null) { 71 SdtdConsole.Instance.Output ("tracker_item id=" + p.EntityID + ", tag=" + tag + ", SHOWINVENTORY DONE"); 72 if (tag != null) { 73 SdtdConsole.Instance.Output ("tracker_item id=" + p.EntityID + ", tag=" + tag + 74 ", SHOWINVENTORY DONE"); 72 75 } 73 74 76 } catch (Exception e) { 75 77 Log.Out ("Error in ShowInventory.Run: " + e); … … 77 79 } 78 80 79 private void PrintInv (List<InvItem> _inv, int _entityId, string _location, string _tag) 80 { 81 private void PrintInv (List<InvItem> _inv, int _entityId, string _location, string _tag) { 81 82 for (int i = 0; i < _inv.Count; i++) { 82 83 if (_inv [i] != null) { 83 if (_tag == null) { // no Tag defined -> readable output 84 if (_tag == null) { 85 // no Tag defined -> readable output 84 86 if (_inv [i].quality < 0) { 85 SdtdConsole.Instance.Output (string.Format (" Slot {0}: {1:000} * {2}", i, _inv [i].count, _inv [i].itemName)); 87 SdtdConsole.Instance.Output (string.Format (" Slot {0}: {1:000} * {2}", i, 88 _inv [i].count, _inv [i].itemName)); 86 89 } else { 87 SdtdConsole.Instance.Output (string.Format (" Slot {0}: {1:000} * {2} - quality: {3}", i, _inv [i].count, _inv [i].itemName, _inv [i].quality)); 90 SdtdConsole.Instance.Output (string.Format (" Slot {0}: {1:000} * {2} - quality: {3}", i, 91 _inv [i].count, _inv [i].itemName, _inv [i].quality)); 88 92 } 93 89 94 DoParts (_inv [i].parts, 1, null); 90 } else { // Tag defined -> parseable output 91 String partsMsg = DoParts(_inv[i].parts, 1, ""); 92 String msg = "tracker_item id=" + _entityId + ", tag=" + _tag + ", location=" + _location + ", slot=" + i + ", item=" + _inv[i].itemName + ", qnty=" + _inv[i].count + ", quality=" + _inv[i].quality + ", parts=(" + partsMsg + ")"; 93 SdtdConsole.Instance.Output(msg); 95 } else { 96 // Tag defined -> parseable output 97 string partsMsg = DoParts (_inv [i].parts, 1, ""); 98 string msg = "tracker_item id=" + _entityId + ", tag=" + _tag + ", location=" + _location + 99 ", slot=" + i + ", item=" + _inv [i].itemName + ", qnty=" + _inv [i].count + 100 ", quality=" + _inv [i].quality + ", parts=(" + partsMsg + ")"; 101 SdtdConsole.Instance.Output (msg); 94 102 } 95 103 } … … 97 105 } 98 106 99 private void PrintEquipment (InvItem[] _equipment, int _entityId, string _location, string _tag) 100 { 107 private void PrintEquipment (InvItem[] _equipment, int _entityId, string _location, string _tag) { 101 108 AddEquipment ("head", _equipment, EquipmentSlots.Headgear, _entityId, _location, _tag); 102 109 AddEquipment ("eyes", _equipment, EquipmentSlots.Eyewear, _entityId, _location, _tag); … … 114 121 } 115 122 116 private void AddEquipment (string _slotname, InvItem[] _items, EquipmentSlots _slot, int _entityId, string _location, string _tag)117 {123 private void AddEquipment (string _slotname, InvItem[] _items, EquipmentSlots _slot, int _entityId, 124 string _location, string _tag) { 118 125 int[] slotindices = XUiM_PlayerEquipment.GetSlotIndicesByEquipmentSlot (_slot); 119 126 … … 121 128 if (_items != null && _items [slotindices [i]] != null) { 122 129 InvItem item = _items [slotindices [i]]; 123 if (_tag == null) { // no Tag defined -> readable output 130 if (_tag == null) { 131 // no Tag defined -> readable output 124 132 if (item.quality < 0) { 125 SdtdConsole.Instance.Output (string.Format (" Slot {0:8}: {1:000}", _slotname, item.itemName)); 133 SdtdConsole.Instance.Output (string.Format (" Slot {0:8}: {1:000}", _slotname, 134 item.itemName)); 126 135 } else { 127 SdtdConsole.Instance.Output (string.Format (" Slot {0:8}: {1:000} - quality: {2}", _slotname, item.itemName, item.quality)); 136 SdtdConsole.Instance.Output (string.Format (" Slot {0:8}: {1:000} - quality: {2}", 137 _slotname, item.itemName, item.quality)); 128 138 } 139 129 140 DoParts (_items [slotindices [i]].parts, 1, null); 130 } else { // Tag defined -> parseable output 131 String partsMsg = DoParts(_items[slotindices[i]].parts, 1, ""); 132 String msg = "tracker_item id=" + _entityId + ", tag=" + _tag + ", location=" + _location + ", slot=" + _slotname + ", item=" + item.itemName + ", qnty=1, quality=" + item.quality + ", parts=(" + partsMsg + ")"; 133 SdtdConsole.Instance.Output(msg); 141 } else { 142 // Tag defined -> parseable output 143 string partsMsg = DoParts (_items [slotindices [i]].parts, 1, ""); 144 string msg = "tracker_item id=" + _entityId + ", tag=" + _tag + ", location=" + _location + 145 ", slot=" + _slotname + ", item=" + item.itemName + ", qnty=1, quality=" + 146 item.quality + ", parts=(" + partsMsg + ")"; 147 SdtdConsole.Instance.Output (msg); 134 148 } 149 135 150 return; 136 151 } … … 138 153 } 139 154 140 private string DoParts (InvItem[] _parts, int _indent, string _currentMessage) 141 { 155 private string DoParts (InvItem[] _parts, int _indent, string _currentMessage) { 142 156 if (_parts != null && _parts.Length > 0) { 143 157 string indenter = new string (' ', _indent * 4); 144 158 for (int i = 0; i < _parts.Length; i++) { 145 159 if (_parts [i] != null) { 146 if (_currentMessage == null) { // no currentMessage given -> readable output 160 if (_currentMessage == null) { 161 // no currentMessage given -> readable output 147 162 if (_parts [i].quality < 0) { 148 SdtdConsole.Instance.Output (string.Format ("{0} - {1}", indenter, _parts [i].itemName)); 163 SdtdConsole.Instance.Output (string.Format ("{0} - {1}", indenter, 164 _parts [i].itemName)); 149 165 } else { 150 SdtdConsole.Instance.Output (string.Format ("{0} - {1} - quality: {2}", indenter, _parts [i].itemName, _parts [i].quality)); 166 SdtdConsole.Instance.Output (string.Format ("{0} - {1} - quality: {2}", 167 indenter, _parts [i].itemName, _parts [i].quality)); 151 168 } 169 152 170 DoParts (_parts [i].parts, _indent + 1, _currentMessage); 153 } else { // currentMessage given -> parseable output 171 } else { 172 // currentMessage given -> parseable output 154 173 if (_currentMessage.Length > 0) { 155 174 _currentMessage += ","; 156 175 } 157 _currentMessage += _parts[i].itemName + "@" + _parts[i].quality; 176 177 _currentMessage += _parts [i].itemName + "@" + _parts [i].quality; 158 178 _currentMessage = DoParts (_parts [i].parts, _indent + 1, _currentMessage); 159 179 } … … 161 181 } 162 182 } 183 163 184 return _currentMessage; 164 185 } 165 166 186 } 167 187 } -
binary-improvements/AllocsCommands/PrivateMessageConnections.cs
r324 r325 1 using System;2 1 using System.Collections.Generic; 3 2 using Steamworks; 4 3 5 namespace AllocsFixes.CustomCommands 6 { 7 public class PrivateMessageConnections 8 { 9 private static Dictionary<CSteamID, CSteamID> senderOfLastPM = new Dictionary<CSteamID, CSteamID> (); 4 namespace AllocsFixes.CustomCommands { 5 public class PrivateMessageConnections { 6 private static readonly Dictionary<CSteamID, CSteamID> senderOfLastPM = new Dictionary<CSteamID, CSteamID> (); 10 7 11 public static void SetLastPMSender (ClientInfo _sender, ClientInfo _receiver) 12 { 8 public static void SetLastPMSender (ClientInfo _sender, ClientInfo _receiver) { 13 9 senderOfLastPM [_receiver.steamId] = _sender.steamId; 14 10 } 15 11 16 public static ClientInfo GetLastPMSenderForPlayer (ClientInfo _player) 17 { 12 public static ClientInfo GetLastPMSenderForPlayer (ClientInfo _player) { 18 13 if (senderOfLastPM.ContainsKey (_player.steamId)) { 19 14 CSteamID recSteamId = senderOfLastPM [_player.steamId]; … … 21 16 return recInfo; 22 17 } 18 23 19 return null; 24 20 } -
binary-improvements/MapRendering/API.cs
r324 r325 1 using System; 1 using AllocsFixes.NetConnections.Servers.Web; 2 using AllocsFixes.NetConnections.Servers.Web.Handlers; 2 3 3 namespace MapRendering 4 { 4 namespace MapRendering { 5 5 public class API : IModApi { 6 public void InitMod () { 7 ModEvents.GameAwake.RegisterHandler (GameAwake); 8 ModEvents.GameStartDone.RegisterHandler (GameStartDone); 9 ModEvents.GameShutdown.RegisterHandler (GameShutdown); 10 ModEvents.CalcChunkColorsDone.RegisterHandler (CalcChunkColorsDone); 11 } 12 6 13 private void GameAwake () { 7 14 // ReSharper disable once ObjectCreationAsStatement 8 new AllocsFixes.NetConnections.Servers.Web.Web ();9 AllocsFixes.NetConnections.Servers.Web.LogBuffer.Instance.GetType ();15 new Web (); 16 LogBuffer.Instance.GetType (); 10 17 } 11 18 12 19 private void GameStartDone () { 13 if ( AllocsFixes.NetConnections.Servers.Web.Handlers.ItemIconHandler.Instance != null) {14 AllocsFixes.NetConnections.Servers.Web.Handlers.ItemIconHandler.Instance.LoadIcons ();20 if (ItemIconHandler.Instance != null) { 21 ItemIconHandler.Instance.LoadIcons (); 15 22 } 16 23 } … … 23 30 AllocsFixes.MapRendering.MapRendering.RenderSingleChunk (_chunk); 24 31 } 25 26 public void InitMod () {27 ModEvents.GameAwake.RegisterHandler (GameAwake);28 ModEvents.GameStartDone.RegisterHandler (GameStartDone);29 ModEvents.GameShutdown.RegisterHandler (GameShutdown);30 ModEvents.CalcChunkColorsDone.RegisterHandler (CalcChunkColorsDone);31 }32 32 } 33 33 } 34 -
binary-improvements/MapRendering/AssemblyInfo.cs
r232 r325 1 1 using System.Reflection; 2 using System.Runtime.CompilerServices;3 2 4 3 // Information about this assembly is defined by the following attributes. 5 4 // Change them to the values specific to your project. 6 5 7 [assembly: AssemblyTitle ("MapRendering")]8 [assembly: AssemblyDescription ("")]9 [assembly: AssemblyConfiguration ("")]10 [assembly: AssemblyCompany ("")]11 [assembly: AssemblyProduct ("")]12 [assembly: AssemblyCopyright ("ci")]13 [assembly: AssemblyTrademark ("")]14 [assembly: AssemblyCulture ("")]6 [assembly: AssemblyTitle ("MapRendering")] 7 [assembly: AssemblyDescription ("")] 8 [assembly: AssemblyConfiguration ("")] 9 [assembly: AssemblyCompany ("")] 10 [assembly: AssemblyProduct ("")] 11 [assembly: AssemblyCopyright ("ci")] 12 [assembly: AssemblyTrademark ("")] 13 [assembly: AssemblyCulture ("")] 15 14 16 15 // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". … … 18 17 // and "{Major}.{Minor}.{Build}.*" will update just the revision. 19 18 20 [assembly: AssemblyVersion ("0.0.0.0")]19 [assembly: AssemblyVersion ("0.0.0.0")] 21 20 22 21 // The following attributes are used to specify the signing key for the assembly, … … 25 24 //[assembly: AssemblyDelaySign(false)] 26 25 //[assembly: AssemblyKeyFile("")] 27 -
binary-improvements/MapRendering/Commands/EnableOpenIDDebug.cs
r318 r325 1 1 using System; 2 2 using System.Collections.Generic; 3 using AllocsFixes.NetConnections.Servers.Web; 3 4 4 namespace AllocsFixes.CustomCommands 5 { 6 public class EnableOpenIDDebug : ConsoleCmdAbstract 7 { 8 public override string GetDescription () 9 { 5 namespace AllocsFixes.CustomCommands { 6 public class EnableOpenIDDebug : ConsoleCmdAbstract { 7 public override string GetDescription () { 10 8 return "enable/disable OpenID debugging"; 11 9 } 12 10 13 public override string[] GetCommands () 14 { 15 return new string[] { "openiddebug" }; 11 public override string[] GetCommands () { 12 return new[] {"openiddebug"}; 16 13 } 17 14 18 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) 19 { 15 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) { 20 16 try { 21 17 if (_params.Count != 1) { 22 SdtdConsole.Instance.Output ("Current state: " + AllocsFixes.NetConnections.Servers.Web.OpenID.debugOpenId);18 SdtdConsole.Instance.Output ("Current state: " + OpenID.debugOpenId); 23 19 return; 24 20 } 25 21 26 AllocsFixes.NetConnections.Servers.Web.OpenID.debugOpenId = _params[0].Equals("1");22 OpenID.debugOpenId = _params [0].Equals ("1"); 27 23 SdtdConsole.Instance.Output ("Set OpenID debugging to " + _params [0].Equals ("1")); 28 24 } catch (Exception e) { -
binary-improvements/MapRendering/Commands/EnableRendering.cs
r230 r325 2 2 using System.Collections.Generic; 3 3 4 namespace AllocsFixes.CustomCommands 5 { 6 public class EnableRendering : ConsoleCmdAbstract 7 { 8 public override string GetDescription () 9 { 4 namespace AllocsFixes.CustomCommands { 5 public class EnableRendering : ConsoleCmdAbstract { 6 public override string GetDescription () { 10 7 return "enable/disable live map rendering"; 11 8 } 12 9 13 public override string[] GetCommands () 14 { 15 return new string[] { "enablerendering" }; 10 public override string[] GetCommands () { 11 return new[] {"enablerendering"}; 16 12 } 17 13 18 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) 19 { 14 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) { 20 15 try { 21 16 if (_params.Count != 1) { 22 SdtdConsole.Instance.Output ("Current state: " + AllocsFixes.MapRendering.MapRendering.renderingEnabled);17 SdtdConsole.Instance.Output ("Current state: " + MapRendering.MapRendering.renderingEnabled); 23 18 return; 24 19 } 25 20 26 AllocsFixes.MapRendering.MapRendering.renderingEnabled = _params[0].Equals("1");21 MapRendering.MapRendering.renderingEnabled = _params [0].Equals ("1"); 27 22 SdtdConsole.Instance.Output ("Set live map rendering to " + _params [0].Equals ("1")); 28 23 } catch (Exception e) { -
binary-improvements/MapRendering/Commands/ReloadWebPermissions.cs
r244 r325 1 1 using System; 2 2 using System.Collections.Generic; 3 using AllocsFixes.NetConnections.Servers.Web; 3 4 4 namespace AllocsFixes.CustomCommands 5 { 6 public class ReloadWebPermissions : ConsoleCmdAbstract 7 { 8 public override string GetDescription () 9 { 5 namespace AllocsFixes.CustomCommands { 6 public class ReloadWebPermissions : ConsoleCmdAbstract { 7 public override string GetDescription () { 10 8 return "force reload of web permissions file"; 11 9 } 12 10 13 public override string[] GetCommands () 14 { 15 return new string[] { "reloadwebpermissions" }; 11 public override string[] GetCommands () { 12 return new[] {"reloadwebpermissions"}; 16 13 } 17 14 18 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) 19 { 15 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) { 20 16 try { 21 AllocsFixes.NetConnections.Servers.Web.WebPermissions.Instance.Load ();17 WebPermissions.Instance.Load (); 22 18 SdtdConsole.Instance.Output ("Web permissions file reloaded"); 23 19 } catch (Exception e) { -
binary-improvements/MapRendering/Commands/RenderMap.cs
r230 r325 1 using AllocsFixes.MapRendering;2 1 using System; 3 using System.IO;4 2 using System.Collections.Generic; 5 3 6 namespace AllocsFixes.CustomCommands 7 { 8 public class RenderMap : ConsoleCmdAbstract 9 { 10 public override string GetDescription () 11 { 4 namespace AllocsFixes.CustomCommands { 5 public class RenderMap : ConsoleCmdAbstract { 6 public override string GetDescription () { 12 7 return "render the current map to a file"; 13 8 } 14 9 15 public override string[] GetCommands () 16 { 17 return new string[] { "rendermap" }; 10 public override string[] GetCommands () { 11 return new[] {"rendermap"}; 18 12 } 19 13 20 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) 21 { 14 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) { 22 15 try { 23 AllocsFixes.MapRendering.MapRendering.Instance.RenderFullMap ();16 MapRendering.MapRendering.Instance.RenderFullMap (); 24 17 25 18 SdtdConsole.Instance.Output ("Render map done"); -
binary-improvements/MapRendering/Commands/WebPermissionsCmd.cs
r244 r325 1 using System;2 1 using System.Collections.Generic; 3 using System.IO;2 using AllocsFixes.NetConnections.Servers.Web; 4 3 5 using AllocsFixes.NetConnections.Servers.Web; 6 using UnityEngine; 7 8 namespace AllocsFixes.CustomCommands 9 { 4 namespace AllocsFixes.CustomCommands { 10 5 public class WebPermissionsCmd : ConsoleCmdAbstract { 11 6 public override string[] GetCommands () { 12 return new string[] { "webpermission"};7 return new[] {"webpermission"}; 13 8 } 14 15 public override string GetDescription () { 9 10 public override string GetDescription () { 16 11 return "Manage web permission levels"; 17 12 } 18 13 19 14 public override string GetHelp () { 20 15 return "Set/get permission levels required to access a given web functionality. Default\n" + 21 22 23 24 25 16 "level required for functions that are not explicitly specified is 0.\n" + 17 "Usage:\n" + 18 " webpermission add <webfunction> <level>\n" + 19 " webpermission remove <webfunction>\n" + 20 " webpermission list"; 26 21 } 27 22 28 23 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) { 29 24 if (_params.Count >= 1) { … … 46 41 } 47 42 } 48 43 49 44 private void ExecuteAdd (List<string> _params) { 50 45 if (_params.Count != 3) { … … 52 47 return; 53 48 } 54 49 55 50 if (!WebPermissions.Instance.IsKnownModule (_params [1])) { 56 51 SdtdConsole.Instance.Output ("\"" + _params [1] + "\" is not a valid web function."); 57 52 return; 58 53 } 59 54 60 55 int level; 61 56 if (!int.TryParse (_params [2], out level)) { … … 63 58 return; 64 59 } 65 60 66 61 WebPermissions.Instance.AddModulePermission (_params [1], level); 67 62 SdtdConsole.Instance.Output (string.Format ("{0} added with permission level of {1}.", _params [1], level)); 68 63 } 69 64 70 65 private void ExecuteRemove (List<string> _params) { 71 66 if (_params.Count != 2) { … … 73 68 return; 74 69 } 75 70 76 71 if (!WebPermissions.Instance.IsKnownModule (_params [1])) { 77 72 SdtdConsole.Instance.Output ("\"" + _params [1] + "\" is not a valid web function."); 78 73 return; 79 74 } 80 75 81 76 WebPermissions.Instance.RemoveModulePermission (_params [1]); 82 77 SdtdConsole.Instance.Output (string.Format ("{0} removed from permissions list.", _params [1])); 83 78 } 84 79 85 80 private void ExecuteList () { 86 81 SdtdConsole.Instance.Output ("Defined web function permissions:"); … … 90 85 } 91 86 } 92 93 87 } 94 88 } -
binary-improvements/MapRendering/Commands/WebTokens.cs
r244 r325 1 using System;2 1 using System.Collections.Generic; 3 using System.IO;4 2 using System.Text.RegularExpressions; 3 using AllocsFixes.NetConnections.Servers.Web; 5 4 6 using AllocsFixes.NetConnections.Servers.Web; 7 using UnityEngine; 8 9 namespace AllocsFixes.CustomCommands 10 { 5 namespace AllocsFixes.CustomCommands { 11 6 public class WebTokens : ConsoleCmdAbstract { 12 private static Regex validNameTokenMatcher = new Regex (@"^\w+$");7 private static readonly Regex validNameTokenMatcher = new Regex (@"^\w+$"); 13 8 14 9 public override string[] GetCommands () { 15 return new string[] { "webtokens"};10 return new[] {"webtokens"}; 16 11 } 17 18 public override string GetDescription () { 12 13 public override string GetDescription () { 19 14 return "Manage web tokens"; 20 15 } … … 22 17 public override string GetHelp () { 23 18 return "Set/get webtoken permission levels. A level of 0 is maximum permission.\n" + 24 25 26 27 19 "Usage:\n" + 20 " webtokens add <username> <usertoken> <level>\n" + 21 " webtokens remove <username>\n" + 22 " webtokens list"; 28 23 } 29 24 30 25 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) { 31 26 if (_params.Count >= 1) { … … 61 56 62 57 if (!validNameTokenMatcher.IsMatch (_params [1])) { 63 SdtdConsole.Instance.Output ("Argument 'username' may only contain characters (A-Z, a-z), digits (0-9) and underscores (_)."); 58 SdtdConsole.Instance.Output ( 59 "Argument 'username' may only contain characters (A-Z, a-z), digits (0-9) and underscores (_)."); 64 60 return; 65 61 } … … 71 67 72 68 if (!validNameTokenMatcher.IsMatch (_params [2])) { 73 SdtdConsole.Instance.Output ("Argument 'usertoken' may only contain characters (A-Z, a-z), digits (0-9) and underscores (_)."); 69 SdtdConsole.Instance.Output ( 70 "Argument 'usertoken' may only contain characters (A-Z, a-z), digits (0-9) and underscores (_)."); 74 71 return; 75 72 } … … 82 79 83 80 WebPermissions.Instance.AddAdmin (_params [1], _params [2], level); 84 SdtdConsole.Instance.Output (string.Format ("Web user with name={0} and password={1} added with permission level of {2}.", _params [1], _params [2], level)); 81 SdtdConsole.Instance.Output (string.Format ( 82 "Web user with name={0} and password={1} added with permission level of {2}.", _params [1], _params [2], 83 level)); 85 84 } 86 85 87 86 private void ExecuteRemove (List<string> _params) { 88 87 if (_params.Count != 2) { … … 90 89 return; 91 90 } 92 91 93 92 if (string.IsNullOrEmpty (_params [1])) { 94 93 SdtdConsole.Instance.Output ("Argument 'username' is empty."); … … 97 96 98 97 if (!validNameTokenMatcher.IsMatch (_params [1])) { 99 SdtdConsole.Instance.Output ("Argument 'username' may only contain characters (A-Z, a-z), digits (0-9) and underscores (_)."); 98 SdtdConsole.Instance.Output ( 99 "Argument 'username' may only contain characters (A-Z, a-z), digits (0-9) and underscores (_)."); 100 100 return; 101 101 } … … 104 104 SdtdConsole.Instance.Output (string.Format ("{0} removed from web user permissions list.", _params [1])); 105 105 } 106 106 107 107 private void ExecuteList () { 108 108 SdtdConsole.Instance.Output ("Defined webuser permissions:"); 109 109 SdtdConsole.Instance.Output (" Level: Name / Token"); 110 110 foreach (WebPermissions.AdminToken at in WebPermissions.Instance.GetAdmins ()) { 111 SdtdConsole.Instance.Output (string.Format (" {0,5}: {1} / {2}", at.permissionLevel, at.name, at.token)); 111 SdtdConsole.Instance.Output ( 112 string.Format (" {0,5}: {1} / {2}", at.permissionLevel, at.name, at.token)); 112 113 } 113 114 } 114 115 115 } 116 116 } -
binary-improvements/MapRendering/Commands/webstat.cs
r279 r325 1 1 using System; 2 2 using System.Collections.Generic; 3 using AllocsFixes.NetConnections.Servers.Web; 3 4 4 namespace AllocsFixes.CustomCommands 5 { 6 public class webstat : ConsoleCmdAbstract 7 { 8 public override string GetDescription () 9 { 5 namespace AllocsFixes.CustomCommands { 6 public class webstat : ConsoleCmdAbstract { 7 public override string GetDescription () { 10 8 return "DEBUG PURPOSES ONLY"; 11 9 } 12 10 13 public override string[] GetCommands () 14 { 15 return new string[] { "webstat" }; 11 public override string[] GetCommands () { 12 return new[] {"webstat"}; 16 13 } 17 14 18 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) 19 { 15 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) { 20 16 try { 21 int curHandlers = AllocsFixes.NetConnections.Servers.Web.Web.currentHandlers;22 int totalHandlers = AllocsFixes.NetConnections.Servers.Web.Web.handlingCount;23 long totalTime = AllocsFixes.NetConnections.Servers.Web.Web.totalHandlingTime;17 int curHandlers = Web.currentHandlers; 18 int totalHandlers = Web.handlingCount; 19 long totalTime = Web.totalHandlingTime; 24 20 SdtdConsole.Instance.Output ("Current Web handlers: " + curHandlers + " - total: " + totalHandlers); 25 SdtdConsole.Instance.Output (" - Total time: " + totalTime + " µs - average time: " + (totalTime / totalHandlers) + " µs"); 21 SdtdConsole.Instance.Output (" - Total time: " + totalTime + " µs - average time: " + 22 totalTime / totalHandlers + " µs"); 26 23 27 curHandlers = AllocsFixes.NetConnections.Servers.Web.WebCommandResult.currentHandlers; 28 totalHandlers = AllocsFixes.NetConnections.Servers.Web.WebCommandResult.handlingCount; 29 totalTime = AllocsFixes.NetConnections.Servers.Web.WebCommandResult.totalHandlingTime; 30 SdtdConsole.Instance.Output ("Current Web command handlers: " + curHandlers + " - total: " + totalHandlers); 31 SdtdConsole.Instance.Output (" - Total time: " + totalTime + " µs" + (totalHandlers > 0 ? " - average time: " + (totalTime / totalHandlers) + " µs" : "")); 24 curHandlers = WebCommandResult.currentHandlers; 25 totalHandlers = WebCommandResult.handlingCount; 26 totalTime = WebCommandResult.totalHandlingTime; 27 SdtdConsole.Instance.Output ("Current Web command handlers: " + curHandlers + " - total: " + 28 totalHandlers); 29 SdtdConsole.Instance.Output (" - Total time: " + totalTime + " µs" + 30 (totalHandlers > 0 31 ? " - average time: " + totalTime / totalHandlers + " µs" 32 : "")); 32 33 } catch (Exception e) { 33 34 Log.Out ("Error in webstat.Run: " + e); -
binary-improvements/MapRendering/MapRendering/Constants.cs
r224 r325 1 using System; 2 3 namespace AllocsFixes.MapRendering 4 { 5 public class Constants 6 { 1 namespace AllocsFixes.MapRendering { 2 public class Constants { 7 3 public static int MAP_BLOCK_SIZE = 128; 8 4 public static int MAP_CHUNK_SIZE = 16; 9 5 public static int MAP_REGION_SIZE = 512; 10 public static int MAP_BLOCK_TO_CHUNK_DIV { get { return MAP_BLOCK_SIZE / MAP_CHUNK_SIZE; } }11 public static int MAP_REGION_TO_CHUNK_DIV { get { return MAP_REGION_SIZE / MAP_CHUNK_SIZE; } }12 6 public static int ZOOMLEVELS = 5; 13 7 public static string MAP_DIRECTORY = string.Empty; 8 9 public static int MAP_BLOCK_TO_CHUNK_DIV { 10 get { return MAP_BLOCK_SIZE / MAP_CHUNK_SIZE; } 11 } 12 13 public static int MAP_REGION_TO_CHUNK_DIV { 14 get { return MAP_REGION_SIZE / MAP_CHUNK_SIZE; } 15 } 14 16 } 15 17 } 16 -
binary-improvements/MapRendering/MapRendering/MapRenderBlockBuffer.cs
r238 r325 1 1 using System; 2 2 using System.IO; 3 using System.Threading;3 using AllocsFixes.FileCache; 4 4 using UnityEngine; 5 5 6 namespace AllocsFixes.MapRendering 7 { 8 public class MapRenderBlockBuffer 9 { 10 private int zoomLevel; 6 namespace AllocsFixes.MapRendering { 7 public class MapRenderBlockBuffer { 8 private readonly Texture2D blockMap = new Texture2D (Constants.MAP_BLOCK_SIZE, Constants.MAP_BLOCK_SIZE); 9 private readonly MapTileCache cache; 10 private readonly Color nullColor = new Color (0, 0, 0, 0); 11 private readonly Texture2D zoomBuffer = new Texture2D (1, 1); 12 private readonly int zoomLevel; 11 13 private string currentBlockMap = string.Empty; 12 private Texture2D blockMap = new Texture2D (Constants.MAP_BLOCK_SIZE, Constants.MAP_BLOCK_SIZE);13 private Texture2D zoomBuffer = new Texture2D (1, 1);14 private Color nullColor = new Color (0, 0, 0, 0);15 private AllocsFixes.FileCache.MapTileCache cache;16 14 17 public MapRenderBlockBuffer (int level, AllocsFixes.FileCache.MapTileCache cache) 18 { 15 public MapRenderBlockBuffer (int level, MapTileCache cache) { 19 16 zoomLevel = level; 20 17 this.cache = cache; 21 18 } 22 19 23 public void ResetBlock () 24 { 20 public void ResetBlock () { 25 21 currentBlockMap = string.Empty; 26 22 } 27 23 28 public void SaveBlock () 29 { 24 public void SaveBlock () { 30 25 try { 31 if (currentBlockMap.Length > 0) 26 if (currentBlockMap.Length > 0) { 32 27 saveTextureToFile (currentBlockMap); 28 } 33 29 } catch (Exception e) { 34 30 Log.Out ("Exception in MapRenderBlockBuffer.SaveBlock(): " + e); … … 36 32 } 37 33 38 public bool LoadBlock (Vector2i block) 39 { 34 public bool LoadBlock (Vector2i block) { 40 35 bool res = false; 41 36 lock (blockMap) { 42 string folder = Constants.MAP_DIRECTORY + "/" + (zoomLevel)+ "/" + block.x;37 string folder = Constants.MAP_DIRECTORY + "/" + zoomLevel + "/" + block.x; 43 38 string fileName = folder + "/" + block.y + ".png"; 44 39 Directory.CreateDirectory (folder); … … 48 43 loadTextureFromFile (fileName); 49 44 } 45 50 46 currentBlockMap = fileName; 51 47 } 48 52 49 return res; 53 50 } … … 55 52 public void SetPart (Vector2i offset, int partSize, Color32[] pixels) { 56 53 if (offset.x + partSize > blockMap.width || offset.y + partSize > blockMap.height) { 57 Log.Error (string.Format ("MapBlockBuffer[{0}].SetPart ({1}, {2}, {3}) has blockMap.size ({4}/{5})", zoomLevel, offset, partSize, pixels.Length, blockMap.width, blockMap.height)); 54 Log.Error (string.Format ("MapBlockBuffer[{0}].SetPart ({1}, {2}, {3}) has blockMap.size ({4}/{5})", 55 zoomLevel, offset, partSize, pixels.Length, blockMap.width, blockMap.height)); 58 56 return; 59 57 } 58 60 59 blockMap.SetPixels32 (offset.x, offset.y, partSize, partSize, pixels); 61 60 } 62 61 63 public Color32[] GetHalfScaled () 64 { 62 public Color32[] GetHalfScaled () { 65 63 zoomBuffer.Resize (Constants.MAP_BLOCK_SIZE, Constants.MAP_BLOCK_SIZE); 66 64 zoomBuffer.SetPixels32 (blockMap.GetPixels32 ()); … … 71 69 } 72 70 73 private void loadTextureFromFile (string _fileName) 74 { 71 private void loadTextureFromFile (string _fileName) { 75 72 byte[] array = cache.LoadTile (zoomLevel, _fileName); 76 if (array == null || !blockMap.LoadImage (array) || blockMap.height != Constants.MAP_BLOCK_SIZE || blockMap.width != Constants.MAP_BLOCK_SIZE) { 73 if (array == null || !blockMap.LoadImage (array) || blockMap.height != Constants.MAP_BLOCK_SIZE || 74 blockMap.width != Constants.MAP_BLOCK_SIZE) { 77 75 if (array != null) { 78 76 Log.Error ("Map image tile " + _fileName + " has been corrupted, recreating tile"); … … 82 80 blockMap.Resize (Constants.MAP_BLOCK_SIZE, Constants.MAP_BLOCK_SIZE); 83 81 } 82 84 83 for (int x = 0; x < Constants.MAP_BLOCK_SIZE; x++) { 85 84 for (int y = 0; y < Constants.MAP_BLOCK_SIZE; y++) { … … 94 93 cache.SaveTile (zoomLevel, array); 95 94 } 96 97 95 } 98 96 } -
binary-improvements/MapRendering/MapRendering/MapRendering.cs
r299 r325 1 using AllocsFixes.JSON;2 1 using System; 2 using System.Collections; 3 3 using System.Collections.Generic; 4 4 using System.IO; 5 5 using System.Text; 6 6 using System.Threading; 7 using System.Timers; 8 using AllocsFixes.FileCache; 9 using AllocsFixes.JSON; 7 10 using UnityEngine; 8 9 namespace AllocsFixes.MapRendering 10 { 11 public class MapRendering 12 { 11 using Object = UnityEngine.Object; 12 13 namespace AllocsFixes.MapRendering { 14 public class MapRendering { 13 15 private static MapRendering instance; 16 17 private static readonly object lockObject = new object (); 18 public static bool renderingEnabled = true; 19 private readonly MapTileCache cache = new MapTileCache (Constants.MAP_BLOCK_SIZE); 20 private readonly Dictionary<Vector2i, Color32[]> dirtyChunks = new Dictionary<Vector2i, Color32[]> (); 21 private readonly MicroStopwatch msw = new MicroStopwatch (); 22 private readonly MapRenderBlockBuffer[] zoomLevelBuffers; 23 private Coroutine renderCoroutineRef; 24 private bool renderingFullMap; 25 private float renderTimeout = float.MaxValue; 26 27 private MapRendering () { 28 Constants.MAP_DIRECTORY = GameUtils.GetSaveGameDir () + "/map"; 29 30 lock (lockObject) { 31 if (!LoadMapInfo ()) { 32 WriteMapInfo (); 33 } 34 } 35 36 cache.SetZoomCount (Constants.ZOOMLEVELS); 37 38 zoomLevelBuffers = new MapRenderBlockBuffer[Constants.ZOOMLEVELS]; 39 for (int i = 0; i < Constants.ZOOMLEVELS; i++) { 40 zoomLevelBuffers [i] = new MapRenderBlockBuffer (i, cache); 41 } 42 43 renderCoroutineRef = ThreadManager.StartCoroutine (renderCoroutine ()); 44 } 14 45 15 46 public static MapRendering Instance { … … 18 49 instance = new MapRendering (); 19 50 } 51 20 52 return instance; 21 53 } 22 54 } 23 55 24 private static object lockObject = new object (); 25 private MapRenderBlockBuffer[] zoomLevelBuffers; 26 private Dictionary<Vector2i, Color32[]> dirtyChunks = new Dictionary<Vector2i, Color32[]> (); 27 private bool renderingFullMap = false; 28 public static bool renderingEnabled = true; 29 private MicroStopwatch msw = new MicroStopwatch (); 30 private AllocsFixes.FileCache.MapTileCache cache = new AllocsFixes.FileCache.MapTileCache (Constants.MAP_BLOCK_SIZE); 31 private float renderTimeout = float.MaxValue; 32 private Coroutine renderCoroutineRef; 33 34 public static AllocsFixes.FileCache.MapTileCache GetTileCache() { 56 public static MapTileCache GetTileCache () { 35 57 return Instance.cache; 36 58 } 37 59 38 private MapRendering () 39 { 40 Constants.MAP_DIRECTORY = GameUtils.GetSaveGameDir () + "/map"; 41 42 lock (lockObject) { 43 if (!LoadMapInfo ()) 44 WriteMapInfo (); 45 } 46 47 cache.SetZoomCount (Constants.ZOOMLEVELS); 48 49 zoomLevelBuffers = new MapRenderBlockBuffer[Constants.ZOOMLEVELS]; 50 for (int i = 0; i < Constants.ZOOMLEVELS; i++) { 51 zoomLevelBuffers [i] = new MapRenderBlockBuffer (i, cache); 52 } 53 54 renderCoroutineRef = ThreadManager.StartCoroutine (renderCoroutine ()); 55 } 56 57 public static void Shutdown () 58 { 60 public static void Shutdown () { 59 61 if (Instance.renderCoroutineRef != null) { 60 62 ThreadManager.StopCoroutine (Instance.renderCoroutineRef); … … 63 65 } 64 66 65 public static void RenderSingleChunk (Chunk chunk) 66 { 67 public static void RenderSingleChunk (Chunk chunk) { 67 68 if (renderingEnabled) { 68 ThreadPool.UnsafeQueueUserWorkItem ((o) => 69 { 69 ThreadPool.UnsafeQueueUserWorkItem (o => { 70 70 try { 71 71 if (!Instance.renderingFullMap) { 72 72 lock (lockObject) { 73 Chunk c = (Chunk) o;73 Chunk c = (Chunk) o; 74 74 Vector3i cPos = c.GetWorldPos (); 75 Vector2i cPos2 = new Vector2i (cPos.x / Constants.MAP_CHUNK_SIZE, cPos.z / Constants.MAP_CHUNK_SIZE); 75 Vector2i cPos2 = new Vector2i (cPos.x / Constants.MAP_CHUNK_SIZE, 76 cPos.z / Constants.MAP_CHUNK_SIZE); 76 77 77 78 ushort[] mapColors = c.GetMapColors (); 78 79 if (mapColors != null) { 79 Color32[] realColors = new Color32[Constants.MAP_CHUNK_SIZE * Constants.MAP_CHUNK_SIZE]; 80 Color32[] realColors = 81 new Color32[Constants.MAP_CHUNK_SIZE * Constants.MAP_CHUNK_SIZE]; 80 82 for (int i_colors = 0; i_colors < mapColors.Length; i_colors++) { 81 83 realColors [i_colors] = shortColorToColor32 (mapColors [i_colors]); 82 84 } 85 83 86 Instance.dirtyChunks [cPos2] = realColors; 87 84 88 //Log.Out ("Add Dirty: " + cPos2); 85 89 } … … 93 97 } 94 98 95 public void RenderFullMap () 96 { 99 public void RenderFullMap () { 97 100 MicroStopwatch microStopwatch = new MicroStopwatch (); 98 101 … … 101 104 Texture2D fullMapTexture = null; 102 105 103 Vector2i minChunk = default (Vector2i), maxChunk = default(Vector2i);104 Vector2i minPos = default (Vector2i), maxPos = default(Vector2i);106 Vector2i minChunk = default (Vector2i), maxChunk = default (Vector2i); 107 Vector2i minPos = default (Vector2i), maxPos = default (Vector2i); 105 108 int widthChunks, heightChunks, widthPix, heightPix; 106 getWorldExtent (rfm, out minChunk, out maxChunk, out minPos, out maxPos, out widthChunks, out heightChunks, out widthPix, out heightPix); 107 108 Log.Out (String.Format ("RenderMap: min: {0}, max: {1}, minPos: {2}, maxPos: {3}, w/h: {4}/{5}, wP/hP: {6}/{7}", 109 minChunk.ToString (), maxChunk.ToString (), 110 minPos.ToString (), maxPos.ToString (), 111 widthChunks, heightChunks, 112 widthPix, heightPix) 109 getWorldExtent (rfm, out minChunk, out maxChunk, out minPos, out maxPos, out widthChunks, out heightChunks, 110 out widthPix, out heightPix); 111 112 Log.Out (string.Format ( 113 "RenderMap: min: {0}, max: {1}, minPos: {2}, maxPos: {3}, w/h: {4}/{5}, wP/hP: {6}/{7}", 114 minChunk.ToString (), maxChunk.ToString (), 115 minPos.ToString (), maxPos.ToString (), 116 widthChunks, heightChunks, 117 widthPix, heightPix) 113 118 ); 114 119 … … 121 126 Directory.Delete (Constants.MAP_DIRECTORY, true); 122 127 } 128 123 129 WriteMapInfo (); 124 130 125 131 renderingFullMap = true; 126 132 127 if (widthPix <= 8192 && heightPix <= 8192) 133 if (widthPix <= 8192 && heightPix <= 8192) { 128 134 fullMapTexture = new Texture2D (widthPix, heightPix); 129 130 Vector2i curFullMapPos = default(Vector2i); 131 Vector2i curChunkPos = default(Vector2i); 135 } 136 137 Vector2i curFullMapPos = default (Vector2i); 138 Vector2i curChunkPos = default (Vector2i); 132 139 for (curFullMapPos.x = 0; curFullMapPos.x < widthPix; curFullMapPos.x += Constants.MAP_CHUNK_SIZE) { 133 for (curFullMapPos.y = 0; curFullMapPos.y < heightPix; curFullMapPos.y += Constants.MAP_CHUNK_SIZE) { 134 curChunkPos.x = (curFullMapPos.x / Constants.MAP_CHUNK_SIZE) + minChunk.x; 135 curChunkPos.y = (curFullMapPos.y / Constants.MAP_CHUNK_SIZE) + minChunk.y; 140 for (curFullMapPos.y = 0; 141 curFullMapPos.y < heightPix; 142 curFullMapPos.y += Constants.MAP_CHUNK_SIZE) { 143 curChunkPos.x = curFullMapPos.x / Constants.MAP_CHUNK_SIZE + minChunk.x; 144 curChunkPos.y = curFullMapPos.y / Constants.MAP_CHUNK_SIZE + minChunk.y; 136 145 137 146 try { … … 141 150 ushort[] mapColors = c.GetMapColors (); 142 151 if (mapColors != null) { 143 Color32[] realColors = new Color32[Constants.MAP_CHUNK_SIZE * Constants.MAP_CHUNK_SIZE]; 152 Color32[] realColors = 153 new Color32[Constants.MAP_CHUNK_SIZE * Constants.MAP_CHUNK_SIZE]; 144 154 for (int i_colors = 0; i_colors < mapColors.Length; i_colors++) { 145 155 realColors [i_colors] = shortColorToColor32 (mapColors [i_colors]); 146 156 } 157 147 158 dirtyChunks [curChunkPos] = realColors; 148 if (fullMapTexture != null) 149 fullMapTexture.SetPixels32 (curFullMapPos.x, curFullMapPos.y, Constants.MAP_CHUNK_SIZE, Constants.MAP_CHUNK_SIZE, realColors); 159 if (fullMapTexture != null) { 160 fullMapTexture.SetPixels32 (curFullMapPos.x, curFullMapPos.y, 161 Constants.MAP_CHUNK_SIZE, Constants.MAP_CHUNK_SIZE, realColors); 162 } 150 163 } 151 164 } … … 159 172 } 160 173 161 Log.Out (String.Format ("RenderMap: {0}/{1} ({2}%)", curFullMapPos.x, widthPix, (int)((float)curFullMapPos.x / widthPix * 100))); 174 Log.Out (string.Format ("RenderMap: {0}/{1} ({2}%)", curFullMapPos.x, widthPix, 175 (int) ((float) curFullMapPos.x / widthPix * 100))); 162 176 } 163 177 } … … 166 180 byte[] array = fullMapTexture.EncodeToPNG (); 167 181 File.WriteAllBytes (Constants.MAP_DIRECTORY + "/map.png", array); 168 UnityEngine.Object.Destroy (fullMapTexture);182 Object.Destroy (fullMapTexture); 169 183 fullMapTexture = null; 170 184 } … … 176 190 } 177 191 178 private void SaveAllBlockMaps (object source, System.Timers.ElapsedEventArgs e) 179 { 192 private void SaveAllBlockMaps (object source, ElapsedEventArgs e) { 180 193 for (int i = 0; i < Constants.ZOOMLEVELS; i++) { 181 194 zoomLevelBuffers [i].SaveBlock (); … … 183 196 } 184 197 185 private System.Collections.IEnumerator renderCoroutine () {198 private IEnumerator renderCoroutine () { 186 199 while (true) { 187 200 lock (lockObject) { … … 189 202 renderTimeout = Time.time + 0.5f; 190 203 } 204 191 205 if (Time.time > renderTimeout || dirtyChunks.Count > 200) { 192 206 RenderDirtyChunks (); 193 207 } 194 208 } 209 195 210 yield return new WaitForSeconds (0.2f); 196 211 } 197 212 } 198 213 199 private void RenderDirtyChunks () 200 { 214 private void RenderDirtyChunks () { 201 215 msw.ResetAndRestart (); 202 216 … … 210 224 //Log.Out ("Start Dirty: " + chunkPos); 211 225 212 Vector2i block = default(Vector2i), blockOffset = default(Vector2i); 213 getBlockNumber (chunkPos, out block, out blockOffset, Constants.MAP_BLOCK_TO_CHUNK_DIV, Constants.MAP_CHUNK_SIZE); 226 Vector2i block = default (Vector2i), blockOffset = default (Vector2i); 227 getBlockNumber (chunkPos, out block, out blockOffset, Constants.MAP_BLOCK_TO_CHUNK_DIV, 228 Constants.MAP_CHUNK_SIZE); 214 229 215 230 zoomLevelBuffers [Constants.ZOOMLEVELS - 1].LoadBlock (block); 216 231 217 Vector2i v_block = default (Vector2i), v_blockOffset = default(Vector2i);232 Vector2i v_block = default (Vector2i), v_blockOffset = default (Vector2i); 218 233 foreach (Vector2i v in keys) { 219 getBlockNumber (v, out v_block, out v_blockOffset, Constants.MAP_BLOCK_TO_CHUNK_DIV, Constants.MAP_CHUNK_SIZE); 234 getBlockNumber (v, out v_block, out v_blockOffset, Constants.MAP_BLOCK_TO_CHUNK_DIV, 235 Constants.MAP_CHUNK_SIZE); 220 236 if (v_block.Equals (block)) { 221 237 //Log.Out ("Dirty: " + v + " render: true"); 222 238 chunksDone.Add (v); 223 239 if (dirtyChunks [v].Length != Constants.MAP_CHUNK_SIZE * Constants.MAP_CHUNK_SIZE) { 224 Log.Error (string.Format ("Rendering chunk has incorrect data size of {0} instead of {1}", dirtyChunks [v].Length, Constants.MAP_CHUNK_SIZE * Constants.MAP_CHUNK_SIZE)); 225 } 226 zoomLevelBuffers [Constants.ZOOMLEVELS - 1].SetPart (v_blockOffset, Constants.MAP_CHUNK_SIZE, dirtyChunks [v]); 227 } else { 228 //Log.Out ("Dirty: " + v + " render: false"); 229 } 230 } 231 232 foreach (Vector2i v in chunksDone) 240 Log.Error (string.Format ("Rendering chunk has incorrect data size of {0} instead of {1}", 241 dirtyChunks [v].Length, Constants.MAP_CHUNK_SIZE * Constants.MAP_CHUNK_SIZE)); 242 } 243 244 zoomLevelBuffers [Constants.ZOOMLEVELS - 1] 245 .SetPart (v_blockOffset, Constants.MAP_CHUNK_SIZE, dirtyChunks [v]); 246 } 247 } 248 249 foreach (Vector2i v in chunksDone) { 233 250 dirtyChunks.Remove (v); 251 } 234 252 235 253 RenderZoomLevel (Constants.ZOOMLEVELS - 1, block); … … 239 257 } 240 258 241 private void RenderZoomLevel (int level, Vector2i innerBlock) 242 { 259 private void RenderZoomLevel (int level, Vector2i innerBlock) { 243 260 if (level > 0) { 244 Vector2i block = default (Vector2i), blockOffset = default(Vector2i);261 Vector2i block = default (Vector2i), blockOffset = default (Vector2i); 245 262 getBlockNumber (innerBlock, out block, out blockOffset, 2, Constants.MAP_BLOCK_SIZE / 2); 246 263 247 264 zoomLevelBuffers [level - 1].LoadBlock (block); 248 zoomLevelBuffers [level - 1].SetPart (blockOffset, Constants.MAP_BLOCK_SIZE / 2, zoomLevelBuffers [level].GetHalfScaled ()); 265 zoomLevelBuffers [level - 1].SetPart (blockOffset, Constants.MAP_BLOCK_SIZE / 2, 266 zoomLevelBuffers [level].GetHalfScaled ()); 249 267 250 268 RenderZoomLevel (level - 1, block); … … 252 270 } 253 271 254 private void getBlockNumber (Vector2i innerPos, out Vector2i block, out Vector2i blockOffset, int scaleFactor, int offsetSize) 255 { 256 block = default(Vector2i); 257 blockOffset = default(Vector2i); 258 block.x = ((innerPos.x + 16777216) / scaleFactor) - (16777216 / scaleFactor); 259 block.y = ((innerPos.y + 16777216) / scaleFactor) - (16777216 / scaleFactor); 260 blockOffset.x = ((innerPos.x + 16777216) % scaleFactor) * offsetSize; 261 blockOffset.y = ((innerPos.y + 16777216) % scaleFactor) * offsetSize; 262 } 263 264 private void WriteMapInfo () 265 { 272 private void getBlockNumber (Vector2i innerPos, out Vector2i block, out Vector2i blockOffset, int scaleFactor, 273 int offsetSize) { 274 block = default (Vector2i); 275 blockOffset = default (Vector2i); 276 block.x = (innerPos.x + 16777216) / scaleFactor - 16777216 / scaleFactor; 277 block.y = (innerPos.y + 16777216) / scaleFactor - 16777216 / scaleFactor; 278 blockOffset.x = (innerPos.x + 16777216) % scaleFactor * offsetSize; 279 blockOffset.y = (innerPos.y + 16777216) % scaleFactor * offsetSize; 280 } 281 282 private void WriteMapInfo () { 266 283 JSONObject mapInfo = new JSONObject (); 267 284 mapInfo.Add ("blockSize", new JSONNumber (Constants.MAP_BLOCK_SIZE)); … … 272 289 } 273 290 274 private bool LoadMapInfo () 275 { 291 private bool LoadMapInfo () { 276 292 if (File.Exists (Constants.MAP_DIRECTORY + "/mapinfo.json")) { 277 293 string json = File.ReadAllText (Constants.MAP_DIRECTORY + "/mapinfo.json", Encoding.UTF8); … … 279 295 JSONNode node = Parser.Parse (json); 280 296 if (node is JSONObject) { 281 JSONObject jo = (JSONObject)node; 282 if (jo.ContainsKey ("blockSize")) 283 Constants.MAP_BLOCK_SIZE = ((JSONNumber)jo ["blockSize"]).GetInt (); 284 if (jo.ContainsKey ("maxZoom")) 285 Constants.ZOOMLEVELS = ((JSONNumber)jo ["maxZoom"]).GetInt () + 1; 297 JSONObject jo = (JSONObject) node; 298 if (jo.ContainsKey ("blockSize")) { 299 Constants.MAP_BLOCK_SIZE = ((JSONNumber) jo ["blockSize"]).GetInt (); 300 } 301 302 if (jo.ContainsKey ("maxZoom")) { 303 Constants.ZOOMLEVELS = ((JSONNumber) jo ["maxZoom"]).GetInt () + 1; 304 } 305 286 306 return true; 287 307 } … … 292 312 } 293 313 } 314 294 315 return false; 295 316 } 296 317 297 318 private void getWorldExtent (RegionFileManager rfm, out Vector2i minChunk, out Vector2i maxChunk, 298 out Vector2i minPos, out Vector2i maxPos, 299 out int widthChunks, out int heightChunks, 300 out int widthPix, out int heightPix) 301 { 302 minChunk = default(Vector2i); 303 maxChunk = default(Vector2i); 304 minPos = default(Vector2i); 305 maxPos = default(Vector2i); 319 out Vector2i minPos, out Vector2i maxPos, 320 out int widthChunks, out int heightChunks, 321 out int widthPix, out int heightPix) { 322 minChunk = default (Vector2i); 323 maxChunk = default (Vector2i); 324 minPos = default (Vector2i); 325 maxPos = default (Vector2i); 306 326 307 327 long[] keys = rfm.GetAllChunkKeys (); 308 int minX = Int32.MaxValue;309 int minY = Int32.MaxValue;310 int maxX = Int32.MinValue;311 int maxY = Int32.MinValue;328 int minX = int.MaxValue; 329 int minY = int.MaxValue; 330 int maxX = int.MinValue; 331 int maxY = int.MinValue; 312 332 foreach (long key in keys) { 313 333 int x = WorldChunkCache.extractX (key); 314 334 int y = WorldChunkCache.extractZ (key); 315 335 316 if (x < minX) 336 if (x < minX) { 317 337 minX = x; 318 if (x > maxX) 338 } 339 340 if (x > maxX) { 319 341 maxX = x; 320 if (y < minY) 342 } 343 344 if (y < minY) { 321 345 minY = y; 322 if (y > maxY) 346 } 347 348 if (y > maxY) { 323 349 maxY = y; 350 } 324 351 } 325 352 … … 343 370 } 344 371 345 private static Color shortColorToColor (ushort col) 346 { 347 return new Color (((float)(col >> 10 & 31) / 31f), ((float)(col >> 5 & 31) / 31f), ((float)(col & 31) / 31f), 255); 348 } 349 350 private static Color32 shortColorToColor32 (ushort col) 351 { 352 byte r = (byte)(256 * (col >> 10 & 31) / 32); 353 byte g = (byte)(256 * (col >> 5 & 31) / 32); 354 byte b = (byte)(256 * (col & 31) / 32); 372 private static Color shortColorToColor (ushort col) { 373 return new Color (((col >> 10) & 31) / 31f, ((col >> 5) & 31) / 31f, (col & 31) / 31f, 255); 374 } 375 376 private static Color32 shortColorToColor32 (ushort col) { 377 byte r = (byte) (256 * ((col >> 10) & 31) / 32); 378 byte g = (byte) (256 * ((col >> 5) & 31) / 32); 379 byte b = (byte) (256 * (col & 31) / 32); 355 380 byte a = 255; 356 381 return new Color32 (r, g, b, a); -
binary-improvements/MapRendering/Web/API/ExecuteConsoleCommand.cs
r306 r325 1 using AllocsFixes.JSON;2 using AllocsFixes.PersistentData;3 1 using System; 4 using System.Collections.Generic;5 2 using System.Net; 6 3 7 namespace AllocsFixes.NetConnections.Servers.Web.API 8 { 9 public class ExecuteConsoleCommand : WebAPI 10 { 11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) { 4 namespace AllocsFixes.NetConnections.Servers.Web.API { 5 public class ExecuteConsoleCommand : WebAPI { 6 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 7 int permissionLevel) { 12 8 if (string.IsNullOrEmpty (req.QueryString ["command"])) { 13 resp.StatusCode = (int) HttpStatusCode.BadRequest;9 resp.StatusCode = (int) HttpStatusCode.BadRequest; 14 10 Web.SetResponseTextContent (resp, "No command given"); 15 11 return; … … 17 13 18 14 WebCommandResult.ResultType responseType = 19 req.QueryString ["raw"] != null ? WebCommandResult.ResultType.Raw : 20 (req.QueryString ["simple"] != null ? WebCommandResult.ResultType.ResultOnly : 21 WebCommandResult.ResultType.Full); 15 req.QueryString ["raw"] != null 16 ? WebCommandResult.ResultType.Raw 17 : (req.QueryString ["simple"] != null 18 ? WebCommandResult.ResultType.ResultOnly 19 : WebCommandResult.ResultType.Full); 22 20 23 21 string commandline = req.QueryString ["command"]; … … 28 26 29 27 if (command == null) { 30 resp.StatusCode = (int) HttpStatusCode.NotImplemented;28 resp.StatusCode = (int) HttpStatusCode.NotImplemented; 31 29 Web.SetResponseTextContent (resp, "Unknown command"); 32 30 return; 33 31 } 34 32 35 AdminToolsCommandPermissions atcp = GameManager.Instance.adminTools.GetAdminToolsCommandPermission (command.GetCommands ()); 33 AdminToolsCommandPermissions atcp = 34 GameManager.Instance.adminTools.GetAdminToolsCommandPermission (command.GetCommands ()); 36 35 37 36 if (permissionLevel > atcp.PermissionLevel) { 38 resp.StatusCode = (int) HttpStatusCode.Forbidden;37 resp.StatusCode = (int) HttpStatusCode.Forbidden; 39 38 Web.SetResponseTextContent (resp, "You are not allowed to execute this command"); 40 39 return; … … 51 50 } 52 51 } 53 -
binary-improvements/MapRendering/Web/API/GetAllowedCommands.cs
r279 r325 1 using System.Net; 1 2 using AllocsFixes.JSON; 2 using AllocsFixes.PersistentData;3 using System;4 using System.Collections.Generic;5 using System.Net;6 3 7 namespace AllocsFixes.NetConnections.Servers.Web.API 8 { 4 namespace AllocsFixes.NetConnections.Servers.Web.API { 9 5 public class GetAllowedCommands : WebAPI { 10 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) { 6 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 7 int permissionLevel) { 11 8 JSONObject result = new JSONObject (); 12 9 JSONArray entries = new JSONArray (); 13 10 foreach (IConsoleCommand cc in SdtdConsole.Instance.GetCommands ()) { 14 AdminToolsCommandPermissions atcp = GameManager.Instance.adminTools.GetAdminToolsCommandPermission (cc.GetCommands ()); 11 AdminToolsCommandPermissions atcp = 12 GameManager.Instance.adminTools.GetAdminToolsCommandPermission (cc.GetCommands ()); 15 13 if (permissionLevel <= atcp.PermissionLevel) { 16 14 string cmd = string.Empty; … … 20 18 } 21 19 } 20 22 21 JSONObject cmdObj = new JSONObject (); 23 22 cmdObj.Add ("command", new JSONString (cmd)); … … 38 37 } 39 38 } 40 -
binary-improvements/MapRendering/Web/API/GetAnimalsLocation.cs
r313 r325 1 using AllocsFixes.JSON; 1 using System.Collections.Generic; 2 using System.Net; 3 using AllocsFixes.JSON; 2 4 using AllocsFixes.LiveData; 3 using System;4 using System.Collections.Generic;5 using System.Net;6 5 7 namespace AllocsFixes.NetConnections.Servers.Web.API 8 { 9 class GetAnimalsLocation : WebAPI 10 { 11 private List<EntityAnimal> animals = new List<EntityAnimal> (); 6 namespace AllocsFixes.NetConnections.Servers.Web.API { 7 internal class GetAnimalsLocation : WebAPI { 8 private readonly List<EntityAnimal> animals = new List<EntityAnimal> (); 12 9 13 public override void HandleRequest(HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) 14 15 JSONArray animalsJsResult = new JSONArray();10 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 11 int permissionLevel) { 12 JSONArray animalsJsResult = new JSONArray (); 16 13 17 14 Animals.Instance.Get (animals); 18 for (int i = 0; i < animals.Count; i++) 19 { 15 for (int i = 0; i < animals.Count; i++) { 20 16 EntityAnimal entity = animals [i]; 21 Vector3i position = new Vector3i(entity.GetPosition());17 Vector3i position = new Vector3i (entity.GetPosition ()); 22 18 23 JSONObject jsonPOS = new JSONObject();24 jsonPOS.Add("x", new JSONNumber(position.x));25 jsonPOS.Add("y", new JSONNumber(position.y));26 jsonPOS.Add("z", new JSONNumber(position.z));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)); 27 23 28 JSONObject pJson = new JSONObject();29 pJson.Add("id", new JSONNumber(entity.entityId));24 JSONObject pJson = new JSONObject (); 25 pJson.Add ("id", new JSONNumber (entity.entityId)); 30 26 31 if (!string.IsNullOrEmpty(entity.EntityName)) 32 pJson.Add("name", new JSONString(entity.EntityName)); 33 else 34 pJson.Add("name", new JSONString("animal class #" + entity.entityClass.ToString())); 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 } 35 32 36 pJson.Add("position", jsonPOS);33 pJson.Add ("position", jsonPOS); 37 34 38 animalsJsResult.Add(pJson);39 40 41 WriteJSON(resp, animalsJsResult);42 43 35 animalsJsResult.Add (pJson); 36 } 37 38 WriteJSON (resp, animalsJsResult); 39 } 40 } 44 41 } -
binary-improvements/MapRendering/Web/API/GetHostileLocation.cs
r313 r325 1 using AllocsFixes.JSON; 1 using System.Collections.Generic; 2 using System.Net; 3 using AllocsFixes.JSON; 2 4 using AllocsFixes.LiveData; 3 using System;4 using System.Collections.Generic;5 using System.Net;6 5 7 namespace AllocsFixes.NetConnections.Servers.Web.API 8 { 9 class GetHostileLocation : WebAPI 10 { 11 private List<EntityEnemy> enemies = new List<EntityEnemy> (); 6 namespace AllocsFixes.NetConnections.Servers.Web.API { 7 internal class GetHostileLocation : WebAPI { 8 private readonly List<EntityEnemy> enemies = new List<EntityEnemy> (); 12 9 13 public override void HandleRequest(HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) 14 15 JSONArray hostilesJsResult = new JSONArray();10 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 11 int permissionLevel) { 12 JSONArray hostilesJsResult = new JSONArray (); 16 13 17 14 Hostiles.Instance.Get (enemies); 18 for (int i = 0; i < enemies.Count; i++) 19 { 15 for (int i = 0; i < enemies.Count; i++) { 20 16 EntityEnemy entity = enemies [i]; 21 Vector3i position = new Vector3i(entity.GetPosition());17 Vector3i position = new Vector3i (entity.GetPosition ()); 22 18 23 JSONObject jsonPOS = new JSONObject();24 jsonPOS.Add("x", new JSONNumber(position.x));25 jsonPOS.Add("y", new JSONNumber(position.y));26 jsonPOS.Add("z", new JSONNumber(position.z));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)); 27 23 28 JSONObject pJson = new JSONObject();29 pJson.Add("id", new JSONNumber(entity.entityId));24 JSONObject pJson = new JSONObject (); 25 pJson.Add ("id", new JSONNumber (entity.entityId)); 30 26 31 if (!string.IsNullOrEmpty(entity.EntityName)) 32 pJson.Add("name", new JSONString(entity.EntityName)); 33 else 34 pJson.Add("name", new JSONString("enemy class #" + entity.entityClass.ToString())); 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 } 35 32 36 pJson.Add("position", jsonPOS);33 pJson.Add ("position", jsonPOS); 37 34 38 hostilesJsResult.Add(pJson);39 35 hostilesJsResult.Add (pJson); 36 } 40 37 41 WriteJSON(resp, hostilesJsResult);42 43 38 WriteJSON (resp, hostilesJsResult); 39 } 40 } 44 41 } -
binary-improvements/MapRendering/Web/API/GetLandClaims.cs
r253 r325 1 using System.Collections.Generic; 2 using System.Net; 1 3 using AllocsFixes.JSON; 2 4 using AllocsFixes.PersistentData; 3 using System;4 using System.Collections.Generic;5 using System.Net;6 5 7 namespace AllocsFixes.NetConnections.Servers.Web.API 8 { 6 namespace AllocsFixes.NetConnections.Servers.Web.API { 9 7 public class GetLandClaims : WebAPI { 10 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) { 8 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 9 int permissionLevel) { 11 10 string requestedSteamID = string.Empty; 12 11 … … 15 14 requestedSteamID = req.QueryString ["steamid"]; 16 15 if (requestedSteamID.Length != 17 || !ulong.TryParse (requestedSteamID, out lViewersSteamID)) { 17 resp.StatusCode = (int) HttpStatusCode.BadRequest;16 resp.StatusCode = (int) HttpStatusCode.BadRequest; 18 17 Web.SetResponseTextContent (resp, "Invalid SteamID given"); 19 18 return; … … 25 24 26 25 bool bViewAll = WebConnection.CanViewAllClaims (permissionLevel); 27 26 28 27 JSONObject result = new JSONObject (); 29 28 result.Add ("claimsize", new JSONNumber (GamePrefs.GetInt (EnumGamePrefs.LandClaimSize))); … … 35 34 if (!string.IsNullOrEmpty (requestedSteamID) || !bViewAll) { 36 35 if (!string.IsNullOrEmpty (requestedSteamID) && !bViewAll) { 37 ownerFilters = new LandClaimList.OwnerFilter[] {36 ownerFilters = new[] { 38 37 LandClaimList.SteamIdFilter (user.SteamID.ToString ()), 39 38 LandClaimList.SteamIdFilter (requestedSteamID) 40 39 }; 41 40 } else if (!bViewAll) { 42 ownerFilters = new LandClaimList.OwnerFilter[] { LandClaimList.SteamIdFilter (user.SteamID.ToString ())};41 ownerFilters = new[] {LandClaimList.SteamIdFilter (user.SteamID.ToString ())}; 43 42 } else { 44 ownerFilters = new LandClaimList.OwnerFilter[] { LandClaimList.SteamIdFilter (requestedSteamID)};43 ownerFilters = new[] {LandClaimList.SteamIdFilter (requestedSteamID)}; 45 44 } 46 45 } 46 47 47 LandClaimList.PositionFilter[] posFilters = null; 48 48 49 Dictionary<P ersistentData.Player, List<Vector3i>> claims = LandClaimList.GetLandClaims (ownerFilters, posFilters);49 Dictionary<Player, List<Vector3i>> claims = LandClaimList.GetLandClaims (ownerFilters, posFilters); 50 50 51 foreach (KeyValuePair<PersistentData.Player, List<Vector3i>> kvp in claims) { 52 51 foreach (KeyValuePair<Player, List<Vector3i>> kvp in claims) { 53 52 try { 54 53 JSONObject owner = new JSONObject (); … … 83 82 } 84 83 } 85 -
binary-improvements/MapRendering/Web/API/GetLog.cs
r253 r325 1 using AllocsFixes.JSON;2 using AllocsFixes.PersistentData;3 using System;4 1 using System.Collections.Generic; 5 2 using System.Net; 3 using AllocsFixes.JSON; 6 4 7 namespace AllocsFixes.NetConnections.Servers.Web.API 8 { 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 9 6 public class GetLog : WebAPI { 10 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) { 7 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 8 int permissionLevel) { 11 9 int firstLine, lastLine; 12 10 … … 39 37 } 40 38 } 41 -
binary-improvements/MapRendering/Web/API/GetPlayerInventories.cs
r321 r325 1 using System.Net; 1 2 using AllocsFixes.JSON; 2 3 using AllocsFixes.PersistentData; 3 using System;4 using System.Collections.Generic;5 using System.Net;6 4 7 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 8 6 public class GetPlayerInventories : WebAPI { 7 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 8 int permissionLevel) { 9 JSONArray AllInventoriesResult = new JSONArray (); 9 10 10 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) {11 JSONArray AllInventoriesResult = new JSONArray ();12 13 11 foreach (string sid in PersistentContainer.Instance.Players.SteamIDs) { 14 12 Player p = PersistentContainer.Instance.Players [sid, false]; … … 55 53 WriteJSON (resp, AllInventoriesResult); 56 54 } 57 58 55 } 59 56 } 60 -
binary-improvements/MapRendering/Web/API/GetPlayerInventory.cs
r321 r325 1 using System.Collections.Generic; 2 using System.Net; 1 3 using AllocsFixes.JSON; 2 4 using AllocsFixes.PersistentData; 3 using System;4 using System.Collections.Generic;5 using System.Net;6 5 7 namespace AllocsFixes.NetConnections.Servers.Web.API 8 { 6 namespace AllocsFixes.NetConnections.Servers.Web.API { 9 7 public class GetPlayerInventory : WebAPI { 10 11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user,int permissionLevel) {8 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 9 int permissionLevel) { 12 10 if (req.QueryString ["steamid"] == null) { 13 resp.StatusCode = (int) HttpStatusCode.InternalServerError;11 resp.StatusCode = (int) HttpStatusCode.InternalServerError; 14 12 Web.SetResponseTextContent (resp, "No SteamID given"); 15 13 return; … … 18 16 Player p = PersistentContainer.Instance.Players [req.QueryString ["steamid"], false]; 19 17 if (p == null) { 20 resp.StatusCode = (int) HttpStatusCode.InternalServerError;18 resp.StatusCode = (int) HttpStatusCode.InternalServerError; 21 19 Web.SetResponseTextContent (resp, "Invalid or unknown SteamID given"); 22 20 return; … … 87 85 jsonItem.Add ("qualitycolor", new JSONString (QualityInfo.GetQualityColorHex (_item.quality))); 88 86 } 87 89 88 return jsonItem; 90 } else {91 return new JSONNull ();92 89 } 90 91 return new JSONNull (); 93 92 } 94 95 93 } 96 94 } 97 -
binary-improvements/MapRendering/Web/API/GetPlayerList.cs
r324 r325 1 using AllocsFixes.JSON;2 using AllocsFixes.PersistentData;3 1 using System; 4 2 using System.Collections.Generic; … … 6 4 using System.Net; 7 5 using System.Text.RegularExpressions; 8 9 namespace AllocsFixes.NetConnections.Servers.Web.API 10 { 11 public class GetPlayerList : WebAPI 12 { 13 private static Regex numberFilterMatcher = new Regex (@"^(>=|=>|>|<=|=<|<|==|=)?\s*([0-9]+(\.[0-9]*)?)$"); 14 private enum NumberMatchType { 15 Equal, 16 Greater, 17 GreaterEqual, 18 Lesser, 19 LesserEqual 20 } 21 22 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) 23 { 24 AdminTools admTools = GameManager.Instance.adminTools; 25 user = user ?? new WebConnection ("", "", 0L); 26 27 bool bViewAll = WebConnection.CanViewAllPlayers (permissionLevel); 6 using AllocsFixes.JSON; 7 using AllocsFixes.PersistentData; 8 9 namespace AllocsFixes.NetConnections.Servers.Web.API { 10 public class GetPlayerList : WebAPI { 11 private static readonly Regex numberFilterMatcher = 12 new Regex (@"^(>=|=>|>|<=|=<|<|==|=)?\s*([0-9]+(\.[0-9]*)?)$"); 13 14 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 15 int permissionLevel) { 16 AdminTools admTools = GameManager.Instance.adminTools; 17 user = user ?? new WebConnection ("", "", 0L); 18 19 bool bViewAll = WebConnection.CanViewAllPlayers (permissionLevel); 28 20 29 21 // TODO: Sort (and filter?) prior to converting to JSON ... hard as how to get the correct column's data? (i.e. column name matches JSON object field names, not source data) … … 46 38 47 39 foreach (string sid in playersList.SteamIDs) { 48 Player p = playersList [sid, false]; 49 50 ulong player_steam_ID = 0L; 51 if (!ulong.TryParse (sid, out player_steam_ID)) 52 player_steam_ID = 0L; 53 54 if ((player_steam_ID == user.SteamID) || bViewAll) { 55 JSONObject pos = new JSONObject (); 56 pos.Add("x", new JSONNumber (p.LastPosition.x)); 57 pos.Add("y", new JSONNumber (p.LastPosition.y)); 58 pos.Add("z", new JSONNumber (p.LastPosition.z)); 59 60 JSONObject pJson = new JSONObject (); 61 pJson.Add("steamid", new JSONString (sid)); 62 pJson.Add("entityid", new JSONNumber (p.EntityID)); 63 pJson.Add("ip", new JSONString (p.IP)); 64 pJson.Add("name", new JSONString (p.Name)); 65 pJson.Add("online", new JSONBoolean (p.IsOnline)); 66 pJson.Add("position", pos); 40 Player p = playersList [sid, false]; 41 42 ulong player_steam_ID = 0L; 43 if (!ulong.TryParse (sid, out player_steam_ID)) { 44 player_steam_ID = 0L; 45 } 46 47 if (player_steam_ID == user.SteamID || bViewAll) { 48 JSONObject pos = new JSONObject (); 49 pos.Add ("x", new JSONNumber (p.LastPosition.x)); 50 pos.Add ("y", new JSONNumber (p.LastPosition.y)); 51 pos.Add ("z", new JSONNumber (p.LastPosition.z)); 52 53 JSONObject pJson = new JSONObject (); 54 pJson.Add ("steamid", new JSONString (sid)); 55 pJson.Add ("entityid", new JSONNumber (p.EntityID)); 56 pJson.Add ("ip", new JSONString (p.IP)); 57 pJson.Add ("name", new JSONString (p.Name)); 58 pJson.Add ("online", new JSONBoolean (p.IsOnline)); 59 pJson.Add ("position", pos); 67 60 68 61 pJson.Add ("totalplaytime", new JSONNumber (p.TotalPlayTime)); 69 pJson.Add ("lastonline", new JSONString (p.LastOnline.ToUniversalTime ().ToString ("yyyy-MM-ddTHH:mm:ssZ"))); 62 pJson.Add ("lastonline", 63 new JSONString (p.LastOnline.ToUniversalTime ().ToString ("yyyy-MM-ddTHH:mm:ssZ"))); 70 64 pJson.Add ("ping", new JSONNumber (p.IsOnline ? p.ClientInfo.ping : -1)); 71 65 … … 76 70 banned = new JSONBoolean (false); 77 71 } 72 78 73 pJson.Add ("banned", banned); 79 74 80 75 playerList.Add (pJson); 81 82 76 } 77 } 83 78 84 79 IEnumerable<JSONObject> list = playerList; … … 124 119 } 125 120 126 private IEnumerable<JSONObject> ExecuteFilter (IEnumerable<JSONObject> _list, string _filterCol, string _filterVal) { 121 private IEnumerable<JSONObject> ExecuteFilter (IEnumerable<JSONObject> _list, string _filterCol, 122 string _filterVal) { 127 123 if (_list.Count () == 0) { 128 124 return _list; … … 131 127 if (_list.First ().ContainsKey (_filterCol)) { 132 128 Type colType = _list.First () [_filterCol].GetType (); 133 if (colType == typeof (JSONNumber)) {129 if (colType == typeof (JSONNumber)) { 134 130 return ExecuteNumberFilter (_list, _filterCol, _filterVal); 135 } else if (colType == typeof(JSONBoolean)) { 131 } 132 133 if (colType == typeof (JSONBoolean)) { 136 134 bool value = _filterVal.Trim ().ToLower () == "true"; 137 135 return _list.Where (line => (line [_filterCol] as JSONBoolean).GetBool () == value); 138 } else if (colType == typeof(JSONString)) { 136 } 137 138 if (colType == typeof (JSONString)) { 139 139 // regex-match whole ^string$, replace * by .*, ? by .?, + by .+ 140 140 _filterVal = _filterVal.Replace ("*", ".*").Replace ("?", ".?").Replace ("+", ".+"); 141 141 _filterVal = "^" + _filterVal + "$"; 142 142 143 //Log.Out ("GetPlayerList: Filter on String with Regex '" + _filterVal + "'"); 143 144 Regex matcher = new Regex (_filterVal, RegexOptions.IgnoreCase); … … 145 146 } 146 147 } 148 147 149 return _list; 148 150 } 149 151 150 152 151 private IEnumerable<JSONObject> ExecuteNumberFilter (IEnumerable<JSONObject> _list, string _filterCol, string _filterVal) { 153 private IEnumerable<JSONObject> ExecuteNumberFilter (IEnumerable<JSONObject> _list, string _filterCol, 154 string _filterVal) { 152 155 // allow value (exact match), =, ==, >=, >, <=, < 153 156 Match filterMatch = numberFilterMatcher.Match (_filterVal); … … 157 160 double epsilon = value / 100000; 158 161 switch (filterMatch.Groups [1].Value) { 159 case "": 160 case "=": 161 case "==": 162 matchType = NumberMatchType.Equal; 163 break; 164 case ">": 165 matchType = NumberMatchType.Greater; 166 break; 167 case ">=": 168 case "=>": 169 matchType = NumberMatchType.GreaterEqual; 170 break; 171 case "<": 172 matchType = NumberMatchType.Lesser; 173 break; 174 case "<=": 175 case "=<": 176 matchType = NumberMatchType.LesserEqual; 177 break; 178 default: 179 matchType = NumberMatchType.Equal; 180 break; 181 } 182 return _list.Where (delegate(JSONObject line) { 162 case "": 163 case "=": 164 case "==": 165 matchType = NumberMatchType.Equal; 166 break; 167 case ">": 168 matchType = NumberMatchType.Greater; 169 break; 170 case ">=": 171 case "=>": 172 matchType = NumberMatchType.GreaterEqual; 173 break; 174 case "<": 175 matchType = NumberMatchType.Lesser; 176 break; 177 case "<=": 178 case "=<": 179 matchType = NumberMatchType.LesserEqual; 180 break; 181 default: 182 matchType = NumberMatchType.Equal; 183 break; 184 } 185 186 return _list.Where (delegate (JSONObject line) { 183 187 double objVal = (line [_filterCol] as JSONNumber).GetDouble (); 184 188 switch (matchType) { 185 case NumberMatchType.Greater:186 return objVal > value;187 case NumberMatchType.GreaterEqual:188 return objVal >= value;189 case NumberMatchType.Lesser:190 return objVal < value;191 case NumberMatchType.LesserEqual:192 return objVal <= value;193 case NumberMatchType.Equal:194 default:195 return NearlyEqual (objVal, value, epsilon);189 case NumberMatchType.Greater: 190 return objVal > value; 191 case NumberMatchType.GreaterEqual: 192 return objVal >= value; 193 case NumberMatchType.Lesser: 194 return objVal < value; 195 case NumberMatchType.LesserEqual: 196 return objVal <= value; 197 case NumberMatchType.Equal: 198 default: 199 return NearlyEqual (objVal, value, epsilon); 196 200 } 197 201 }); 198 } else {199 Log.Out ("GetPlayerList: ignoring invalid filter for number-column '{0}': '{1}'", _filterCol, _filterVal); 200 }202 } 203 204 Log.Out ("GetPlayerList: ignoring invalid filter for number-column '{0}': '{1}'", _filterCol, _filterVal); 201 205 return _list; 202 206 } … … 210 214 if (_list.First ().ContainsKey (_sortCol)) { 211 215 Type colType = _list.First () [_sortCol].GetType (); 212 if (colType == typeof (JSONNumber)) {216 if (colType == typeof (JSONNumber)) { 213 217 if (_ascending) { 214 218 return _list.OrderBy (line => (line [_sortCol] as JSONNumber).GetDouble ()); 215 } else { 216 return _list.OrderByDescending (line => (line [_sortCol] as JSONNumber).GetDouble ()); 217 } 218 } else if (colType == typeof(JSONBoolean)) { 219 } 220 221 return _list.OrderByDescending (line => (line [_sortCol] as JSONNumber).GetDouble ()); 222 } 223 224 if (colType == typeof (JSONBoolean)) { 219 225 if (_ascending) { 220 226 return _list.OrderBy (line => (line [_sortCol] as JSONBoolean).GetBool ()); 221 } else { 222 return _list.OrderByDescending (line => (line [_sortCol] as JSONBoolean).GetBool ()); 223 } 224 } else { 225 if (_ascending) { 226 return _list.OrderBy (line => line [_sortCol].ToString ()); 227 } else { 228 return _list.OrderByDescending (line => line [_sortCol].ToString ()); 229 } 230 } 231 } 227 } 228 229 return _list.OrderByDescending (line => (line [_sortCol] as JSONBoolean).GetBool ()); 230 } 231 232 if (_ascending) { 233 return _list.OrderBy (line => line [_sortCol].ToString ()); 234 } 235 236 return _list.OrderByDescending (line => line [_sortCol].ToString ()); 237 } 238 232 239 return _list; 233 240 } 234 241 235 242 236 private bool NearlyEqual(double a, double b, double epsilon) 237 { 238 double absA = Math.Abs(a); 239 double absB = Math.Abs(b); 240 double diff = Math.Abs(a - b); 241 242 if (a == b) 243 { // shortcut, handles infinities 243 private bool NearlyEqual (double a, double b, double epsilon) { 244 double absA = Math.Abs (a); 245 double absB = Math.Abs (b); 246 double diff = Math.Abs (a - b); 247 248 if (a == b) { 244 249 return true; 245 } 246 else if (a == 0 || b == 0 || diff < Double.Epsilon) 247 { 248 // a or b is zero or both are extremely close to it 249 // relative error is less meaningful here 250 } 251 252 if (a == 0 || b == 0 || diff < double.Epsilon) { 250 253 return diff < epsilon; 251 254 } 252 else 253 { // use relative error 254 return diff / (absA + absB) < epsilon; 255 } 256 } 257 255 256 return diff / (absA + absB) < epsilon; 257 } 258 259 private enum NumberMatchType { 260 Equal, 261 Greater, 262 GreaterEqual, 263 Lesser, 264 LesserEqual 265 } 258 266 } 259 267 } 260 -
binary-improvements/MapRendering/Web/API/GetPlayersLocation.cs
r315 r325 1 using System.Net; 1 2 using AllocsFixes.JSON; 2 3 using AllocsFixes.PersistentData; 3 using System;4 using System.Collections.Generic;5 using System.Net;6 4 7 namespace AllocsFixes.NetConnections.Servers.Web.API 8 { 9 public class GetPlayersLocation : WebAPI 10 { 11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) 12 { 13 AdminTools admTools = GameManager.Instance.adminTools; 14 user = user ?? new WebConnection ("", "", 0L); 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 6 public class GetPlayersLocation : WebAPI { 7 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 8 int permissionLevel) { 9 AdminTools admTools = GameManager.Instance.adminTools; 10 user = user ?? new WebConnection ("", "", 0L); 15 11 16 12 bool listOffline = false; … … 19 15 } 20 16 21 17 bool bViewAll = WebConnection.CanViewAllPlayers (permissionLevel); 22 18 23 19 JSONArray playersJsResult = new JSONArray (); 24 20 25 21 Players playersList = PersistentContainer.Instance.Players; 26 22 27 23 foreach (string sid in playersList.SteamIDs) { 28 if (admTools != null) 29 if (admTools.IsBanned (sid)) 30 continue; 24 if (admTools != null) { 25 if (admTools.IsBanned (sid)) { 26 continue; 27 } 28 } 31 29 32 30 Player p = playersList [sid, false]; 33 31 34 32 if (listOffline || p.IsOnline) { 35 ulong player_steam_ID = 0L; 36 if (!ulong.TryParse (sid, out player_steam_ID)) 37 player_steam_ID = 0L; 33 ulong player_steam_ID = 0L; 34 if (!ulong.TryParse (sid, out player_steam_ID)) { 35 player_steam_ID = 0L; 36 } 38 37 39 if ((player_steam_ID == user.SteamID)|| bViewAll) {40 41 pos.Add("x", new JSONNumber (p.LastPosition.x));42 pos.Add("y", new JSONNumber (p.LastPosition.y));43 pos.Add("z", new JSONNumber (p.LastPosition.z));38 if (player_steam_ID == user.SteamID || bViewAll) { 39 JSONObject pos = new JSONObject (); 40 pos.Add ("x", new JSONNumber (p.LastPosition.x)); 41 pos.Add ("y", new JSONNumber (p.LastPosition.y)); 42 pos.Add ("z", new JSONNumber (p.LastPosition.z)); 44 43 45 JSONObject pJson = new JSONObject (); 46 pJson.Add("steamid", new JSONString (sid)); 47 // pJson.Add("entityid", new JSONNumber (p.EntityID)); 48 // pJson.Add("ip", new JSONString (p.IP)); 49 pJson.Add("name", new JSONString (p.Name)); 50 pJson.Add("online", new JSONBoolean (p.IsOnline)); 51 pJson.Add("position", pos); 44 JSONObject pJson = new JSONObject (); 45 pJson.Add ("steamid", new JSONString (sid)); 52 46 53 // pJson.Add ("totalplaytime", new JSONNumber (p.TotalPlayTime)); 54 // pJson.Add ("lastonline", new JSONString (p.LastOnline.ToString ("s"))); 55 // pJson.Add ("ping", new JSONNumber (p.IsOnline ? p.ClientInfo.ping : -1)); 47 // pJson.Add("entityid", new JSONNumber (p.EntityID)); 48 // pJson.Add("ip", new JSONString (p.IP)); 49 pJson.Add ("name", new JSONString (p.Name)); 50 pJson.Add ("online", new JSONBoolean (p.IsOnline)); 51 pJson.Add ("position", pos); 52 53 // pJson.Add ("totalplaytime", new JSONNumber (p.TotalPlayTime)); 54 // pJson.Add ("lastonline", new JSONString (p.LastOnline.ToString ("s"))); 55 // pJson.Add ("ping", new JSONNumber (p.IsOnline ? p.ClientInfo.ping : -1)); 56 56 57 57 playersJsResult.Add (pJson); 58 58 } 59 59 } 60 60 } 61 61 62 62 WriteJSON (resp, playersJsResult); … … 64 64 } 65 65 } 66 -
binary-improvements/MapRendering/Web/API/GetPlayersOnline.cs
r324 r325 1 using System.Collections.Generic; 2 using System.Net; 1 3 using AllocsFixes.JSON; 2 4 using AllocsFixes.PersistentData; 3 using System;4 using System.Collections.Generic;5 using System.Net;6 5 7 namespace AllocsFixes.NetConnections.Servers.Web.API 8 { 9 public class GetPlayersOnline : WebAPI 10 { 11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) 12 { 13 JSONArray players = new JSONArray(); 6 namespace AllocsFixes.NetConnections.Servers.Web.API { 7 public class GetPlayersOnline : WebAPI { 8 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 9 int permissionLevel) { 10 JSONArray players = new JSONArray (); 14 11 15 12 World w = GameManager.Instance.World; … … 18 15 Player player = PersistentContainer.Instance.Players [ci.playerId, false]; 19 16 20 JSONObject pos = new JSONObject ();21 pos.Add ("x", new JSONNumber ((int) current.Value.GetPosition ().x));22 pos.Add ("y", new JSONNumber ((int) current.Value.GetPosition ().y));23 pos.Add ("z", new JSONNumber ((int) current.Value.GetPosition ().z));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)); 24 21 25 JSONObject p = new JSONObject ();22 JSONObject p = new JSONObject (); 26 23 p.Add ("steamid", new JSONString (ci.playerId)); 27 24 p.Add ("entityid", new JSONNumber (ci.entityId)); … … 46 43 p.Add ("ping", new JSONNumber (ci != null ? ci.ping : -1)); 47 44 48 players.Add (p);45 players.Add (p); 49 46 } 50 47 51 WriteJSON (resp, players);48 WriteJSON (resp, players); 52 49 } 53 50 } 54 51 } 55 -
binary-improvements/MapRendering/Web/API/GetServerInfo.cs
r279 r325 1 using System; 2 using System.Net; 1 3 using AllocsFixes.JSON; 2 using AllocsFixes.PersistentData;3 using System;4 using System.Collections.Generic;5 using System.Net;6 4 7 namespace AllocsFixes.NetConnections.Servers.Web.API 8 { 9 public class GetServerInfo : WebAPI 10 { 11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) 12 { 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 6 public class GetServerInfo : WebAPI { 7 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 8 int permissionLevel) { 13 9 JSONObject serverInfo = new JSONObject (); 14 10 15 11 GameServerInfo gsi = Steam.Masterserver.Server.LocalGameInfo; 16 12 17 foreach (string stringGamePref in Enum.GetNames (typeof(GameInfoString))) {18 string value = gsi.GetValue ( (GameInfoString)Enum.Parse (typeof(GameInfoString), stringGamePref));13 foreach (string stringGamePref in Enum.GetNames (typeof (GameInfoString))) { 14 string value = gsi.GetValue ((GameInfoString) Enum.Parse (typeof (GameInfoString), stringGamePref)); 19 15 20 16 JSONObject singleStat = new JSONObject (); … … 25 21 } 26 22 27 foreach (string intGamePref in Enum.GetNames (typeof(GameInfoInt))) {28 int value = gsi.GetValue ( (GameInfoInt)Enum.Parse (typeof(GameInfoInt), intGamePref));23 foreach (string intGamePref in Enum.GetNames (typeof (GameInfoInt))) { 24 int value = gsi.GetValue ((GameInfoInt) Enum.Parse (typeof (GameInfoInt), intGamePref)); 29 25 30 26 JSONObject singleStat = new JSONObject (); … … 35 31 } 36 32 37 foreach (string boolGamePref in Enum.GetNames (typeof(GameInfoBool))) {38 bool value = gsi.GetValue ( (GameInfoBool)Enum.Parse (typeof(GameInfoBool), boolGamePref));33 foreach (string boolGamePref in Enum.GetNames (typeof (GameInfoBool))) { 34 bool value = gsi.GetValue ((GameInfoBool) Enum.Parse (typeof (GameInfoBool), boolGamePref)); 39 35 40 36 JSONObject singleStat = new JSONObject (); … … 46 42 47 43 48 WriteJSON (resp, serverInfo);44 WriteJSON (resp, serverInfo); 49 45 } 50 46 } 51 47 } 52 -
binary-improvements/MapRendering/Web/API/GetStats.cs
r313 r325 1 using System.Net; 1 2 using AllocsFixes.JSON; 2 3 using AllocsFixes.LiveData; 3 using AllocsFixes.PersistentData;4 using System;5 using System.Collections.Generic;6 using System.Net;7 4 8 namespace AllocsFixes.NetConnections.Servers.Web.API 9 { 10 public class GetStats : WebAPI 11 { 12 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) 13 { 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 6 public class GetStats : WebAPI { 7 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 8 int permissionLevel) { 14 9 JSONObject result = new JSONObject (); 15 10 … … 32 27 } 33 28 } 34 -
binary-improvements/MapRendering/Web/API/GetWebUIUpdates.cs
r313 r325 1 using System.Net; 1 2 using AllocsFixes.JSON; 2 3 using AllocsFixes.LiveData; 3 using AllocsFixes.PersistentData;4 using System;5 using System.Collections.Generic;6 using System.Net;7 4 8 namespace AllocsFixes.NetConnections.Servers.Web.API 9 { 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 10 6 public class GetWebUIUpdates : WebAPI { 11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) { 7 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 8 int permissionLevel) { 12 9 int latestLine; 13 if (req.QueryString ["latestLine"] == null || !int.TryParse (req.QueryString ["latestLine"], out latestLine)) { 10 if (req.QueryString ["latestLine"] == null || 11 !int.TryParse (req.QueryString ["latestLine"], out latestLine)) { 14 12 latestLine = 0; 15 13 } … … 37 35 } 38 36 } 39 -
binary-improvements/MapRendering/Web/API/Null.cs
r251 r325 1 using AllocsFixes.JSON; 2 using System; 3 using System.Collections.Generic; 4 using System.Net; 1 using System.Net; 5 2 using System.Text; 6 3 7 namespace AllocsFixes.NetConnections.Servers.Web.API 8 { 9 public class Null : WebAPI 10 { 11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) 12 { 4 namespace AllocsFixes.NetConnections.Servers.Web.API { 5 public class Null : WebAPI { 6 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 7 int permissionLevel) { 13 8 resp.ContentLength64 = 0; 14 9 resp.ContentType = "text/plain"; 15 10 resp.ContentEncoding = Encoding.ASCII; 16 11 resp.OutputStream.Write (new byte[] { }, 0, 0); 17 18 12 } 13 } 19 14 } -
binary-improvements/MapRendering/Web/API/WebAPI.cs
r309 r325 1 using System;2 1 using System.Net; 3 2 using System.Text; 3 using AllocsFixes.JSON; 4 4 5 namespace AllocsFixes.NetConnections.Servers.Web.API 6 { 7 public abstract class WebAPI 8 { 9 public static void WriteJSON (HttpListenerResponse resp, JSON.JSONNode root) 10 { 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 6 public abstract class WebAPI { 7 public static void WriteJSON (HttpListenerResponse resp, JSONNode root) { 11 8 StringBuilder sb = new StringBuilder (); 12 9 root.ToString (sb); … … 18 15 } 19 16 20 public static void WriteText (HttpListenerResponse _resp, string _text) 21 { 17 public static void WriteText (HttpListenerResponse _resp, string _text) { 22 18 byte[] buf = Encoding.UTF8.GetBytes (_text); 23 19 _resp.ContentLength64 = buf.Length; … … 27 23 } 28 24 29 public abstract void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel); 25 public abstract void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 26 int permissionLevel); 30 27 31 28 public virtual int DefaultPermissionLevel () { … … 34 31 } 35 32 } 36 -
binary-improvements/MapRendering/Web/ConnectionHandler.cs
r250 r325 2 2 using System.Collections.Generic; 3 3 4 namespace AllocsFixes.NetConnections.Servers.Web 5 { 4 namespace AllocsFixes.NetConnections.Servers.Web { 6 5 public class ConnectionHandler { 6 private readonly Dictionary<string, WebConnection> connections = new Dictionary<string, WebConnection> (); 7 7 private Web parent; 8 private Dictionary<string, WebConnection> connections = new Dictionary<string, WebConnection> ();9 8 10 9 public ConnectionHandler (Web _parent) { … … 18 17 19 18 WebConnection con = connections [_sessionId]; 19 20 20 // if (con.Age.TotalMinutes > parent.sessionTimeoutMinutes) { 21 21 // connections.Remove (_sessionId); … … 49 49 } 50 50 } 51 52 51 } 53 52 } 54 -
binary-improvements/MapRendering/Web/Handlers/ApiHandler.cs
r279 r325 1 using AllocsFixes.NetConnections.Servers.Web.API;2 1 using System; 3 2 using System.Collections.Generic; 4 using System.IO;5 3 using System.Net; 6 4 using System.Reflection; 7 using System.Threading;5 using AllocsFixes.NetConnections.Servers.Web.API; 8 6 9 namespace AllocsFixes.NetConnections.Servers.Web.Handlers 10 { 7 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { 11 8 public class ApiHandler : PathHandler { 12 private string staticPart;13 private Dictionary<String, WebAPI> apis = new Dictionary<string, WebAPI> ();9 private readonly Dictionary<string, WebAPI> apis = new Dictionary<string, WebAPI> (); 10 private readonly string staticPart; 14 11 15 12 public ApiHandler (string staticPart, string moduleName = null) : base (moduleName) { … … 17 14 18 15 foreach (Type t in Assembly.GetExecutingAssembly ().GetTypes ()) { 19 if (!t.IsAbstract && t.IsSubclassOf (typeof (WebAPI))) {16 if (!t.IsAbstract && t.IsSubclassOf (typeof (WebAPI))) { 20 17 ConstructorInfo ctor = t.GetConstructor (new Type [0]); 21 18 if (ctor != null) { 22 WebAPI apiInstance = (WebAPI) ctor.Invoke (new object [0]);19 WebAPI apiInstance = (WebAPI) ctor.Invoke (new object [0]); 23 20 addApi (t.Name.ToLower (), apiInstance); 24 21 } … … 26 23 } 27 24 28 29 Type dummy_t = typeof (API.Null);30 31 32 WebAPI dummy_apiInstance = (WebAPI)dummy_ctor.Invoke (new object[0]);25 // Add dummy types 26 Type dummy_t = typeof (Null); 27 ConstructorInfo dummy_ctor = dummy_t.GetConstructor (new Type [0]); 28 if (dummy_ctor != null) { 29 WebAPI dummy_apiInstance = (WebAPI) dummy_ctor.Invoke (new object[0]); 33 30 34 35 addApi("viewallclaims", dummy_apiInstance);36 addApi("viewallplayers", dummy_apiInstance);37 31 // Permissions that don't map to a real API 32 addApi ("viewallclaims", dummy_apiInstance); 33 addApi ("viewallplayers", dummy_apiInstance); 34 } 38 35 } 39 36 … … 43 40 } 44 41 45 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) { 42 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 43 int permissionLevel) { 46 44 string apiName = req.Url.AbsolutePath.Remove (0, staticPart.Length); 47 45 if (!AuthorizeForCommand (apiName, user, permissionLevel)) { 48 resp.StatusCode = (int) HttpStatusCode.Forbidden;46 resp.StatusCode = (int) HttpStatusCode.Forbidden; 49 47 if (user != null) { 50 48 //Log.Out ("ApiHandler: user '{0}' not allowed to execute '{1}'", user.SteamID, apiName); 51 } else {52 //Log.Out ("ApiHandler: unidentified user from '{0}' not allowed to execute '{1}'", req.RemoteEndPoint.Address, apiName);53 49 } 50 54 51 return; 55 } else {56 foreach (KeyValuePair<string, WebAPI> kvp in apis) { 57 if (apiName.StartsWith (kvp.Key)) {58 try{59 kvp.Value.HandleRequest (req, resp, user, permissionLevel);60 return;61 } catch (Exception e) {62 Log.Error ("Error in ApiHandler.HandleRequest(): Handler {0} threw an exception:", kvp.Key);63 Log.Exception (e);64 resp.StatusCode = (int)HttpStatusCode.InternalServerError;65 return;66 }52 } 53 54 foreach (KeyValuePair<string, WebAPI> kvp in apis) { 55 if (apiName.StartsWith (kvp.Key)) { 56 try { 57 kvp.Value.HandleRequest (req, resp, user, permissionLevel); 58 return; 59 } catch (Exception e) { 60 Log.Error ("Error in ApiHandler.HandleRequest(): Handler {0} threw an exception:", kvp.Key); 61 Log.Exception (e); 62 resp.StatusCode = (int) HttpStatusCode.InternalServerError; 63 return; 67 64 } 68 65 } 69 66 } 70 67 71 68 Log.Out ("Error in ApiHandler.HandleRequest(): No handler found for API \"" + apiName + "\""); 72 resp.StatusCode = (int) HttpStatusCode.NotFound;69 resp.StatusCode = (int) HttpStatusCode.NotFound; 73 70 } 74 71 … … 76 73 return WebPermissions.Instance.ModuleAllowedWithLevel ("webapi." + apiName, permissionLevel); 77 74 } 78 79 75 } 80 81 76 } 82 -
binary-improvements/MapRendering/Web/Handlers/ItemIconHandler.cs
r306 r325 1 1 using System; 2 2 using System.Collections.Generic; 3 using System.IO; 3 4 using System.Net; 4 using System.Threading; 5 using UnityEngine; 6 using Object = UnityEngine.Object; 5 7 6 using UnityEngine; 7 using System.IO; 8 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { 9 public class ItemIconHandler : PathHandler { 10 private readonly Dictionary<string, byte[]> icons = new Dictionary<string, byte[]> (); 11 private readonly bool logMissingFiles; 8 12 9 namespace AllocsFixes.NetConnections.Servers.Web.Handlers 10 { 11 public class ItemIconHandler : PathHandler { 12 private static ItemIconHandler instance = null; 13 public static ItemIconHandler Instance { 14 get { return instance; } 13 private readonly string staticPart; 14 private bool loaded; 15 16 static ItemIconHandler () { 17 Instance = null; 15 18 } 16 19 17 private string staticPart; 18 private bool logMissingFiles; 19 private Dictionary<string, byte[]> icons = new Dictionary<string, byte[]> (); 20 private bool loaded = false; 21 22 public ItemIconHandler (string staticPart, bool logMissingFiles, string moduleName = null) : base(moduleName) { 20 public ItemIconHandler (string staticPart, bool logMissingFiles, string moduleName = null) : base (moduleName) { 23 21 this.staticPart = staticPart; 24 22 this.logMissingFiles = logMissingFiles; 25 I temIconHandler.instance = this;23 Instance = this; 26 24 } 27 25 28 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) { 26 public static ItemIconHandler Instance { get; private set; } 27 28 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 29 int permissionLevel) { 29 30 if (!loaded) { 30 resp.StatusCode = (int) HttpStatusCode.InternalServerError;31 resp.StatusCode = (int) HttpStatusCode.InternalServerError; 31 32 Log.Out ("Web:IconHandler: Icons not loaded"); 32 33 return; … … 44 45 resp.OutputStream.Write (itemIconData, 0, itemIconData.Length); 45 46 } else { 46 resp.StatusCode = (int) HttpStatusCode.NotFound;47 resp.StatusCode = (int) HttpStatusCode.NotFound; 47 48 if (logMissingFiles) { 48 49 Log.Out ("Web:IconHandler:FileNotFound: \"" + req.Url.AbsolutePath + "\" "); 49 50 } 50 return;51 51 } 52 52 } … … 66 66 return false; 67 67 } 68 68 69 DynamicUIAtlas atlas = atlasObj.GetComponent<DynamicUIAtlas> (); 69 70 if (atlas == null) { … … 78 79 Texture2D atlasTex; 79 80 80 if (!DynamicUIAtlasTools.ReadPrebakedAtlasDescriptor (textureResourceName, out sprites, out elementWidth, out elementHeight)) { 81 if (!DynamicUIAtlasTools.ReadPrebakedAtlasDescriptor (textureResourceName, out sprites, 82 out elementWidth, out elementHeight)) { 81 83 SdtdConsole.Instance.Output ("Web:IconHandler: Could not read dynamic atlas descriptor"); 82 84 return false; … … 98 100 tintedIcons.Add (name, new List<Color> ()); 99 101 } 102 100 103 List<Color> list = tintedIcons [name]; 101 104 list.Add (tintColor); … … 108 111 string name = data.name; 109 112 Texture2D tex = new Texture2D (data.width, data.height, TextureFormat.ARGB32, false); 110 tex.SetPixels (atlasTex.GetPixels (data.x, atlasTex.height - data.height - data.y, data.width, data.height)); 113 tex.SetPixels (atlasTex.GetPixels (data.x, atlasTex.height - data.height - data.y, data.width, 114 data.height)); 111 115 112 116 AddIcon (name, tex, tintedIcons); 113 117 114 UnityEngine.Object.Destroy (tex);118 Object.Destroy (tex); 115 119 } 116 Resources.UnloadAsset(atlasTex); 120 121 Resources.UnloadAsset (atlasTex); 117 122 118 123 // Load icons from mods … … 131 136 } 132 137 133 UnityEngine.Object.Destroy (tex);138 Object.Destroy (tex); 134 139 } 135 140 } … … 168 173 icons [tintedName] = tintedTex.EncodeToPNG (); 169 174 170 UnityEngine.Object.Destroy (tintedTex);175 Object.Destroy (tintedTex); 171 176 } 172 177 } 173 178 } 174 179 } 175 176 180 } 177 181 } 178 -
binary-improvements/MapRendering/Web/Handlers/PathHandler.cs
r279 r325 1 using System;2 1 using System.Net; 3 2 4 namespace AllocsFixes.NetConnections.Servers.Web.Handlers 5 { 6 public abstract class PathHandler 7 { 8 private string moduleName = null; 3 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { 4 public abstract class PathHandler { 5 private readonly string moduleName; 6 7 protected PathHandler (string _moduleName, int _defaultPermissionLevel = 0) { 8 moduleName = _moduleName; 9 WebPermissions.Instance.AddKnownModule (_moduleName, _defaultPermissionLevel); 10 } 11 9 12 public string ModuleName { 10 13 get { return moduleName; } 11 14 } 12 15 13 protected PathHandler (string _moduleName, int _defaultPermissionLevel = 0) { 14 this.moduleName = _moduleName; 15 WebPermissions.Instance.AddKnownModule (_moduleName, _defaultPermissionLevel); 16 } 17 18 public abstract void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel); 16 public abstract void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 17 int permissionLevel); 19 18 20 19 public bool IsAuthorizedForHandler (WebConnection user, int permissionLevel) { 21 20 if (moduleName != null) { 22 21 return WebPermissions.Instance.ModuleAllowedWithLevel (moduleName, permissionLevel); 23 } else {24 return true;25 22 } 23 24 return true; 26 25 } 27 26 } 28 27 } 29 -
binary-improvements/MapRendering/Web/Handlers/SessionHandler.cs
r311 r325 1 using System;2 using System.Collections.Generic;3 1 using System.IO; 4 2 using System.Net; 5 3 using System.Text; 6 using System.Threading;7 4 8 namespace AllocsFixes.NetConnections.Servers.Web.Handlers 9 { 5 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { 10 6 public class SessionHandler : PathHandler { 11 private string staticPart;12 private Web parent;13 private string header = "";14 private string footer = "";7 private readonly string footer = ""; 8 private readonly string header = ""; 9 private readonly Web parent; 10 private readonly string staticPart; 15 11 16 public SessionHandler (string _staticPart, string _dataFolder, Web _parent, string moduleName = null) : base(moduleName) { 17 this.staticPart = _staticPart; 18 this.parent = _parent; 12 public SessionHandler (string _staticPart, string _dataFolder, Web _parent, string moduleName = null) : 13 base (moduleName) { 14 staticPart = _staticPart; 15 parent = _parent; 19 16 20 17 if (File.Exists (_dataFolder + "/sessionheader.tmpl")) { … … 27 24 } 28 25 29 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) { 26 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 27 int permissionLevel) { 30 28 string subpath = req.Url.AbsolutePath.Remove (0, staticPart.Length); 31 29 … … 37 35 resp.Redirect ("/static/index.html"); 38 36 return; 39 } else {40 result.Append ("<h1>Login failed, <a href=\"/static/index.html\">click to return to main page</a>.</h1>");41 37 } 38 39 result.Append ( 40 "<h1>Login failed, <a href=\"/static/index.html\">click to return to main page</a>.</h1>"); 42 41 } else if (subpath.StartsWith ("logout")) { 43 42 if (user != null) { … … 48 47 resp.Redirect ("/static/index.html"); 49 48 return; 50 } else {51 result.Append ("<h1>Not logged in, <a href=\"/static/index.html\">click to return to main page</a>.</h1>");52 49 } 50 51 result.Append ( 52 "<h1>Not logged in, <a href=\"/static/index.html\">click to return to main page</a>.</h1>"); 53 53 } else if (subpath.StartsWith ("login")) { 54 54 string host = (Web.isSslRedirected (req) ? "https://" : "http://") + req.UserHostName; … … 57 57 return; 58 58 } else { 59 result.Append ("<h1>Unknown command, <a href=\"/static/index.html\">click to return to main page</a>.</h1>"); 59 result.Append ( 60 "<h1>Unknown command, <a href=\"/static/index.html\">click to return to main page</a>.</h1>"); 60 61 } 61 62 … … 68 69 resp.OutputStream.Write (buf, 0, buf.Length); 69 70 } 70 71 71 } 72 73 72 } 74 -
binary-improvements/MapRendering/Web/Handlers/SimpleRedirectHandler.cs
r244 r325 1 using System;2 1 using System.Net; 3 2 4 namespace AllocsFixes.NetConnections.Servers.Web.Handlers 5 { 6 public class SimpleRedirectHandler : PathHandler 7 { 8 string target; 3 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { 4 public class SimpleRedirectHandler : PathHandler { 5 private readonly string target; 9 6 10 public SimpleRedirectHandler (string target, string moduleName = null) : base(moduleName) 11 { 7 public SimpleRedirectHandler (string target, string moduleName = null) : base (moduleName) { 12 8 this.target = target; 13 9 } 14 10 15 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel)16 {11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 12 int permissionLevel) { 17 13 resp.Redirect (target); 18 14 } 19 15 } 20 16 } 21 -
binary-improvements/MapRendering/Web/Handlers/StaticHandler.cs
r251 r325 1 using System;2 using System.Collections.Generic;3 1 using System.IO; 4 2 using System.Net; 5 using System.Threading;3 using AllocsFixes.FileCache; 6 4 7 namespace AllocsFixes.NetConnections.Servers.Web.Handlers 8 { 9 public class StaticHandler : PathHandler 10 { 11 private string datapath; 12 private string staticPart; 13 private AllocsFixes.FileCache.AbstractCache cache; 14 private bool logMissingFiles; 5 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { 6 public class StaticHandler : PathHandler { 7 private readonly AbstractCache cache; 8 private readonly string datapath; 9 private readonly bool logMissingFiles; 10 private readonly string staticPart; 15 11 16 public StaticHandler (string staticPart, string filePath, A llocsFixes.FileCache.AbstractCache cache, bool logMissingFiles, string moduleName = null) : base(moduleName)17 {12 public StaticHandler (string staticPart, string filePath, AbstractCache cache, bool logMissingFiles, 13 string moduleName = null) : base (moduleName) { 18 14 this.staticPart = staticPart; 19 this.datapath = filePath;15 datapath = filePath; 20 16 this.cache = cache; 21 17 this.logMissingFiles = logMissingFiles; 22 18 } 23 19 24 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel)25 {20 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 21 int permissionLevel) { 26 22 string fn = req.Url.AbsolutePath.Remove (0, staticPart.Length); 27 23 … … 33 29 resp.OutputStream.Write (content, 0, content.Length); 34 30 } else { 35 resp.StatusCode = (int)HttpStatusCode.NotFound; 36 if (logMissingFiles) 37 Log.Out ("Web:Static:FileNotFound: \"" + req.Url.AbsolutePath + "\" @ \"" + datapath + "/" + req.Url.AbsolutePath.Remove (0, staticPart.Length) + "\""); 38 return; 31 resp.StatusCode = (int) HttpStatusCode.NotFound; 32 if (logMissingFiles) { 33 Log.Out ("Web:Static:FileNotFound: \"" + req.Url.AbsolutePath + "\" @ \"" + datapath + "/" + 34 req.Url.AbsolutePath.Remove (0, staticPart.Length) + "\""); 35 } 39 36 } 40 37 } 41 38 } 42 39 } 43 -
binary-improvements/MapRendering/Web/Handlers/UserStatusHandler.cs
r309 r325 1 using System;2 using System.Collections.Generic;3 using System.IO;4 1 using System.Net; 5 using System.Threading;6 using System.Text;7 2 using AllocsFixes.JSON; 3 using AllocsFixes.NetConnections.Servers.Web.API; 8 4 9 namespace AllocsFixes.NetConnections.Servers.Web.Handlers 10 { 5 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { 11 6 public class UserStatusHandler : PathHandler { 12 public UserStatusHandler (string moduleName = null) : base (moduleName) {7 public UserStatusHandler (string moduleName = null) : base (moduleName) { 13 8 } 14 9 15 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) { 10 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 11 int permissionLevel) { 16 12 JSONObject result = new JSONObject (); 17 13 … … 23 19 JSONObject permObj = new JSONObject (); 24 20 permObj.Add ("module", new JSONString (perm.module)); 25 permObj.Add ("allowed", new JSONBoolean (WebPermissions.Instance.ModuleAllowedWithLevel (perm.module, permissionLevel))); 21 permObj.Add ("allowed", 22 new JSONBoolean (WebPermissions.Instance.ModuleAllowedWithLevel (perm.module, permissionLevel))); 26 23 perms.Add (permObj); 27 24 } 25 28 26 result.Add ("permissions", perms); 29 27 30 AllocsFixes.NetConnections.Servers.Web.API.WebAPI.WriteJSON (resp, result);28 WebAPI.WriteJSON (resp, result); 31 29 } 32 33 30 } 34 35 31 } 36 -
binary-improvements/MapRendering/Web/LogBuffer.cs
r270 r325 2 2 using System.Collections.Generic; 3 3 using System.Text.RegularExpressions; 4 5 4 using UnityEngine; 6 5 7 namespace AllocsFixes.NetConnections.Servers.Web 8 { 6 namespace AllocsFixes.NetConnections.Servers.Web { 9 7 public class LogBuffer { 10 8 private const int MAX_ENTRIES = 3000; 11 9 private static LogBuffer instance; 10 11 private static readonly Regex logMessageMatcher = 12 new Regex (@"^([0-9]{4}-[0-9]{2}-[0-9]{2})T([0-9]{2}:[0-9]{2}:[0-9]{2}) ([0-9]+[,.][0-9]+) [A-Z]+ (.*)$"); 13 14 private readonly List<LogEntry> logEntries = new List<LogEntry> (); 15 16 private int listOffset; 17 18 private LogBuffer () { 19 Logger.Main.LogCallbacks += LogCallback; 20 } 12 21 13 22 public static LogBuffer Instance { … … 16 25 instance = new LogBuffer (); 17 26 } 27 18 28 return instance; 19 29 } 20 30 } 21 22 private static Regex logMessageMatcher = new Regex (@"^([0-9]{4}-[0-9]{2}-[0-9]{2})T([0-9]{2}:[0-9]{2}:[0-9]{2}) ([0-9]+[,.][0-9]+) [A-Z]+ (.*)$");23 private List<LogEntry> logEntries = new List<LogEntry> ();24 private int listOffset = 0;25 31 26 32 public int OldestLine { … … 55 61 } 56 62 } 63 57 64 return null; 58 65 } 59 }60 61 private LogBuffer () {62 Logger.Main.LogCallbacks += LogCallback;63 66 } 64 67 … … 123 126 public class LogEntry { 124 127 public string date; 128 public string message; 125 129 public string time; 126 public string uptime;127 public string message;128 130 public string trace; 129 131 public LogType type; 132 public string uptime; 130 133 } 131 134 } 132 135 } 133 -
binary-improvements/MapRendering/Web/MimeType.cs
r230 r325 2 2 using System.Collections.Generic; 3 3 4 namespace AllocsFixes.NetConnections.Servers.Web 5 { 6 public class MimeType 7 { 8 private static IDictionary<string, string> _mappings = new Dictionary<string, string> (StringComparer.InvariantCultureIgnoreCase) { 9 {".323", "text/h323"}, 10 {".3g2", "video/3gpp2"}, 11 {".3gp", "video/3gpp"}, 12 {".3gp2", "video/3gpp2"}, 13 {".3gpp", "video/3gpp"}, 14 {".7z", "application/x-7z-compressed"}, 15 {".aa", "audio/audible"}, 16 {".AAC", "audio/aac"}, 17 {".aaf", "application/octet-stream"}, 18 {".aax", "audio/vnd.audible.aax"}, 19 {".ac3", "audio/ac3"}, 20 {".aca", "application/octet-stream"}, 21 {".accda", "application/msaccess.addin"}, 22 {".accdb", "application/msaccess"}, 23 {".accdc", "application/msaccess.cab"}, 24 {".accde", "application/msaccess"}, 25 {".accdr", "application/msaccess.runtime"}, 26 {".accdt", "application/msaccess"}, 27 {".accdw", "application/msaccess.webapplication"}, 28 {".accft", "application/msaccess.ftemplate"}, 29 {".acx", "application/internet-property-stream"}, 30 {".AddIn", "text/xml"}, 31 {".ade", "application/msaccess"}, 32 {".adobebridge", "application/x-bridge-url"}, 33 {".adp", "application/msaccess"}, 34 {".ADT", "audio/vnd.dlna.adts"}, 35 {".ADTS", "audio/aac"}, 36 {".afm", "application/octet-stream"}, 37 {".ai", "application/postscript"}, 38 {".aif", "audio/x-aiff"}, 39 {".aifc", "audio/aiff"}, 40 {".aiff", "audio/aiff"}, 41 {".air", "application/vnd.adobe.air-application-installer-package+zip"}, 42 {".amc", "application/x-mpeg"}, 43 {".application", "application/x-ms-application"}, 44 {".art", "image/x-jg"}, 45 {".asa", "application/xml"}, 46 {".asax", "application/xml"}, 47 {".ascx", "application/xml"}, 48 {".asd", "application/octet-stream"}, 49 {".asf", "video/x-ms-asf"}, 50 {".ashx", "application/xml"}, 51 {".asi", "application/octet-stream"}, 52 {".asm", "text/plain"}, 53 {".asmx", "application/xml"}, 54 {".aspx", "application/xml"}, 55 {".asr", "video/x-ms-asf"}, 56 {".asx", "video/x-ms-asf"}, 57 {".atom", "application/atom+xml"}, 58 {".au", "audio/basic"}, 59 {".avi", "video/x-msvideo"}, 60 {".axs", "application/olescript"}, 61 {".bas", "text/plain"}, 62 {".bcpio", "application/x-bcpio"}, 63 {".bin", "application/octet-stream"}, 64 {".bmp", "image/bmp"}, 65 {".c", "text/plain"}, 66 {".cab", "application/octet-stream"}, 67 {".caf", "audio/x-caf"}, 68 {".calx", "application/vnd.ms-office.calx"}, 69 {".cat", "application/vnd.ms-pki.seccat"}, 70 {".cc", "text/plain"}, 71 {".cd", "text/plain"}, 72 {".cdda", "audio/aiff"}, 73 {".cdf", "application/x-cdf"}, 74 {".cer", "application/x-x509-ca-cert"}, 75 {".chm", "application/octet-stream"}, 76 {".class", "application/x-java-applet"}, 77 {".clp", "application/x-msclip"}, 78 {".cmx", "image/x-cmx"}, 79 {".cnf", "text/plain"}, 80 {".cod", "image/cis-cod"}, 81 {".config", "application/xml"}, 82 {".contact", "text/x-ms-contact"}, 83 {".coverage", "application/xml"}, 84 {".cpio", "application/x-cpio"}, 85 {".cpp", "text/plain"}, 86 {".crd", "application/x-mscardfile"}, 87 {".crl", "application/pkix-crl"}, 88 {".crt", "application/x-x509-ca-cert"}, 89 {".cs", "text/plain"}, 90 {".csdproj", "text/plain"}, 91 {".csh", "application/x-csh"}, 92 {".csproj", "text/plain"}, 93 {".css", "text/css"}, 94 {".csv", "text/csv"}, 95 {".cur", "application/octet-stream"}, 96 {".cxx", "text/plain"}, 97 {".dat", "application/octet-stream"}, 98 {".datasource", "application/xml"}, 99 {".dbproj", "text/plain"}, 100 {".dcr", "application/x-director"}, 101 {".def", "text/plain"}, 102 {".deploy", "application/octet-stream"}, 103 {".der", "application/x-x509-ca-cert"}, 104 {".dgml", "application/xml"}, 105 {".dib", "image/bmp"}, 106 {".dif", "video/x-dv"}, 107 {".dir", "application/x-director"}, 108 {".disco", "text/xml"}, 109 {".dll", "application/x-msdownload"}, 110 {".dll.config", "text/xml"}, 111 {".dlm", "text/dlm"}, 112 {".doc", "application/msword"}, 113 {".docm", "application/vnd.ms-word.document.macroEnabled.12"}, 114 {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, 115 {".dot", "application/msword"}, 116 {".dotm", "application/vnd.ms-word.template.macroEnabled.12"}, 117 {".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"}, 118 {".dsp", "application/octet-stream"}, 119 {".dsw", "text/plain"}, 120 {".dtd", "text/xml"}, 121 {".dtsConfig", "text/xml"}, 122 {".dv", "video/x-dv"}, 123 {".dvi", "application/x-dvi"}, 124 {".dwf", "drawing/x-dwf"}, 125 {".dwp", "application/octet-stream"}, 126 {".dxr", "application/x-director"}, 127 {".eml", "message/rfc822"}, 128 {".emz", "application/octet-stream"}, 129 {".eot", "application/octet-stream"}, 130 {".eps", "application/postscript"}, 131 {".etl", "application/etl"}, 132 {".etx", "text/x-setext"}, 133 {".evy", "application/envoy"}, 134 {".exe", "application/octet-stream"}, 135 {".exe.config", "text/xml"}, 136 {".fdf", "application/vnd.fdf"}, 137 {".fif", "application/fractals"}, 138 {".filters", "Application/xml"}, 139 {".fla", "application/octet-stream"}, 140 {".flr", "x-world/x-vrml"}, 141 {".flv", "video/x-flv"}, 142 {".fsscript", "application/fsharp-script"}, 143 {".fsx", "application/fsharp-script"}, 144 {".generictest", "application/xml"}, 145 {".gif", "image/gif"}, 146 {".group", "text/x-ms-group"}, 147 {".gsm", "audio/x-gsm"}, 148 {".gtar", "application/x-gtar"}, 149 {".gz", "application/x-gzip"}, 150 {".h", "text/plain"}, 151 {".hdf", "application/x-hdf"}, 152 {".hdml", "text/x-hdml"}, 153 {".hhc", "application/x-oleobject"}, 154 {".hhk", "application/octet-stream"}, 155 {".hhp", "application/octet-stream"}, 156 {".hlp", "application/winhlp"}, 157 {".hpp", "text/plain"}, 158 {".hqx", "application/mac-binhex40"}, 159 {".hta", "application/hta"}, 160 {".htc", "text/x-component"}, 161 {".htm", "text/html"}, 162 {".html", "text/html"}, 163 {".htt", "text/webviewhtml"}, 164 {".hxa", "application/xml"}, 165 {".hxc", "application/xml"}, 166 {".hxd", "application/octet-stream"}, 167 {".hxe", "application/xml"}, 168 {".hxf", "application/xml"}, 169 {".hxh", "application/octet-stream"}, 170 {".hxi", "application/octet-stream"}, 171 {".hxk", "application/xml"}, 172 {".hxq", "application/octet-stream"}, 173 {".hxr", "application/octet-stream"}, 174 {".hxs", "application/octet-stream"}, 175 {".hxt", "text/html"}, 176 {".hxv", "application/xml"}, 177 {".hxw", "application/octet-stream"}, 178 {".hxx", "text/plain"}, 179 {".i", "text/plain"}, 180 {".ico", "image/x-icon"}, 181 {".ics", "application/octet-stream"}, 182 {".idl", "text/plain"}, 183 {".ief", "image/ief"}, 184 {".iii", "application/x-iphone"}, 185 {".inc", "text/plain"}, 186 {".inf", "application/octet-stream"}, 187 {".inl", "text/plain"}, 188 {".ins", "application/x-internet-signup"}, 189 {".ipa", "application/x-itunes-ipa"}, 190 {".ipg", "application/x-itunes-ipg"}, 191 {".ipproj", "text/plain"}, 192 {".ipsw", "application/x-itunes-ipsw"}, 193 {".iqy", "text/x-ms-iqy"}, 194 {".isp", "application/x-internet-signup"}, 195 {".ite", "application/x-itunes-ite"}, 196 {".itlp", "application/x-itunes-itlp"}, 197 {".itms", "application/x-itunes-itms"}, 198 {".itpc", "application/x-itunes-itpc"}, 199 {".IVF", "video/x-ivf"}, 200 {".jar", "application/java-archive"}, 201 {".java", "application/octet-stream"}, 202 {".jck", "application/liquidmotion"}, 203 {".jcz", "application/liquidmotion"}, 204 {".jfif", "image/pjpeg"}, 205 {".jnlp", "application/x-java-jnlp-file"}, 206 {".jpb", "application/octet-stream"}, 207 {".jpe", "image/jpeg"}, 208 {".jpeg", "image/jpeg"}, 209 {".jpg", "image/jpeg"}, 210 {".js", "application/x-javascript"}, 211 {".json", "application/json"}, 212 {".jsx", "text/jscript"}, 213 {".jsxbin", "text/plain"}, 214 {".latex", "application/x-latex"}, 215 {".library-ms", "application/windows-library+xml"}, 216 {".lit", "application/x-ms-reader"}, 217 {".loadtest", "application/xml"}, 218 {".lpk", "application/octet-stream"}, 219 {".lsf", "video/x-la-asf"}, 220 {".lst", "text/plain"}, 221 {".lsx", "video/x-la-asf"}, 222 {".lzh", "application/octet-stream"}, 223 {".m13", "application/x-msmediaview"}, 224 {".m14", "application/x-msmediaview"}, 225 {".m1v", "video/mpeg"}, 226 {".m2t", "video/vnd.dlna.mpeg-tts"}, 227 {".m2ts", "video/vnd.dlna.mpeg-tts"}, 228 {".m2v", "video/mpeg"}, 229 {".m3u", "audio/x-mpegurl"}, 230 {".m3u8", "audio/x-mpegurl"}, 231 {".m4a", "audio/m4a"}, 232 {".m4b", "audio/m4b"}, 233 {".m4p", "audio/m4p"}, 234 {".m4r", "audio/x-m4r"}, 235 {".m4v", "video/x-m4v"}, 236 {".mac", "image/x-macpaint"}, 237 {".mak", "text/plain"}, 238 {".man", "application/x-troff-man"}, 239 {".manifest", "application/x-ms-manifest"}, 240 {".map", "text/plain"}, 241 {".master", "application/xml"}, 242 {".mda", "application/msaccess"}, 243 {".mdb", "application/x-msaccess"}, 244 {".mde", "application/msaccess"}, 245 {".mdp", "application/octet-stream"}, 246 {".me", "application/x-troff-me"}, 247 {".mfp", "application/x-shockwave-flash"}, 248 {".mht", "message/rfc822"}, 249 {".mhtml", "message/rfc822"}, 250 {".mid", "audio/mid"}, 251 {".midi", "audio/mid"}, 252 {".mix", "application/octet-stream"}, 253 {".mk", "text/plain"}, 254 {".mmf", "application/x-smaf"}, 255 {".mno", "text/xml"}, 256 {".mny", "application/x-msmoney"}, 257 {".mod", "video/mpeg"}, 258 {".mov", "video/quicktime"}, 259 {".movie", "video/x-sgi-movie"}, 260 {".mp2", "video/mpeg"}, 261 {".mp2v", "video/mpeg"}, 262 {".mp3", "audio/mpeg"}, 263 {".mp4", "video/mp4"}, 264 {".mp4v", "video/mp4"}, 265 {".mpa", "video/mpeg"}, 266 {".mpe", "video/mpeg"}, 267 {".mpeg", "video/mpeg"}, 268 {".mpf", "application/vnd.ms-mediapackage"}, 269 {".mpg", "video/mpeg"}, 270 {".mpp", "application/vnd.ms-project"}, 271 {".mpv2", "video/mpeg"}, 272 {".mqv", "video/quicktime"}, 273 {".ms", "application/x-troff-ms"}, 274 {".msi", "application/octet-stream"}, 275 {".mso", "application/octet-stream"}, 276 {".mts", "video/vnd.dlna.mpeg-tts"}, 277 {".mtx", "application/xml"}, 278 {".mvb", "application/x-msmediaview"}, 279 {".mvc", "application/x-miva-compiled"}, 280 {".mxp", "application/x-mmxp"}, 281 {".nc", "application/x-netcdf"}, 282 {".nsc", "video/x-ms-asf"}, 283 {".nws", "message/rfc822"}, 284 {".ocx", "application/octet-stream"}, 285 {".oda", "application/oda"}, 286 {".odc", "text/x-ms-odc"}, 287 {".odh", "text/plain"}, 288 {".odl", "text/plain"}, 289 {".odp", "application/vnd.oasis.opendocument.presentation"}, 290 {".ods", "application/oleobject"}, 291 {".odt", "application/vnd.oasis.opendocument.text"}, 292 {".one", "application/onenote"}, 293 {".onea", "application/onenote"}, 294 {".onepkg", "application/onenote"}, 295 {".onetmp", "application/onenote"}, 296 {".onetoc", "application/onenote"}, 297 {".onetoc2", "application/onenote"}, 298 {".orderedtest", "application/xml"}, 299 {".osdx", "application/opensearchdescription+xml"}, 300 {".p10", "application/pkcs10"}, 301 {".p12", "application/x-pkcs12"}, 302 {".p7b", "application/x-pkcs7-certificates"}, 303 {".p7c", "application/pkcs7-mime"}, 304 {".p7m", "application/pkcs7-mime"}, 305 {".p7r", "application/x-pkcs7-certreqresp"}, 306 {".p7s", "application/pkcs7-signature"}, 307 {".pbm", "image/x-portable-bitmap"}, 308 {".pcast", "application/x-podcast"}, 309 {".pct", "image/pict"}, 310 {".pcx", "application/octet-stream"}, 311 {".pcz", "application/octet-stream"}, 312 {".pdf", "application/pdf"}, 313 {".pfb", "application/octet-stream"}, 314 {".pfm", "application/octet-stream"}, 315 {".pfx", "application/x-pkcs12"}, 316 {".pgm", "image/x-portable-graymap"}, 317 {".pic", "image/pict"}, 318 {".pict", "image/pict"}, 319 {".pkgdef", "text/plain"}, 320 {".pkgundef", "text/plain"}, 321 {".pko", "application/vnd.ms-pki.pko"}, 322 {".pls", "audio/scpls"}, 323 {".pma", "application/x-perfmon"}, 324 {".pmc", "application/x-perfmon"}, 325 {".pml", "application/x-perfmon"}, 326 {".pmr", "application/x-perfmon"}, 327 {".pmw", "application/x-perfmon"}, 328 {".png", "image/png"}, 329 {".pnm", "image/x-portable-anymap"}, 330 {".pnt", "image/x-macpaint"}, 331 {".pntg", "image/x-macpaint"}, 332 {".pnz", "image/png"}, 333 {".pot", "application/vnd.ms-powerpoint"}, 334 {".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"}, 335 {".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"}, 336 {".ppa", "application/vnd.ms-powerpoint"}, 337 {".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"}, 338 {".ppm", "image/x-portable-pixmap"}, 339 {".pps", "application/vnd.ms-powerpoint"}, 340 {".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"}, 341 {".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"}, 342 {".ppt", "application/vnd.ms-powerpoint"}, 343 {".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"}, 344 {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, 345 {".prf", "application/pics-rules"}, 346 {".prm", "application/octet-stream"}, 347 {".prx", "application/octet-stream"}, 348 {".ps", "application/postscript"}, 349 {".psc1", "application/PowerShell"}, 350 {".psd", "application/octet-stream"}, 351 {".psess", "application/xml"}, 352 {".psm", "application/octet-stream"}, 353 {".psp", "application/octet-stream"}, 354 {".pub", "application/x-mspublisher"}, 355 {".pwz", "application/vnd.ms-powerpoint"}, 356 {".qht", "text/x-html-insertion"}, 357 {".qhtm", "text/x-html-insertion"}, 358 {".qt", "video/quicktime"}, 359 {".qti", "image/x-quicktime"}, 360 {".qtif", "image/x-quicktime"}, 361 {".qtl", "application/x-quicktimeplayer"}, 362 {".qxd", "application/octet-stream"}, 363 {".ra", "audio/x-pn-realaudio"}, 364 {".ram", "audio/x-pn-realaudio"}, 365 {".rar", "application/octet-stream"}, 366 {".ras", "image/x-cmu-raster"}, 367 {".rat", "application/rat-file"}, 368 {".rc", "text/plain"}, 369 {".rc2", "text/plain"}, 370 {".rct", "text/plain"}, 371 {".rdlc", "application/xml"}, 372 {".resx", "application/xml"}, 373 {".rf", "image/vnd.rn-realflash"}, 374 {".rgb", "image/x-rgb"}, 375 {".rgs", "text/plain"}, 376 {".rm", "application/vnd.rn-realmedia"}, 377 {".rmi", "audio/mid"}, 378 {".rmp", "application/vnd.rn-rn_music_package"}, 379 {".roff", "application/x-troff"}, 380 {".rpm", "audio/x-pn-realaudio-plugin"}, 381 {".rqy", "text/x-ms-rqy"}, 382 {".rtf", "application/rtf"}, 383 {".rtx", "text/richtext"}, 384 {".ruleset", "application/xml"}, 385 {".s", "text/plain"}, 386 {".safariextz", "application/x-safari-safariextz"}, 387 {".scd", "application/x-msschedule"}, 388 {".sct", "text/scriptlet"}, 389 {".sd2", "audio/x-sd2"}, 390 {".sdp", "application/sdp"}, 391 {".sea", "application/octet-stream"}, 392 {".searchConnector-ms", "application/windows-search-connector+xml"}, 393 {".setpay", "application/set-payment-initiation"}, 394 {".setreg", "application/set-registration-initiation"}, 395 {".settings", "application/xml"}, 396 {".sgimb", "application/x-sgimb"}, 397 {".sgml", "text/sgml"}, 398 {".sh", "application/x-sh"}, 399 {".shar", "application/x-shar"}, 400 {".shtml", "text/html"}, 401 {".sit", "application/x-stuffit"}, 402 {".sitemap", "application/xml"}, 403 {".skin", "application/xml"}, 404 {".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"}, 405 {".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"}, 406 {".slk", "application/vnd.ms-excel"}, 407 {".sln", "text/plain"}, 408 {".slupkg-ms", "application/x-ms-license"}, 409 {".smd", "audio/x-smd"}, 410 {".smi", "application/octet-stream"}, 411 {".smx", "audio/x-smd"}, 412 {".smz", "audio/x-smd"}, 413 {".snd", "audio/basic"}, 414 {".snippet", "application/xml"}, 415 {".snp", "application/octet-stream"}, 416 {".sol", "text/plain"}, 417 {".sor", "text/plain"}, 418 {".spc", "application/x-pkcs7-certificates"}, 419 {".spl", "application/futuresplash"}, 420 {".src", "application/x-wais-source"}, 421 {".srf", "text/plain"}, 422 {".SSISDeploymentManifest", "text/xml"}, 423 {".ssm", "application/streamingmedia"}, 424 {".sst", "application/vnd.ms-pki.certstore"}, 425 {".stl", "application/vnd.ms-pki.stl"}, 426 {".sv4cpio", "application/x-sv4cpio"}, 427 {".sv4crc", "application/x-sv4crc"}, 428 {".svc", "application/xml"}, 429 {".swf", "application/x-shockwave-flash"}, 430 {".t", "application/x-troff"}, 431 {".tar", "application/x-tar"}, 432 {".tcl", "application/x-tcl"}, 433 {".testrunconfig", "application/xml"}, 434 {".testsettings", "application/xml"}, 435 {".tex", "application/x-tex"}, 436 {".texi", "application/x-texinfo"}, 437 {".texinfo", "application/x-texinfo"}, 438 {".tgz", "application/x-compressed"}, 439 {".thmx", "application/vnd.ms-officetheme"}, 440 {".thn", "application/octet-stream"}, 441 {".tif", "image/tiff"}, 442 {".tiff", "image/tiff"}, 443 {".tlh", "text/plain"}, 444 {".tli", "text/plain"}, 445 {".toc", "application/octet-stream"}, 446 {".tr", "application/x-troff"}, 447 {".trm", "application/x-msterminal"}, 448 {".trx", "application/xml"}, 449 {".ts", "video/vnd.dlna.mpeg-tts"}, 450 {".tsv", "text/tab-separated-values"}, 451 {".ttf", "application/octet-stream"}, 452 {".tts", "video/vnd.dlna.mpeg-tts"}, 453 {".txt", "text/plain"}, 454 {".u32", "application/octet-stream"}, 455 {".uls", "text/iuls"}, 456 {".user", "text/plain"}, 457 {".ustar", "application/x-ustar"}, 458 {".vb", "text/plain"}, 459 {".vbdproj", "text/plain"}, 460 {".vbk", "video/mpeg"}, 461 {".vbproj", "text/plain"}, 462 {".vbs", "text/vbscript"}, 463 {".vcf", "text/x-vcard"}, 464 {".vcproj", "Application/xml"}, 465 {".vcs", "text/plain"}, 466 {".vcxproj", "Application/xml"}, 467 {".vddproj", "text/plain"}, 468 {".vdp", "text/plain"}, 469 {".vdproj", "text/plain"}, 470 {".vdx", "application/vnd.ms-visio.viewer"}, 471 {".vml", "text/xml"}, 472 {".vscontent", "application/xml"}, 473 {".vsct", "text/xml"}, 474 {".vsd", "application/vnd.visio"}, 475 {".vsi", "application/ms-vsi"}, 476 {".vsix", "application/vsix"}, 477 {".vsixlangpack", "text/xml"}, 478 {".vsixmanifest", "text/xml"}, 479 {".vsmdi", "application/xml"}, 480 {".vspscc", "text/plain"}, 481 {".vss", "application/vnd.visio"}, 482 {".vsscc", "text/plain"}, 483 {".vssettings", "text/xml"}, 484 {".vssscc", "text/plain"}, 485 {".vst", "application/vnd.visio"}, 486 {".vstemplate", "text/xml"}, 487 {".vsto", "application/x-ms-vsto"}, 488 {".vsw", "application/vnd.visio"}, 489 {".vsx", "application/vnd.visio"}, 490 {".vtx", "application/vnd.visio"}, 491 {".wav", "audio/wav"}, 492 {".wave", "audio/wav"}, 493 {".wax", "audio/x-ms-wax"}, 494 {".wbk", "application/msword"}, 495 {".wbmp", "image/vnd.wap.wbmp"}, 496 {".wcm", "application/vnd.ms-works"}, 497 {".wdb", "application/vnd.ms-works"}, 498 {".wdp", "image/vnd.ms-photo"}, 499 {".webarchive", "application/x-safari-webarchive"}, 500 {".webtest", "application/xml"}, 501 {".wiq", "application/xml"}, 502 {".wiz", "application/msword"}, 503 {".wks", "application/vnd.ms-works"}, 504 {".WLMP", "application/wlmoviemaker"}, 505 {".wlpginstall", "application/x-wlpg-detect"}, 506 {".wlpginstall3", "application/x-wlpg3-detect"}, 507 {".wm", "video/x-ms-wm"}, 508 {".wma", "audio/x-ms-wma"}, 509 {".wmd", "application/x-ms-wmd"}, 510 {".wmf", "application/x-msmetafile"}, 511 {".wml", "text/vnd.wap.wml"}, 512 {".wmlc", "application/vnd.wap.wmlc"}, 513 {".wmls", "text/vnd.wap.wmlscript"}, 514 {".wmlsc", "application/vnd.wap.wmlscriptc"}, 515 {".wmp", "video/x-ms-wmp"}, 516 {".wmv", "video/x-ms-wmv"}, 517 {".wmx", "video/x-ms-wmx"}, 518 {".wmz", "application/x-ms-wmz"}, 519 {".wpl", "application/vnd.ms-wpl"}, 520 {".wps", "application/vnd.ms-works"}, 521 {".wri", "application/x-mswrite"}, 522 {".wrl", "x-world/x-vrml"}, 523 {".wrz", "x-world/x-vrml"}, 524 {".wsc", "text/scriptlet"}, 525 {".wsdl", "text/xml"}, 526 {".wvx", "video/x-ms-wvx"}, 527 {".x", "application/directx"}, 528 {".xaf", "x-world/x-vrml"}, 529 {".xaml", "application/xaml+xml"}, 530 {".xap", "application/x-silverlight-app"}, 531 {".xbap", "application/x-ms-xbap"}, 532 {".xbm", "image/x-xbitmap"}, 533 {".xdr", "text/plain"}, 534 {".xht", "application/xhtml+xml"}, 535 {".xhtml", "application/xhtml+xml"}, 536 {".xla", "application/vnd.ms-excel"}, 537 {".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"}, 538 {".xlc", "application/vnd.ms-excel"}, 539 {".xld", "application/vnd.ms-excel"}, 540 {".xlk", "application/vnd.ms-excel"}, 541 {".xll", "application/vnd.ms-excel"}, 542 {".xlm", "application/vnd.ms-excel"}, 543 {".xls", "application/vnd.ms-excel"}, 544 {".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"}, 545 {".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"}, 546 {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, 547 {".xlt", "application/vnd.ms-excel"}, 548 {".xltm", "application/vnd.ms-excel.template.macroEnabled.12"}, 549 {".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"}, 550 {".xlw", "application/vnd.ms-excel"}, 551 {".xml", "text/xml"}, 552 {".xmta", "application/xml"}, 553 {".xof", "x-world/x-vrml"}, 554 {".XOML", "text/plain"}, 555 {".xpm", "image/x-xpixmap"}, 556 {".xps", "application/vnd.ms-xpsdocument"}, 557 {".xrm-ms", "text/xml"}, 558 {".xsc", "application/xml"}, 559 {".xsd", "text/xml"}, 560 {".xsf", "text/xml"}, 561 {".xsl", "text/xml"}, 562 {".xslt", "text/xml"}, 563 {".xsn", "application/octet-stream"}, 564 {".xss", "application/xml"}, 565 {".xtp", "application/octet-stream"}, 566 {".xwd", "image/x-xwindowdump"}, 567 {".z", "application/x-compress"}, 568 {".zip", "application/x-zip-compressed"}, 569 }; 4 namespace AllocsFixes.NetConnections.Servers.Web { 5 public class MimeType { 6 private static readonly IDictionary<string, string> _mappings = 7 new Dictionary<string, string> (StringComparer.InvariantCultureIgnoreCase) { 8 {".323", "text/h323"}, 9 {".3g2", "video/3gpp2"}, 10 {".3gp", "video/3gpp"}, 11 {".3gp2", "video/3gpp2"}, 12 {".3gpp", "video/3gpp"}, 13 {".7z", "application/x-7z-compressed"}, 14 {".aa", "audio/audible"}, 15 {".AAC", "audio/aac"}, 16 {".aaf", "application/octet-stream"}, 17 {".aax", "audio/vnd.audible.aax"}, 18 {".ac3", "audio/ac3"}, 19 {".aca", "application/octet-stream"}, 20 {".accda", "application/msaccess.addin"}, 21 {".accdb", "application/msaccess"}, 22 {".accdc", "application/msaccess.cab"}, 23 {".accde", "application/msaccess"}, 24 {".accdr", "application/msaccess.runtime"}, 25 {".accdt", "application/msaccess"}, 26 {".accdw", "application/msaccess.webapplication"}, 27 {".accft", "application/msaccess.ftemplate"}, 28 {".acx", "application/internet-property-stream"}, 29 {".AddIn", "text/xml"}, 30 {".ade", "application/msaccess"}, 31 {".adobebridge", "application/x-bridge-url"}, 32 {".adp", "application/msaccess"}, 33 {".ADT", "audio/vnd.dlna.adts"}, 34 {".ADTS", "audio/aac"}, 35 {".afm", "application/octet-stream"}, 36 {".ai", "application/postscript"}, 37 {".aif", "audio/x-aiff"}, 38 {".aifc", "audio/aiff"}, 39 {".aiff", "audio/aiff"}, 40 {".air", "application/vnd.adobe.air-application-installer-package+zip"}, 41 {".amc", "application/x-mpeg"}, 42 {".application", "application/x-ms-application"}, 43 {".art", "image/x-jg"}, 44 {".asa", "application/xml"}, 45 {".asax", "application/xml"}, 46 {".ascx", "application/xml"}, 47 {".asd", "application/octet-stream"}, 48 {".asf", "video/x-ms-asf"}, 49 {".ashx", "application/xml"}, 50 {".asi", "application/octet-stream"}, 51 {".asm", "text/plain"}, 52 {".asmx", "application/xml"}, 53 {".aspx", "application/xml"}, 54 {".asr", "video/x-ms-asf"}, 55 {".asx", "video/x-ms-asf"}, 56 {".atom", "application/atom+xml"}, 57 {".au", "audio/basic"}, 58 {".avi", "video/x-msvideo"}, 59 {".axs", "application/olescript"}, 60 {".bas", "text/plain"}, 61 {".bcpio", "application/x-bcpio"}, 62 {".bin", "application/octet-stream"}, 63 {".bmp", "image/bmp"}, 64 {".c", "text/plain"}, 65 {".cab", "application/octet-stream"}, 66 {".caf", "audio/x-caf"}, 67 {".calx", "application/vnd.ms-office.calx"}, 68 {".cat", "application/vnd.ms-pki.seccat"}, 69 {".cc", "text/plain"}, 70 {".cd", "text/plain"}, 71 {".cdda", "audio/aiff"}, 72 {".cdf", "application/x-cdf"}, 73 {".cer", "application/x-x509-ca-cert"}, 74 {".chm", "application/octet-stream"}, 75 {".class", "application/x-java-applet"}, 76 {".clp", "application/x-msclip"}, 77 {".cmx", "image/x-cmx"}, 78 {".cnf", "text/plain"}, 79 {".cod", "image/cis-cod"}, 80 {".config", "application/xml"}, 81 {".contact", "text/x-ms-contact"}, 82 {".coverage", "application/xml"}, 83 {".cpio", "application/x-cpio"}, 84 {".cpp", "text/plain"}, 85 {".crd", "application/x-mscardfile"}, 86 {".crl", "application/pkix-crl"}, 87 {".crt", "application/x-x509-ca-cert"}, 88 {".cs", "text/plain"}, 89 {".csdproj", "text/plain"}, 90 {".csh", "application/x-csh"}, 91 {".csproj", "text/plain"}, 92 {".css", "text/css"}, 93 {".csv", "text/csv"}, 94 {".cur", "application/octet-stream"}, 95 {".cxx", "text/plain"}, 96 {".dat", "application/octet-stream"}, 97 {".datasource", "application/xml"}, 98 {".dbproj", "text/plain"}, 99 {".dcr", "application/x-director"}, 100 {".def", "text/plain"}, 101 {".deploy", "application/octet-stream"}, 102 {".der", "application/x-x509-ca-cert"}, 103 {".dgml", "application/xml"}, 104 {".dib", "image/bmp"}, 105 {".dif", "video/x-dv"}, 106 {".dir", "application/x-director"}, 107 {".disco", "text/xml"}, 108 {".dll", "application/x-msdownload"}, 109 {".dll.config", "text/xml"}, 110 {".dlm", "text/dlm"}, 111 {".doc", "application/msword"}, 112 {".docm", "application/vnd.ms-word.document.macroEnabled.12"}, 113 {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, 114 {".dot", "application/msword"}, 115 {".dotm", "application/vnd.ms-word.template.macroEnabled.12"}, 116 {".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"}, 117 {".dsp", "application/octet-stream"}, 118 {".dsw", "text/plain"}, 119 {".dtd", "text/xml"}, 120 {".dtsConfig", "text/xml"}, 121 {".dv", "video/x-dv"}, 122 {".dvi", "application/x-dvi"}, 123 {".dwf", "drawing/x-dwf"}, 124 {".dwp", "application/octet-stream"}, 125 {".dxr", "application/x-director"}, 126 {".eml", "message/rfc822"}, 127 {".emz", "application/octet-stream"}, 128 {".eot", "application/octet-stream"}, 129 {".eps", "application/postscript"}, 130 {".etl", "application/etl"}, 131 {".etx", "text/x-setext"}, 132 {".evy", "application/envoy"}, 133 {".exe", "application/octet-stream"}, 134 {".exe.config", "text/xml"}, 135 {".fdf", "application/vnd.fdf"}, 136 {".fif", "application/fractals"}, 137 {".filters", "Application/xml"}, 138 {".fla", "application/octet-stream"}, 139 {".flr", "x-world/x-vrml"}, 140 {".flv", "video/x-flv"}, 141 {".fsscript", "application/fsharp-script"}, 142 {".fsx", "application/fsharp-script"}, 143 {".generictest", "application/xml"}, 144 {".gif", "image/gif"}, 145 {".group", "text/x-ms-group"}, 146 {".gsm", "audio/x-gsm"}, 147 {".gtar", "application/x-gtar"}, 148 {".gz", "application/x-gzip"}, 149 {".h", "text/plain"}, 150 {".hdf", "application/x-hdf"}, 151 {".hdml", "text/x-hdml"}, 152 {".hhc", "application/x-oleobject"}, 153 {".hhk", "application/octet-stream"}, 154 {".hhp", "application/octet-stream"}, 155 {".hlp", "application/winhlp"}, 156 {".hpp", "text/plain"}, 157 {".hqx", "application/mac-binhex40"}, 158 {".hta", "application/hta"}, 159 {".htc", "text/x-component"}, 160 {".htm", "text/html"}, 161 {".html", "text/html"}, 162 {".htt", "text/webviewhtml"}, 163 {".hxa", "application/xml"}, 164 {".hxc", "application/xml"}, 165 {".hxd", "application/octet-stream"}, 166 {".hxe", "application/xml"}, 167 {".hxf", "application/xml"}, 168 {".hxh", "application/octet-stream"}, 169 {".hxi", "application/octet-stream"}, 170 {".hxk", "application/xml"}, 171 {".hxq", "application/octet-stream"}, 172 {".hxr", "application/octet-stream"}, 173 {".hxs", "application/octet-stream"}, 174 {".hxt", "text/html"}, 175 {".hxv", "application/xml"}, 176 {".hxw", "application/octet-stream"}, 177 {".hxx", "text/plain"}, 178 {".i", "text/plain"}, 179 {".ico", "image/x-icon"}, 180 {".ics", "application/octet-stream"}, 181 {".idl", "text/plain"}, 182 {".ief", "image/ief"}, 183 {".iii", "application/x-iphone"}, 184 {".inc", "text/plain"}, 185 {".inf", "application/octet-stream"}, 186 {".inl", "text/plain"}, 187 {".ins", "application/x-internet-signup"}, 188 {".ipa", "application/x-itunes-ipa"}, 189 {".ipg", "application/x-itunes-ipg"}, 190 {".ipproj", "text/plain"}, 191 {".ipsw", "application/x-itunes-ipsw"}, 192 {".iqy", "text/x-ms-iqy"}, 193 {".isp", "application/x-internet-signup"}, 194 {".ite", "application/x-itunes-ite"}, 195 {".itlp", "application/x-itunes-itlp"}, 196 {".itms", "application/x-itunes-itms"}, 197 {".itpc", "application/x-itunes-itpc"}, 198 {".IVF", "video/x-ivf"}, 199 {".jar", "application/java-archive"}, 200 {".java", "application/octet-stream"}, 201 {".jck", "application/liquidmotion"}, 202 {".jcz", "application/liquidmotion"}, 203 {".jfif", "image/pjpeg"}, 204 {".jnlp", "application/x-java-jnlp-file"}, 205 {".jpb", "application/octet-stream"}, 206 {".jpe", "image/jpeg"}, 207 {".jpeg", "image/jpeg"}, 208 {".jpg", "image/jpeg"}, 209 {".js", "application/x-javascript"}, 210 {".json", "application/json"}, 211 {".jsx", "text/jscript"}, 212 {".jsxbin", "text/plain"}, 213 {".latex", "application/x-latex"}, 214 {".library-ms", "application/windows-library+xml"}, 215 {".lit", "application/x-ms-reader"}, 216 {".loadtest", "application/xml"}, 217 {".lpk", "application/octet-stream"}, 218 {".lsf", "video/x-la-asf"}, 219 {".lst", "text/plain"}, 220 {".lsx", "video/x-la-asf"}, 221 {".lzh", "application/octet-stream"}, 222 {".m13", "application/x-msmediaview"}, 223 {".m14", "application/x-msmediaview"}, 224 {".m1v", "video/mpeg"}, 225 {".m2t", "video/vnd.dlna.mpeg-tts"}, 226 {".m2ts", "video/vnd.dlna.mpeg-tts"}, 227 {".m2v", "video/mpeg"}, 228 {".m3u", "audio/x-mpegurl"}, 229 {".m3u8", "audio/x-mpegurl"}, 230 {".m4a", "audio/m4a"}, 231 {".m4b", "audio/m4b"}, 232 {".m4p", "audio/m4p"}, 233 {".m4r", "audio/x-m4r"}, 234 {".m4v", "video/x-m4v"}, 235 {".mac", "image/x-macpaint"}, 236 {".mak", "text/plain"}, 237 {".man", "application/x-troff-man"}, 238 {".manifest", "application/x-ms-manifest"}, 239 {".map", "text/plain"}, 240 {".master", "application/xml"}, 241 {".mda", "application/msaccess"}, 242 {".mdb", "application/x-msaccess"}, 243 {".mde", "application/msaccess"}, 244 {".mdp", "application/octet-stream"}, 245 {".me", "application/x-troff-me"}, 246 {".mfp", "application/x-shockwave-flash"}, 247 {".mht", "message/rfc822"}, 248 {".mhtml", "message/rfc822"}, 249 {".mid", "audio/mid"}, 250 {".midi", "audio/mid"}, 251 {".mix", "application/octet-stream"}, 252 {".mk", "text/plain"}, 253 {".mmf", "application/x-smaf"}, 254 {".mno", "text/xml"}, 255 {".mny", "application/x-msmoney"}, 256 {".mod", "video/mpeg"}, 257 {".mov", "video/quicktime"}, 258 {".movie", "video/x-sgi-movie"}, 259 {".mp2", "video/mpeg"}, 260 {".mp2v", "video/mpeg"}, 261 {".mp3", "audio/mpeg"}, 262 {".mp4", "video/mp4"}, 263 {".mp4v", "video/mp4"}, 264 {".mpa", "video/mpeg"}, 265 {".mpe", "video/mpeg"}, 266 {".mpeg", "video/mpeg"}, 267 {".mpf", "application/vnd.ms-mediapackage"}, 268 {".mpg", "video/mpeg"}, 269 {".mpp", "application/vnd.ms-project"}, 270 {".mpv2", "video/mpeg"}, 271 {".mqv", "video/quicktime"}, 272 {".ms", "application/x-troff-ms"}, 273 {".msi", "application/octet-stream"}, 274 {".mso", "application/octet-stream"}, 275 {".mts", "video/vnd.dlna.mpeg-tts"}, 276 {".mtx", "application/xml"}, 277 {".mvb", "application/x-msmediaview"}, 278 {".mvc", "application/x-miva-compiled"}, 279 {".mxp", "application/x-mmxp"}, 280 {".nc", "application/x-netcdf"}, 281 {".nsc", "video/x-ms-asf"}, 282 {".nws", "message/rfc822"}, 283 {".ocx", "application/octet-stream"}, 284 {".oda", "application/oda"}, 285 {".odc", "text/x-ms-odc"}, 286 {".odh", "text/plain"}, 287 {".odl", "text/plain"}, 288 {".odp", "application/vnd.oasis.opendocument.presentation"}, 289 {".ods", "application/oleobject"}, 290 {".odt", "application/vnd.oasis.opendocument.text"}, 291 {".one", "application/onenote"}, 292 {".onea", "application/onenote"}, 293 {".onepkg", "application/onenote"}, 294 {".onetmp", "application/onenote"}, 295 {".onetoc", "application/onenote"}, 296 {".onetoc2", "application/onenote"}, 297 {".orderedtest", "application/xml"}, 298 {".osdx", "application/opensearchdescription+xml"}, 299 {".p10", "application/pkcs10"}, 300 {".p12", "application/x-pkcs12"}, 301 {".p7b", "application/x-pkcs7-certificates"}, 302 {".p7c", "application/pkcs7-mime"}, 303 {".p7m", "application/pkcs7-mime"}, 304 {".p7r", "application/x-pkcs7-certreqresp"}, 305 {".p7s", "application/pkcs7-signature"}, 306 {".pbm", "image/x-portable-bitmap"}, 307 {".pcast", "application/x-podcast"}, 308 {".pct", "image/pict"}, 309 {".pcx", "application/octet-stream"}, 310 {".pcz", "application/octet-stream"}, 311 {".pdf", "application/pdf"}, 312 {".pfb", "application/octet-stream"}, 313 {".pfm", "application/octet-stream"}, 314 {".pfx", "application/x-pkcs12"}, 315 {".pgm", "image/x-portable-graymap"}, 316 {".pic", "image/pict"}, 317 {".pict", "image/pict"}, 318 {".pkgdef", "text/plain"}, 319 {".pkgundef", "text/plain"}, 320 {".pko", "application/vnd.ms-pki.pko"}, 321 {".pls", "audio/scpls"}, 322 {".pma", "application/x-perfmon"}, 323 {".pmc", "application/x-perfmon"}, 324 {".pml", "application/x-perfmon"}, 325 {".pmr", "application/x-perfmon"}, 326 {".pmw", "application/x-perfmon"}, 327 {".png", "image/png"}, 328 {".pnm", "image/x-portable-anymap"}, 329 {".pnt", "image/x-macpaint"}, 330 {".pntg", "image/x-macpaint"}, 331 {".pnz", "image/png"}, 332 {".pot", "application/vnd.ms-powerpoint"}, 333 {".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"}, 334 {".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"}, 335 {".ppa", "application/vnd.ms-powerpoint"}, 336 {".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"}, 337 {".ppm", "image/x-portable-pixmap"}, 338 {".pps", "application/vnd.ms-powerpoint"}, 339 {".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"}, 340 {".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"}, 341 {".ppt", "application/vnd.ms-powerpoint"}, 342 {".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"}, 343 {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, 344 {".prf", "application/pics-rules"}, 345 {".prm", "application/octet-stream"}, 346 {".prx", "application/octet-stream"}, 347 {".ps", "application/postscript"}, 348 {".psc1", "application/PowerShell"}, 349 {".psd", "application/octet-stream"}, 350 {".psess", "application/xml"}, 351 {".psm", "application/octet-stream"}, 352 {".psp", "application/octet-stream"}, 353 {".pub", "application/x-mspublisher"}, 354 {".pwz", "application/vnd.ms-powerpoint"}, 355 {".qht", "text/x-html-insertion"}, 356 {".qhtm", "text/x-html-insertion"}, 357 {".qt", "video/quicktime"}, 358 {".qti", "image/x-quicktime"}, 359 {".qtif", "image/x-quicktime"}, 360 {".qtl", "application/x-quicktimeplayer"}, 361 {".qxd", "application/octet-stream"}, 362 {".ra", "audio/x-pn-realaudio"}, 363 {".ram", "audio/x-pn-realaudio"}, 364 {".rar", "application/octet-stream"}, 365 {".ras", "image/x-cmu-raster"}, 366 {".rat", "application/rat-file"}, 367 {".rc", "text/plain"}, 368 {".rc2", "text/plain"}, 369 {".rct", "text/plain"}, 370 {".rdlc", "application/xml"}, 371 {".resx", "application/xml"}, 372 {".rf", "image/vnd.rn-realflash"}, 373 {".rgb", "image/x-rgb"}, 374 {".rgs", "text/plain"}, 375 {".rm", "application/vnd.rn-realmedia"}, 376 {".rmi", "audio/mid"}, 377 {".rmp", "application/vnd.rn-rn_music_package"}, 378 {".roff", "application/x-troff"}, 379 {".rpm", "audio/x-pn-realaudio-plugin"}, 380 {".rqy", "text/x-ms-rqy"}, 381 {".rtf", "application/rtf"}, 382 {".rtx", "text/richtext"}, 383 {".ruleset", "application/xml"}, 384 {".s", "text/plain"}, 385 {".safariextz", "application/x-safari-safariextz"}, 386 {".scd", "application/x-msschedule"}, 387 {".sct", "text/scriptlet"}, 388 {".sd2", "audio/x-sd2"}, 389 {".sdp", "application/sdp"}, 390 {".sea", "application/octet-stream"}, 391 {".searchConnector-ms", "application/windows-search-connector+xml"}, 392 {".setpay", "application/set-payment-initiation"}, 393 {".setreg", "application/set-registration-initiation"}, 394 {".settings", "application/xml"}, 395 {".sgimb", "application/x-sgimb"}, 396 {".sgml", "text/sgml"}, 397 {".sh", "application/x-sh"}, 398 {".shar", "application/x-shar"}, 399 {".shtml", "text/html"}, 400 {".sit", "application/x-stuffit"}, 401 {".sitemap", "application/xml"}, 402 {".skin", "application/xml"}, 403 {".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"}, 404 {".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"}, 405 {".slk", "application/vnd.ms-excel"}, 406 {".sln", "text/plain"}, 407 {".slupkg-ms", "application/x-ms-license"}, 408 {".smd", "audio/x-smd"}, 409 {".smi", "application/octet-stream"}, 410 {".smx", "audio/x-smd"}, 411 {".smz", "audio/x-smd"}, 412 {".snd", "audio/basic"}, 413 {".snippet", "application/xml"}, 414 {".snp", "application/octet-stream"}, 415 {".sol", "text/plain"}, 416 {".sor", "text/plain"}, 417 {".spc", "application/x-pkcs7-certificates"}, 418 {".spl", "application/futuresplash"}, 419 {".src", "application/x-wais-source"}, 420 {".srf", "text/plain"}, 421 {".SSISDeploymentManifest", "text/xml"}, 422 {".ssm", "application/streamingmedia"}, 423 {".sst", "application/vnd.ms-pki.certstore"}, 424 {".stl", "application/vnd.ms-pki.stl"}, 425 {".sv4cpio", "application/x-sv4cpio"}, 426 {".sv4crc", "application/x-sv4crc"}, 427 {".svc", "application/xml"}, 428 {".swf", "application/x-shockwave-flash"}, 429 {".t", "application/x-troff"}, 430 {".tar", "application/x-tar"}, 431 {".tcl", "application/x-tcl"}, 432 {".testrunconfig", "application/xml"}, 433 {".testsettings", "application/xml"}, 434 {".tex", "application/x-tex"}, 435 {".texi", "application/x-texinfo"}, 436 {".texinfo", "application/x-texinfo"}, 437 {".tgz", "application/x-compressed"}, 438 {".thmx", "application/vnd.ms-officetheme"}, 439 {".thn", "application/octet-stream"}, 440 {".tif", "image/tiff"}, 441 {".tiff", "image/tiff"}, 442 {".tlh", "text/plain"}, 443 {".tli", "text/plain"}, 444 {".toc", "application/octet-stream"}, 445 {".tr", "application/x-troff"}, 446 {".trm", "application/x-msterminal"}, 447 {".trx", "application/xml"}, 448 {".ts", "video/vnd.dlna.mpeg-tts"}, 449 {".tsv", "text/tab-separated-values"}, 450 {".ttf", "application/octet-stream"}, 451 {".tts", "video/vnd.dlna.mpeg-tts"}, 452 {".txt", "text/plain"}, 453 {".u32", "application/octet-stream"}, 454 {".uls", "text/iuls"}, 455 {".user", "text/plain"}, 456 {".ustar", "application/x-ustar"}, 457 {".vb", "text/plain"}, 458 {".vbdproj", "text/plain"}, 459 {".vbk", "video/mpeg"}, 460 {".vbproj", "text/plain"}, 461 {".vbs", "text/vbscript"}, 462 {".vcf", "text/x-vcard"}, 463 {".vcproj", "Application/xml"}, 464 {".vcs", "text/plain"}, 465 {".vcxproj", "Application/xml"}, 466 {".vddproj", "text/plain"}, 467 {".vdp", "text/plain"}, 468 {".vdproj", "text/plain"}, 469 {".vdx", "application/vnd.ms-visio.viewer"}, 470 {".vml", "text/xml"}, 471 {".vscontent", "application/xml"}, 472 {".vsct", "text/xml"}, 473 {".vsd", "application/vnd.visio"}, 474 {".vsi", "application/ms-vsi"}, 475 {".vsix", "application/vsix"}, 476 {".vsixlangpack", "text/xml"}, 477 {".vsixmanifest", "text/xml"}, 478 {".vsmdi", "application/xml"}, 479 {".vspscc", "text/plain"}, 480 {".vss", "application/vnd.visio"}, 481 {".vsscc", "text/plain"}, 482 {".vssettings", "text/xml"}, 483 {".vssscc", "text/plain"}, 484 {".vst", "application/vnd.visio"}, 485 {".vstemplate", "text/xml"}, 486 {".vsto", "application/x-ms-vsto"}, 487 {".vsw", "application/vnd.visio"}, 488 {".vsx", "application/vnd.visio"}, 489 {".vtx", "application/vnd.visio"}, 490 {".wav", "audio/wav"}, 491 {".wave", "audio/wav"}, 492 {".wax", "audio/x-ms-wax"}, 493 {".wbk", "application/msword"}, 494 {".wbmp", "image/vnd.wap.wbmp"}, 495 {".wcm", "application/vnd.ms-works"}, 496 {".wdb", "application/vnd.ms-works"}, 497 {".wdp", "image/vnd.ms-photo"}, 498 {".webarchive", "application/x-safari-webarchive"}, 499 {".webtest", "application/xml"}, 500 {".wiq", "application/xml"}, 501 {".wiz", "application/msword"}, 502 {".wks", "application/vnd.ms-works"}, 503 {".WLMP", "application/wlmoviemaker"}, 504 {".wlpginstall", "application/x-wlpg-detect"}, 505 {".wlpginstall3", "application/x-wlpg3-detect"}, 506 {".wm", "video/x-ms-wm"}, 507 {".wma", "audio/x-ms-wma"}, 508 {".wmd", "application/x-ms-wmd"}, 509 {".wmf", "application/x-msmetafile"}, 510 {".wml", "text/vnd.wap.wml"}, 511 {".wmlc", "application/vnd.wap.wmlc"}, 512 {".wmls", "text/vnd.wap.wmlscript"}, 513 {".wmlsc", "application/vnd.wap.wmlscriptc"}, 514 {".wmp", "video/x-ms-wmp"}, 515 {".wmv", "video/x-ms-wmv"}, 516 {".wmx", "video/x-ms-wmx"}, 517 {".wmz", "application/x-ms-wmz"}, 518 {".wpl", "application/vnd.ms-wpl"}, 519 {".wps", "application/vnd.ms-works"}, 520 {".wri", "application/x-mswrite"}, 521 {".wrl", "x-world/x-vrml"}, 522 {".wrz", "x-world/x-vrml"}, 523 {".wsc", "text/scriptlet"}, 524 {".wsdl", "text/xml"}, 525 {".wvx", "video/x-ms-wvx"}, 526 {".x", "application/directx"}, 527 {".xaf", "x-world/x-vrml"}, 528 {".xaml", "application/xaml+xml"}, 529 {".xap", "application/x-silverlight-app"}, 530 {".xbap", "application/x-ms-xbap"}, 531 {".xbm", "image/x-xbitmap"}, 532 {".xdr", "text/plain"}, 533 {".xht", "application/xhtml+xml"}, 534 {".xhtml", "application/xhtml+xml"}, 535 {".xla", "application/vnd.ms-excel"}, 536 {".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"}, 537 {".xlc", "application/vnd.ms-excel"}, 538 {".xld", "application/vnd.ms-excel"}, 539 {".xlk", "application/vnd.ms-excel"}, 540 {".xll", "application/vnd.ms-excel"}, 541 {".xlm", "application/vnd.ms-excel"}, 542 {".xls", "application/vnd.ms-excel"}, 543 {".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"}, 544 {".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"}, 545 {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, 546 {".xlt", "application/vnd.ms-excel"}, 547 {".xltm", "application/vnd.ms-excel.template.macroEnabled.12"}, 548 {".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"}, 549 {".xlw", "application/vnd.ms-excel"}, 550 {".xml", "text/xml"}, 551 {".xmta", "application/xml"}, 552 {".xof", "x-world/x-vrml"}, 553 {".XOML", "text/plain"}, 554 {".xpm", "image/x-xpixmap"}, 555 {".xps", "application/vnd.ms-xpsdocument"}, 556 {".xrm-ms", "text/xml"}, 557 {".xsc", "application/xml"}, 558 {".xsd", "text/xml"}, 559 {".xsf", "text/xml"}, 560 {".xsl", "text/xml"}, 561 {".xslt", "text/xml"}, 562 {".xsn", "application/octet-stream"}, 563 {".xss", "application/xml"}, 564 {".xtp", "application/octet-stream"}, 565 {".xwd", "image/x-xwindowdump"}, 566 {".z", "application/x-compress"}, 567 {".zip", "application/x-zip-compressed"} 568 }; 570 569 571 public static string GetMimeType (string extension) 572 { 570 public static string GetMimeType (string extension) { 573 571 if (extension == null) { 574 572 throw new ArgumentNullException ("extension"); … … 585 583 } 586 584 } 587 -
binary-improvements/MapRendering/Web/OpenID.cs
r318 r325 5 5 using System.Net; 6 6 using System.Net.Security; 7 using System.Reflection; 8 using System.Security.Cryptography.X509Certificates; 7 9 using System.Text; 8 10 using System.Text.RegularExpressions; 9 using System.Security.Cryptography.X509Certificates; 10 using System.Reflection; 11 12 namespace AllocsFixes.NetConnections.Servers.Web 13 { 11 12 namespace AllocsFixes.NetConnections.Servers.Web { 14 13 public static class OpenID { 15 14 private const string STEAM_LOGIN = "https://steamcommunity.com/openid/login"; 16 private static Regex steamIdUrlMatcher = new Regex (@"^https?:\/\/steamcommunity\.com\/openid\/id\/([0-9]{17,18})"); 17 18 private static readonly X509Certificate2 caCert = new X509Certificate2 (Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location) + "/steam-rootca.cer"); 19 private static readonly X509Certificate2 caIntermediateCert = new X509Certificate2 (Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location) + "/steam-intermediate.cer"); 15 16 private static readonly Regex steamIdUrlMatcher = 17 new Regex (@"^https?:\/\/steamcommunity\.com\/openid\/id\/([0-9]{17,18})"); 18 19 private static readonly X509Certificate2 caCert = 20 new X509Certificate2 (Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location) + 21 "/steam-rootca.cer"); 22 23 private static readonly X509Certificate2 caIntermediateCert = 24 new X509Certificate2 (Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location) + 25 "/steam-intermediate.cer"); 20 26 21 27 private static readonly bool verboseSsl = false; 22 public static bool debugOpenId = false;28 public static bool debugOpenId; 23 29 24 30 static OpenID () { 25 for (int i = 0; i < System.Environment.GetCommandLineArgs ().Length; i++) {26 if ( System.Environment.GetCommandLineArgs () [i].EqualsCaseInsensitive ("-debugopenid")) {31 for (int i = 0; i < Environment.GetCommandLineArgs ().Length; i++) { 32 if (Environment.GetCommandLineArgs () [i].EqualsCaseInsensitive ("-debugopenid")) { 27 33 debugOpenId = true; 28 34 } … … 34 40 Log.Out ("Steam certificate: No error (1)"); 35 41 } 42 36 43 return true; 37 44 } … … 49 56 Log.Out ("Steam certificate: No error (2)"); 50 57 } 58 51 59 return true; 52 60 } … … 58 66 Log.Out ("Steam certificate: No error (3)"); 59 67 } 68 60 69 return true; 61 70 } … … 66 75 Log.Out ("Validating cert: " + chainEl.Certificate.Subject); 67 76 } 77 68 78 // Iterate all status flags of the current cert 69 79 foreach (X509ChainStatus chainStatus in chainEl.ChainElementStatus) { … … 71 81 Log.Out (" Status: " + chainStatus.Status); 72 82 } 83 73 84 if (chainStatus.Status == X509ChainStatusFlags.NoError) { 74 85 // This status is not an error, skip 75 86 continue; 76 87 } 88 77 89 if (chainStatus.Status == X509ChainStatusFlags.UntrustedRoot && chainEl.Certificate == caCert) { 78 90 // This status is about the cert being an untrusted root certificate but the certificate is one of those we added, ignore 79 91 continue; 80 92 } 93 81 94 // This status is an error, print information 82 Log.Warning ("Steam certificate error: " + chainEl.Certificate.Subject + " ### Error: " + chainStatus.Status); 95 Log.Warning ("Steam certificate error: " + chainEl.Certificate.Subject + " ### Error: " + 96 chainStatus.Status); 83 97 privateChain.Reset (); 84 98 return false; … … 87 101 88 102 foreach (X509ChainStatus chainStatus in privateChain.ChainStatus) { 89 if (chainStatus.Status != X509ChainStatusFlags.NoError && chainStatus.Status != X509ChainStatusFlags.UntrustedRoot) { 103 if (chainStatus.Status != X509ChainStatusFlags.NoError && 104 chainStatus.Status != X509ChainStatusFlags.UntrustedRoot) { 90 105 Log.Warning ("Steam certificate error: " + chainStatus.Status); 91 106 privateChain.Reset (); … … 99 114 Log.Out ("Steam certificate: No error (4)"); 100 115 } 116 101 117 return true; 102 118 }; 103 104 119 } 105 120 … … 123 138 return 0; 124 139 } 140 125 141 if (mode == "error") { 126 142 Log.Warning ("Steam OpenID login error: " + getValue (_req, "openid.error")); … … 128 144 PrintOpenIdResponse (_req); 129 145 } 146 130 147 return 0; 131 148 } 149 132 150 string steamIdString = getValue (_req, "openid.claimed_id"); 133 151 ulong steamId = 0; … … 140 158 PrintOpenIdResponse (_req); 141 159 } 160 142 161 return 0; 143 162 } … … 161 180 162 181 byte[] postData = Encoding.ASCII.GetBytes (buildUrlParams (queryParams)); 163 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (STEAM_LOGIN);182 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (STEAM_LOGIN); 164 183 request.Method = "POST"; 165 184 request.ContentType = "application/x-www-form-urlencoded"; … … 170 189 } 171 190 172 HttpWebResponse response = (HttpWebResponse) request.GetResponse ();191 HttpWebResponse response = (HttpWebResponse) request.GetResponse (); 173 192 string responseString = null; 174 193 using (Stream st = response.GetResponseStream ()) { … … 180 199 if (responseString.ToLower ().Contains ("is_valid:true")) { 181 200 return steamId; 182 } else {183 Log.Warning ("Steam OpenID login failed: {0}", responseString); 184 return 0;185 }201 } 202 203 Log.Warning ("Steam OpenID login failed: {0}", responseString); 204 return 0; 186 205 } 187 206 … … 192 211 paramsArr [i++] = kvp.Key + "=" + Uri.EscapeDataString (kvp.Value); 193 212 } 213 194 214 return string.Join ("&", paramsArr); 195 215 } … … 200 220 throw new MissingMemberException ("OpenID parameter \"" + _name + "\" missing"); 201 221 } 222 202 223 return nvc [_name]; 203 224 } … … 209 230 } 210 231 } 211 212 232 } 213 233 } 214 -
binary-improvements/MapRendering/Web/Web.cs
r314 r325 1 1 using System; 2 2 using System.Collections.Generic; 3 using System.Collections.Specialized;4 3 using System.IO; 5 4 using System.Net; … … 8 7 using System.Text; 9 8 using System.Threading; 9 using AllocsFixes.FileCache; 10 using AllocsFixes.NetConnections.Servers.Web.Handlers; 10 11 using UnityEngine; 11 12 12 using AllocsFixes.NetConnections.Servers.Web.Handlers; 13 14 namespace AllocsFixes.NetConnections.Servers.Web 15 { 13 namespace AllocsFixes.NetConnections.Servers.Web { 16 14 public class Web : IConsoleServer { 17 15 private const int GUEST_PERMISSION_LEVEL = 2000; 16 public static int handlingCount; 17 public static int currentHandlers; 18 public static long totalHandlingTime = 0; 18 19 private readonly HttpListener _listener = new HttpListener (); 19 private Dictionary<string, PathHandler> handlers = new Dictionary<string, PathHandler> (); 20 public static int handlingCount = 0; 21 public static int currentHandlers = 0; 22 public static long totalHandlingTime = 0; 23 private string dataFolder; 24 private bool useStaticCache = false; 25 26 public static bool isSslRedirected (HttpListenerRequest req) { 27 string proto = req.Headers ["X-Forwarded-Proto"]; 28 if (!string.IsNullOrEmpty (proto)) { 29 return proto.Equals ("https", StringComparison.OrdinalIgnoreCase); 30 } 31 32 return false; 33 } 20 private readonly string dataFolder; 21 private readonly Dictionary<string, PathHandler> handlers = new Dictionary<string, PathHandler> (); 22 private readonly bool useStaticCache; 34 23 35 24 public ConnectionHandler connectionHandler; … … 42 31 return; 43 32 } 44 if (!Directory.Exists (Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location) + "/webserver")) { 33 34 if (!Directory.Exists (Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location) + 35 "/webserver")) { 45 36 Log.Out ("Webserver not started (folder \"webserver\" not found in WebInterface mod folder)"); 46 37 return; … … 56 47 return; 57 48 } 58 59 handlers.Add ( 60 "/index.htm", 61 new SimpleRedirectHandler ("/static/index.html")); 62 handlers.Add ( 63 "/favicon.ico", 64 new SimpleRedirectHandler ("/static/favicon.ico")); 65 handlers.Add ( 49 50 handlers.Add ( 51 "/index.htm", 52 new SimpleRedirectHandler ("/static/index.html")); 53 handlers.Add ( 54 "/favicon.ico", 55 new SimpleRedirectHandler ("/static/favicon.ico")); 56 handlers.Add ( 57 "/session/", 58 new SessionHandler ( 66 59 "/session/", 67 new SessionHandler ( 68 "/session/", 69 dataFolder, 70 this) 71 ); 72 handlers.Add ( 73 "/userstatus", 74 new UserStatusHandler () 60 dataFolder, 61 this) 62 ); 63 handlers.Add ( 64 "/userstatus", 65 new UserStatusHandler () 75 66 ); 76 67 if (useStaticCache) { 77 68 handlers.Add ( 69 "/static/", 70 new StaticHandler ( 78 71 "/static/", 79 new StaticHandler ( 80 "/static/", 81 dataFolder, 82 new AllocsFixes.FileCache.SimpleCache (), 83 false) 72 dataFolder, 73 new SimpleCache (), 74 false) 84 75 ); 85 76 } else { 86 77 handlers.Add ( 78 "/static/", 79 new StaticHandler ( 87 80 "/static/", 88 new StaticHandler ( 89 "/static/", 90 dataFolder, 91 new AllocsFixes.FileCache.DirectAccess (), 92 false) 81 dataFolder, 82 new DirectAccess (), 83 false) 93 84 ); 94 85 } … … 118 109 connectionHandler = new ConnectionHandler (this); 119 110 120 _listener.Prefixes.Add ( String.Format ("http://*:{0}/", webPort + 2));111 _listener.Prefixes.Add (string.Format ("http://*:{0}/", webPort + 2)); 121 112 _listener.Start (); 122 113 123 114 SdtdConsole.Instance.RegisterServer (this); 124 115 125 _listener.BeginGetContext ( new AsyncCallback (HandleRequest), _listener);116 _listener.BeginGetContext (HandleRequest, _listener); 126 117 127 118 Log.Out ("Started Webserver on " + (webPort + 2)); … … 129 120 Log.Out ("Error in Web.ctor: " + e); 130 121 } 122 } 123 124 public void Disconnect () { 125 try { 126 _listener.Stop (); 127 _listener.Close (); 128 } catch (Exception e) { 129 Log.Out ("Error in Web.Disconnect: " + e); 130 } 131 } 132 133 public void SendLine (string line) { 134 connectionHandler.SendLine (line); 135 } 136 137 public void SendLog (string text, string trace, LogType type) { 138 // Do nothing, handled by LogBuffer internally 139 } 140 141 public static bool isSslRedirected (HttpListenerRequest req) { 142 string proto = req.Headers ["X-Forwarded-Proto"]; 143 if (!string.IsNullOrEmpty (proto)) { 144 return proto.Equals ("https", StringComparison.OrdinalIgnoreCase); 145 } 146 147 return false; 131 148 } 132 149 … … 135 152 Interlocked.Increment (ref handlingCount); 136 153 Interlocked.Increment (ref currentHandlers); 154 137 155 // MicroStopwatch msw = new MicroStopwatch (); 138 156 HttpListenerContext ctx = _listener.EndGetContext (result); 139 _listener.BeginGetContext ( new AsyncCallback (HandleRequest), _listener);157 _listener.BeginGetContext (HandleRequest, _listener); 140 158 try { 141 159 HttpListenerRequest request = ctx.Request; … … 163 181 // No game yet -> fail request 164 182 if (GameManager.Instance.World == null) { 165 response.StatusCode = (int) HttpStatusCode.ServiceUnavailable;183 response.StatusCode = (int) HttpStatusCode.ServiceUnavailable; 166 184 return; 167 185 } … … 174 192 if (request.Url.AbsolutePath.StartsWith (kvp.Key)) { 175 193 if (!kvp.Value.IsAuthorizedForHandler (conn, permissionLevel)) { 176 response.StatusCode = (int) HttpStatusCode.Forbidden;194 response.StatusCode = (int) HttpStatusCode.Forbidden; 177 195 if (conn != null) { 178 196 //Log.Out ("Web.HandleRequest: user '{0}' not allowed to access '{1}'", conn.SteamID, kvp.Value.ModuleName); 179 } else {180 //Log.Out ("Web.HandleRequest: unidentified user from '{0}' not allowed to access '{1}'", request.RemoteEndPoint.Address, kvp.Value.ModuleName);181 197 } 182 198 } else { 183 199 kvp.Value.HandleRequest (request, response, conn, permissionLevel); 184 200 } 201 185 202 return; 186 203 } … … 190 207 // Not really relevant for non-debugging purposes: 191 208 //Log.Out ("Error in Web.HandleRequest(): No handler found for path \"" + request.Url.AbsolutePath + "\""); 192 response.StatusCode = (int) HttpStatusCode.NotFound;209 response.StatusCode = (int) HttpStatusCode.NotFound; 193 210 } catch (IOException e) { 194 211 if (e.InnerException is SocketException) { 195 Log.Out ("Error in Web.HandleRequest(): Remote host closed connection: " + e.InnerException.Message); 212 Log.Out ("Error in Web.HandleRequest(): Remote host closed connection: " + 213 e.InnerException.Message); 196 214 } else { 197 215 Log.Out ("Error (IO) in Web.HandleRequest(): " + e); … … 203 221 ctx.Response.Close (); 204 222 } 223 205 224 // msw.Stop (); 206 225 // totalHandlingTime += msw.ElapsedMicroseconds; … … 223 242 if (con != null) { 224 243 _con = con; 225 return GameManager.Instance.adminTools.GetAdminToolsClientInfo (_con.SteamID.ToString ()).PermissionLevel; 244 return GameManager.Instance.adminTools.GetAdminToolsClientInfo (_con.SteamID.ToString ()) 245 .PermissionLevel; 226 246 } 227 247 } 228 248 229 249 if (_req.QueryString ["adminuser"] != null && _req.QueryString ["admintoken"] != null) { 230 WebPermissions.AdminToken admin = WebPermissions.Instance.GetWebAdmin (_req.QueryString ["adminuser"], _req.QueryString ["admintoken"]); 250 WebPermissions.AdminToken admin = WebPermissions.Instance.GetWebAdmin (_req.QueryString ["adminuser"], 251 _req.QueryString ["admintoken"]); 231 252 if (admin != null) { 232 253 return admin.permissionLevel; 233 } else {234 Log.Warning ("Invalid Admintoken used from " + _req.RemoteEndPoint.ToString ()); 235 }254 } 255 256 Log.Warning ("Invalid Admintoken used from " + _req.RemoteEndPoint); 236 257 } 237 258 … … 242 263 WebConnection con = connectionHandler.LogIn (id, _req.RemoteEndPoint.Address.ToString ()); 243 264 _con = con; 244 int level = GameManager.Instance.adminTools.GetAdminToolsClientInfo (id.ToString ()).PermissionLevel; 245 Log.Out ("Steam OpenID login from {0} with ID {1}, permission level {2}", _req.RemoteEndPoint.ToString (), con.SteamID, level); 265 int level = GameManager.Instance.adminTools.GetAdminToolsClientInfo (id.ToString ()) 266 .PermissionLevel; 267 Log.Out ("Steam OpenID login from {0} with ID {1}, permission level {2}", 268 _req.RemoteEndPoint.ToString (), con.SteamID, level); 246 269 return level; 247 } else {248 Log.Out ("Steam OpenID login failed from {0}", _req.RemoteEndPoint.ToString ()); 249 }270 } 271 272 Log.Out ("Steam OpenID login failed from {0}", _req.RemoteEndPoint.ToString ()); 250 273 } catch (Exception e) { 251 274 Log.Error ("Error validating login:"); … … 255 278 256 279 return GUEST_PERMISSION_LEVEL; 257 }258 259 public void Disconnect () {260 try {261 _listener.Stop ();262 _listener.Close ();263 } catch (Exception e) {264 Log.Out ("Error in Web.Disconnect: " + e);265 }266 }267 268 public void SendLine (string line) {269 connectionHandler.SendLine (line);270 }271 272 public void SendLog (string text, string trace, UnityEngine.LogType type) {273 // Do nothing, handled by LogBuffer internally274 280 } 275 281 … … 281 287 resp.OutputStream.Write (buf, 0, buf.Length); 282 288 } 283 284 289 } 285 290 } -
binary-improvements/MapRendering/Web/WebCommandResult.cs
r309 r325 1 1 using System; 2 2 using System.Collections.Generic; 3 using System.IO; 3 4 using System.Net; 5 using System.Net.Sockets; 4 6 using System.Text; 7 using System.Threading; 8 using AllocsFixes.JSON; 9 using AllocsFixes.NetConnections.Servers.Web.API; 10 using UnityEngine; 5 11 6 using AllocsFixes.JSON; 7 using System.IO; 8 using System.Net.Sockets; 9 using System.Threading; 10 using AllocsFixes.NetConnections.Servers.Web.API; 11 12 namespace AllocsFixes.NetConnections.Servers.Web 13 { 14 public class WebCommandResult : IConsoleConnection 15 { 12 namespace AllocsFixes.NetConnections.Servers.Web { 13 public class WebCommandResult : IConsoleConnection { 16 14 public enum ResultType { 17 15 Full, … … 20 18 } 21 19 22 public static int handlingCount = 0; 23 public static int currentHandlers = 0; 24 public static long totalHandlingTime = 0; 20 public static int handlingCount; 21 public static int currentHandlers; 22 public static long totalHandlingTime; 23 private readonly string command; 24 private readonly string parameters; 25 25 26 private HttpListenerResponse response; 27 private string command; 28 private string parameters; 29 private ResultType responseType; 26 private readonly HttpListenerResponse response; 27 private readonly ResultType responseType; 30 28 31 public WebCommandResult (string _command, string _parameters, ResultType _responseType, HttpListenerResponse _response) { 29 public WebCommandResult (string _command, string _parameters, ResultType _responseType, 30 HttpListenerResponse _response) { 32 31 Interlocked.Increment (ref handlingCount); 33 32 Interlocked.Increment (ref currentHandlers); … … 65 64 result = resultObj; 66 65 } 66 67 67 WebAPI.WriteJSON (response, result); 68 68 } 69 69 } catch (IOException e) { 70 70 if (e.InnerException is SocketException) { 71 Log.Out ("Error in WebCommandResult.SendLines(): Remote host closed connection: " + e.InnerException.Message); 71 Log.Out ("Error in WebCommandResult.SendLines(): Remote host closed connection: " + 72 e.InnerException.Message); 72 73 } else { 73 74 Log.Out ("Error (IO) in WebCommandResult.SendLines(): " + e); … … 85 86 Log.Out ("WebCommandResult.SendLines(): Took {0} µs", msw.ElapsedMicroseconds); 86 87 } 88 87 89 Interlocked.Decrement (ref currentHandlers); 88 90 } … … 93 95 } 94 96 95 public void SendLog (string _msg, string _trace, UnityEngine.LogType _type) {97 public void SendLog (string _msg, string _trace, LogType _type) { 96 98 //throw new NotImplementedException (); 97 99 } 98 100 99 public void EnableLogLevel ( UnityEngine.LogType _type, bool _enable) {101 public void EnableLogLevel (LogType _type, bool _enable) { 100 102 //throw new NotImplementedException (); 101 103 } … … 106 108 } 107 109 } 108 -
binary-improvements/MapRendering/Web/WebConnection.cs
r253 r325 1 1 using System; 2 2 using System.Collections.Generic; 3 using AllocsFixes.NetConnections.Servers.Web;4 3 using UnityEngine; 5 4 6 namespace AllocsFixes.NetConnections.Servers.Web 7 { 5 namespace AllocsFixes.NetConnections.Servers.Web { 8 6 public class WebConnection : ConsoleConnectionAbstract { 9 private string sessionId; 10 private string endpoint; 11 private ulong steamId; 12 private DateTime login; 7 private readonly DateTime login; 8 private readonly List<string> outputLines = new List<string> (); 13 9 private DateTime lastAction; 14 private List<string> outputLines = new List<string> ();10 private readonly string conDescription; 15 11 16 public string SessionID { 17 get { return sessionId; } 12 public WebConnection (string _sessionId, string _endpoint, ulong _steamId) { 13 SessionID = _sessionId; 14 Endpoint = _endpoint; 15 SteamID = _steamId; 16 login = DateTime.Now; 17 lastAction = login; 18 conDescription = "WebPanel from " + Endpoint; 18 19 } 19 20 20 public string Endpoint { 21 get { return endpoint; } 22 } 21 public string SessionID { get; private set; } 23 22 24 public ulong SteamID {25 get { return steamId; } 26 }23 public string Endpoint { get; private set; } 24 25 public ulong SteamID { get; private set; } 27 26 28 27 public TimeSpan Age { … … 30 29 } 31 30 32 33 31 public static bool CanViewAllPlayers (int _permissionLevel) { 32 bool val = false; 34 33 35 36 34 try { 35 const int defaultPermissionLevel = 0; 37 36 38 37 val = _permissionLevel <= defaultPermissionLevel; 39 38 40 foreach (WebPermissions.WebModulePermission wap in WebPermissions.Instance.GetModules ()) 41 if (wap.module.Trim ().ToLower () == "webapi.viewallplayers") 42 val = _permissionLevel <= wap.permissionLevel; 43 } 44 catch { } 39 foreach (WebPermissions.WebModulePermission wap in WebPermissions.Instance.GetModules ()) { 40 if (wap.module.Trim ().ToLower () == "webapi.viewallplayers") { 41 val = _permissionLevel <= wap.permissionLevel; 42 } 43 } 44 } catch { 45 } 45 46 46 47 47 return val; 48 } 48 49 49 50 50 public static bool CanViewAllClaims (int _permissionLevel) { 51 bool val = false; 51 52 52 53 53 try { 54 const int defaultPermissionLevel = 0; 54 55 55 56 val = _permissionLevel <= defaultPermissionLevel; 56 57 57 foreach (WebPermissions.WebModulePermission wap in WebPermissions.Instance.GetModules ()) 58 if (wap.module.Trim ().ToLower () == "webapi.viewallclaims") 59 val = _permissionLevel <= wap.permissionLevel; 60 } 61 catch { } 58 foreach (WebPermissions.WebModulePermission wap in WebPermissions.Instance.GetModules ()) { 59 if (wap.module.Trim ().ToLower () == "webapi.viewallclaims") { 60 val = _permissionLevel <= wap.permissionLevel; 61 } 62 } 63 } catch { 64 } 62 65 63 return val; 64 } 65 66 public WebConnection (string _sessionId, string _endpoint, ulong _steamId) { 67 this.sessionId = _sessionId; 68 this.endpoint = _endpoint; 69 this.steamId = _steamId; 70 this.login = DateTime.Now; 71 this.lastAction = this.login; 66 return val; 72 67 } 73 68 74 69 public void UpdateUsage () { 75 this.lastAction = DateTime.Now;70 lastAction = DateTime.Now; 76 71 } 77 72 78 73 public override string GetDescription () { 79 return "WebPanel from " + endpoint;74 return conDescription; 80 75 } 81 76 … … 91 86 // Do nothing, handled by LogBuffer 92 87 } 93 94 88 } 95 89 } 96 -
binary-improvements/MapRendering/Web/WebPermissions.cs
r279 r325 1 using System;2 1 using System.Collections.Generic; 3 2 using System.IO; 4 3 using System.Xml; 5 4 6 namespace AllocsFixes.NetConnections.Servers.Web 7 { 5 namespace AllocsFixes.NetConnections.Servers.Web { 8 6 public class WebPermissions { 9 private static WebPermissions instance = null;10 11 public static WebPermissions Instance {12 get {13 lock (typeof(WebPermissions)) {14 if (instance == null) {15 instance = new WebPermissions ();16 }17 return instance;18 }19 }20 }21 22 7 private const string PERMISSIONS_FILE = "webpermissions.xml"; 23 Dictionary<string, AdminToken> admintokens; 24 Dictionary<string, WebModulePermission> modules; 25 Dictionary<string, WebModulePermission> knownModules = new Dictionary<string, WebModulePermission> (); 26 WebModulePermission defaultModulePermission = new WebModulePermission ("", 0); 27 FileSystemWatcher fileWatcher; 8 private static WebPermissions instance; 9 private readonly WebModulePermission defaultModulePermission = new WebModulePermission ("", 0); 10 11 private readonly Dictionary<string, WebModulePermission> knownModules = 12 new Dictionary<string, WebModulePermission> (); 13 14 private Dictionary<string, AdminToken> admintokens; 15 private FileSystemWatcher fileWatcher; 16 17 private Dictionary<string, WebModulePermission> modules; 28 18 29 19 public WebPermissions () { … … 33 23 } 34 24 25 public static WebPermissions Instance { 26 get { 27 lock (typeof (WebPermissions)) { 28 if (instance == null) { 29 instance = new WebPermissions (); 30 } 31 32 return instance; 33 } 34 } 35 } 36 35 37 public bool ModuleAllowedWithLevel (string _module, int _level) { 36 38 WebModulePermission permInfo = GetModulePermission (_module); … … 41 43 if (IsAdmin (_name) && admintokens [_name].token == _token) { 42 44 return admintokens [_name]; 43 } else {44 return null; 45 }45 } 46 47 return null; 46 48 } 47 49 … … 50 52 return modules [_module.ToLower ()]; 51 53 } 54 52 55 return defaultModulePermission; 53 56 } … … 83 86 return result; 84 87 } 85 88 86 89 87 90 // Commands … … 99 102 if (!string.IsNullOrEmpty (_module)) { 100 103 lock (this) { 101 if (!IsKnownModule(_module)) {104 if (!IsKnownModule (_module)) { 102 105 knownModules.Add (_module, new WebModulePermission (_module, _defaultPermission)); 103 } 106 } 107 104 108 if (_defaultPermission > 0 && !modules.ContainsKey (_module.ToLower ())) { 105 109 AddModulePermission (_module, _defaultPermission); … … 114 118 return knownModules.ContainsKey (_module); 115 119 } 116 } else {117 return false; 118 }119 } 120 120 } 121 122 return false; 123 } 124 121 125 public void RemoveModulePermission (string _module, bool _save = true) { 122 126 lock (this) { … … 140 144 return result; 141 145 } 142 146 143 147 144 148 //IO Tasks … … 146 150 private void InitFileWatcher () { 147 151 fileWatcher = new FileSystemWatcher (GetFilePath (), GetFileName ()); 148 fileWatcher.Changed += new FileSystemEventHandler (OnFileChanged);149 fileWatcher.Created += new FileSystemEventHandler (OnFileChanged);150 fileWatcher.Deleted += new FileSystemEventHandler (OnFileChanged);152 fileWatcher.Changed += OnFileChanged; 153 fileWatcher.Created += OnFileChanged; 154 fileWatcher.Deleted += OnFileChanged; 151 155 fileWatcher.EnableRaisingEvents = true; 152 156 } … … 198 202 continue; 199 203 } 204 200 205 if (subChild.NodeType != XmlNodeType.Element) { 201 206 Log.Warning ("Unexpected XML node found in 'admintokens' section: " + subChild.OuterXml); … … 203 208 } 204 209 205 XmlElement lineItem = (XmlElement) subChild;210 XmlElement lineItem = (XmlElement) subChild; 206 211 207 212 if (!lineItem.HasAttribute ("name")) { 208 Log.Warning ("Ignoring admintoken-entry because of missing 'name' attribute: " + subChild.OuterXml); 213 Log.Warning ("Ignoring admintoken-entry because of missing 'name' attribute: " + 214 subChild.OuterXml); 209 215 continue; 210 216 } 211 217 212 218 if (!lineItem.HasAttribute ("token")) { 213 Log.Warning ("Ignoring admintoken-entry because of missing 'token' attribute: " + subChild.OuterXml); 219 Log.Warning ("Ignoring admintoken-entry because of missing 'token' attribute: " + 220 subChild.OuterXml); 214 221 continue; 215 222 } 216 223 217 224 if (!lineItem.HasAttribute ("permission_level")) { 218 Log.Warning ("Ignoring admintoken-entry because of missing 'permission_level' attribute: " + subChild.OuterXml); 225 Log.Warning ("Ignoring admintoken-entry because of missing 'permission_level' attribute: " + 226 subChild.OuterXml); 219 227 continue; 220 228 } … … 224 232 int permissionLevel = 2000; 225 233 if (!int.TryParse (lineItem.GetAttribute ("permission_level"), out permissionLevel)) { 226 Log.Warning ("Ignoring admintoken-entry because of invalid (non-numeric) value for 'permission_level' attribute: " + subChild.OuterXml); 227 continue; 228 } 229 230 AddAdmin (name, token, permissionLevel, false); 231 234 Log.Warning ( 235 "Ignoring admintoken-entry because of invalid (non-numeric) value for 'permission_level' attribute: " + 236 subChild.OuterXml); 237 continue; 238 } 239 240 AddAdmin (name, token, permissionLevel, false); 232 241 } 233 242 } … … 238 247 continue; 239 248 } 249 240 250 if (subChild.NodeType != XmlNodeType.Element) { 241 251 Log.Warning ("Unexpected XML node found in 'permissions' section: " + subChild.OuterXml); … … 243 253 } 244 254 245 XmlElement lineItem = (XmlElement) subChild;255 XmlElement lineItem = (XmlElement) subChild; 246 256 247 257 if (!lineItem.HasAttribute ("module")) { 248 Log.Warning ("Ignoring permission-entry because of missing 'module' attribute: " + subChild.OuterXml); 249 continue; 250 } 251 258 Log.Warning ("Ignoring permission-entry because of missing 'module' attribute: " + 259 subChild.OuterXml); 260 continue; 261 } 262 252 263 if (!lineItem.HasAttribute ("permission_level")) { 253 Log.Warning ("Ignoring permission-entry because of missing 'permission_level' attribute: " + subChild.OuterXml); 254 continue; 255 } 256 264 Log.Warning ("Ignoring permission-entry because of missing 'permission_level' attribute: " + 265 subChild.OuterXml); 266 continue; 267 } 268 257 269 int permissionLevel = 0; 258 270 if (!int.TryParse (lineItem.GetAttribute ("permission_level"), out permissionLevel)) { 259 Log.Warning ("Ignoring permission-entry because of invalid (non-numeric) value for 'permission_level' attribute: " + subChild.OuterXml); 260 continue; 261 } 262 263 AddModulePermission (lineItem.GetAttribute ("module").ToLower (), permissionLevel, false); 264 } 265 } 266 271 Log.Warning ( 272 "Ignoring permission-entry because of invalid (non-numeric) value for 'permission_level' attribute: " + 273 subChild.OuterXml); 274 continue; 275 } 276 277 AddModulePermission (lineItem.GetAttribute ("module").ToLower (), permissionLevel, false); 278 } 279 } 267 280 } 268 281 … … 273 286 fileWatcher.EnableRaisingEvents = false; 274 287 275 using (StreamWriter sw = new StreamWriter(GetFullPath ())) { 276 sw.WriteLine ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); 277 sw.WriteLine ("<webpermissions>"); 278 sw.WriteLine (); 279 sw.WriteLine (" <admintokens>"); 280 sw.WriteLine (" <!-- <token name=\"adminuser1\" token=\"supersecrettoken\" permission_level=\"0\" /> -->"); 281 foreach (AdminToken at in admintokens.Values) { 282 sw.WriteLine (string.Format (" <token name=\"{0}\" token=\"{1}\" permission_level=\"{2}\" />", at.name, at.token, at.permissionLevel)); 283 } 284 sw.WriteLine (" </admintokens>"); 285 sw.WriteLine (); 286 sw.WriteLine (" <permissions>"); 287 foreach (WebModulePermission wap in modules.Values) { 288 sw.WriteLine (string.Format (" <permission module=\"{0}\" permission_level=\"{1}\" />", wap.module, wap.permissionLevel)); 289 } 290 sw.WriteLine (" <!-- <permission module=\"web.map\" permission_level=\"1000\" /> -->"); 291 sw.WriteLine (); 292 sw.WriteLine (" <!-- <permission module=\"webapi.getlog\" permission_level=\"0\" /> -->"); 293 sw.WriteLine (" <!-- <permission module=\"webapi.executeconsolecommand\" permission_level=\"0\" /> -->"); 294 sw.WriteLine (); 295 sw.WriteLine (" <!-- <permission module=\"webapi.getstats\" permission_level=\"1000\" /> -->"); 296 sw.WriteLine (" <!-- <permission module=\"webapi.getplayersonline\" permission_level=\"1000\" /> -->"); 297 sw.WriteLine (); 298 sw.WriteLine (" <!-- <permission module=\"webapi.getplayerslocation\" permission_level=\"1000\" /> -->"); 299 sw.WriteLine (" <!-- <permission module=\"webapi.viewallplayers\" permission_level=\"1\" /> -->"); 300 sw.WriteLine (); 301 sw.WriteLine (" <!-- <permission module=\"webapi.getlandclaims\" permission_level=\"1000\" /> -->"); 302 sw.WriteLine (" <!-- <permission module=\"webapi.viewallclaims\" permission_level=\"1\" /> -->"); 303 sw.WriteLine (); 304 sw.WriteLine (" <!-- <permission module=\"webapi.getplayerinventory\" permission_level=\"1\" /> -->"); 305 sw.WriteLine (); 306 sw.WriteLine (" <!-- <permission module=\"webapi.gethostilelocation\" permission_level=\"1\" /> -->"); 307 sw.WriteLine (" <!-- <permission module=\"webapi.getanimalslocation\" permission_level=\"1\" /> -->"); 308 sw.WriteLine (" </permissions>"); 309 sw.WriteLine (); 310 sw.WriteLine ("</webpermissions>"); 288 using (StreamWriter sw = new StreamWriter (GetFullPath ())) { 289 sw.WriteLine ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); 290 sw.WriteLine ("<webpermissions>"); 291 sw.WriteLine (); 292 sw.WriteLine (" <admintokens>"); 293 sw.WriteLine ( 294 " <!-- <token name=\"adminuser1\" token=\"supersecrettoken\" permission_level=\"0\" /> -->"); 295 foreach (AdminToken at in admintokens.Values) { 296 sw.WriteLine (" <token name=\"{0}\" token=\"{1}\" permission_level=\"{2}\" />", at.name, at.token, 297 at.permissionLevel); 298 } 299 300 sw.WriteLine (" </admintokens>"); 301 sw.WriteLine (); 302 sw.WriteLine (" <permissions>"); 303 foreach (WebModulePermission wap in modules.Values) { 304 sw.WriteLine (" <permission module=\"{0}\" permission_level=\"{1}\" />", wap.module, 305 wap.permissionLevel); 306 } 307 308 sw.WriteLine (" <!-- <permission module=\"web.map\" permission_level=\"1000\" /> -->"); 309 sw.WriteLine (); 310 sw.WriteLine (" <!-- <permission module=\"webapi.getlog\" permission_level=\"0\" /> -->"); 311 sw.WriteLine ( 312 " <!-- <permission module=\"webapi.executeconsolecommand\" permission_level=\"0\" /> -->"); 313 sw.WriteLine (); 314 sw.WriteLine (" <!-- <permission module=\"webapi.getstats\" permission_level=\"1000\" /> -->"); 315 sw.WriteLine (" <!-- <permission module=\"webapi.getplayersonline\" permission_level=\"1000\" /> -->"); 316 sw.WriteLine (); 317 sw.WriteLine ( 318 " <!-- <permission module=\"webapi.getplayerslocation\" permission_level=\"1000\" /> -->"); 319 sw.WriteLine (" <!-- <permission module=\"webapi.viewallplayers\" permission_level=\"1\" /> -->"); 320 sw.WriteLine (); 321 sw.WriteLine (" <!-- <permission module=\"webapi.getlandclaims\" permission_level=\"1000\" /> -->"); 322 sw.WriteLine (" <!-- <permission module=\"webapi.viewallclaims\" permission_level=\"1\" /> -->"); 323 sw.WriteLine (); 324 sw.WriteLine (" <!-- <permission module=\"webapi.getplayerinventory\" permission_level=\"1\" /> -->"); 325 sw.WriteLine (); 326 sw.WriteLine (" <!-- <permission module=\"webapi.gethostilelocation\" permission_level=\"1\" /> -->"); 327 sw.WriteLine (" <!-- <permission module=\"webapi.getanimalslocation\" permission_level=\"1\" /> -->"); 328 sw.WriteLine (" </permissions>"); 329 sw.WriteLine (); 330 sw.WriteLine ("</webpermissions>"); 311 331 312 332 sw.Flush (); … … 318 338 319 339 320 321 340 public class AdminToken { 322 341 public string name; 342 public int permissionLevel; 323 343 public string token; 324 public int permissionLevel;325 344 326 345 public AdminToken (string _name, string _token, int _permissionLevel) { … … 340 359 } 341 360 } 342 343 344 361 } 345 362 } 346
Note:
See TracChangeset
for help on using the changeset viewer.