Changeset 326 for binary-improvements
- Timestamp:
- Sep 4, 2018, 2:33:52 PM (6 years ago)
- Location:
- binary-improvements
- Files:
-
- 36 edited
Legend:
- Unmodified
- Added
- Removed
-
binary-improvements/7dtd-server-fixes/src/ChatHookExample.cs
r325 r326 5 5 6 6 public static bool Hook (ClientInfo _cInfo, EChatType _type, string _message, string _playerName) { 7 if (!string.IsNullOrEmpty (_message)) { 8 if (_message.EqualsCaseInsensitive ("/alloc")) { 9 if (_cInfo != null) { 10 Log.Out ("Sent chat hook reply to {0}", _cInfo.playerId); 11 _cInfo.SendPackage (new NetPackageChat (EChatType.Whisper, -1, ANSWER, "", false, null)); 12 } else { 13 Log.Error ("ChatHookExample: Argument _cInfo null on message: {0}", _message); 14 } 15 16 return false; 17 } 7 if (string.IsNullOrEmpty (_message) || !_message.EqualsCaseInsensitive ("/alloc")) { 8 return true; 18 9 } 19 10 20 return true; 11 if (_cInfo != null) { 12 Log.Out ("Sent chat hook reply to {0}", _cInfo.playerId); 13 _cInfo.SendPackage (new NetPackageChat (EChatType.Whisper, -1, ANSWER, "", false, null)); 14 } else { 15 Log.Error ("ChatHookExample: Argument _cInfo null on message: {0}", _message); 16 } 17 18 return false; 19 21 20 } 22 21 } -
binary-improvements/7dtd-server-fixes/src/FileCache/MapTileCache.cs
r325 r326 54 54 try { 55 55 lock (cache) { 56 if (cache [zoomlevel].filename != null) { 57 cache [zoomlevel].data = content; 58 File.WriteAllBytes (cache [zoomlevel].filename, content); 56 if (cache [zoomlevel].filename == null) { 57 return; 59 58 } 59 60 cache [zoomlevel].data = content; 61 File.WriteAllBytes (cache [zoomlevel].filename, content); 60 62 } 61 63 } catch (Exception e) { -
binary-improvements/7dtd-server-fixes/src/JSON/JSONNull.cs
r325 r326 10 10 //Log.Out ("ParseNull enter (" + offset + ")"); 11 11 12 if (json.Substring (offset, 4).Equals ("null")) { 13 //Log.Out ("JSON:Parsed Null"); 14 offset += 4; 15 return new JSONNull (); 12 if (!json.Substring (offset, 4).Equals ("null")) { 13 throw new MalformedJSONException ("No valid null value found"); 16 14 } 17 15 18 throw new MalformedJSONException ("No valid null value found"); 16 //Log.Out ("JSON:Parsed Null"); 17 offset += 4; 18 return new JSONNull (); 19 19 } 20 20 } -
binary-improvements/7dtd-server-fixes/src/JSON/JSONObject.cs
r325 r326 104 104 //Log.Out ("JSON:Parsed Object: " + obj.ToString ()); 105 105 return obj; 106 default: 107 break; 106 108 } 107 109 } -
binary-improvements/7dtd-server-fixes/src/LandClaimList.cs
r325 r326 14 14 Dictionary<Player, List<Vector3i>> result = new Dictionary<Player, List<Vector3i>> (); 15 15 16 if (d != null) { 17 Dictionary<PersistentPlayerData, List<Vector3i>> owners = 18 new Dictionary<PersistentPlayerData, List<Vector3i>> (); 19 foreach (KeyValuePair<Vector3i, PersistentPlayerData> kvp in d) { 20 bool allowed = true; 21 if (_positionFilters != null) { 22 foreach (PositionFilter pf in _positionFilters) { 23 if (!pf (kvp.Key)) { 24 allowed = false; 25 break; 26 } 16 if (d == null) { 17 return result; 18 } 19 20 Dictionary<PersistentPlayerData, List<Vector3i>> owners = 21 new Dictionary<PersistentPlayerData, List<Vector3i>> (); 22 foreach (KeyValuePair<Vector3i, PersistentPlayerData> kvp in d) { 23 bool allowed = true; 24 if (_positionFilters != null) { 25 foreach (PositionFilter pf in _positionFilters) { 26 if (!pf (kvp.Key)) { 27 allowed = false; 28 break; 27 29 } 28 }29 30 if (allowed) {31 if (!owners.ContainsKey (kvp.Value)) {32 owners.Add (kvp.Value, new List<Vector3i> ());33 }34 35 owners [kvp.Value].Add (kvp.Key);36 30 } 37 31 } 38 32 39 foreach (KeyValuePair<PersistentPlayerData, List<Vector3i>> kvp in owners) { 40 Player p = PersistentContainer.Instance.Players [kvp.Key.PlayerId, false]; 41 if (p == null) { 42 p = new Player (kvp.Key.PlayerId); 33 if (allowed) { 34 if (!owners.ContainsKey (kvp.Value)) { 35 owners.Add (kvp.Value, new List<Vector3i> ()); 43 36 } 44 37 45 bool allowed = true; 46 if (_ownerFilters != null) { 47 foreach (OwnerFilter of in _ownerFilters) { 48 if (!of (p)) { 49 allowed = false; 50 break; 51 } 38 owners [kvp.Value].Add (kvp.Key); 39 } 40 } 41 42 foreach (KeyValuePair<PersistentPlayerData, List<Vector3i>> kvp in owners) { 43 Player p = PersistentContainer.Instance.Players [kvp.Key.PlayerId, false]; 44 if (p == null) { 45 p = new Player (kvp.Key.PlayerId); 46 } 47 48 bool allowed = true; 49 if (_ownerFilters != null) { 50 foreach (OwnerFilter of in _ownerFilters) { 51 if (!of (p)) { 52 allowed = false; 53 break; 52 54 } 53 55 } 56 } 54 57 55 if (allowed) { 56 result.Add (p, new List<Vector3i> ()); 57 foreach (Vector3i v in kvp.Value) { 58 result [p].Add (v); 59 } 58 if (allowed) { 59 result.Add (p, new List<Vector3i> ()); 60 foreach (Vector3i v in kvp.Value) { 61 result [p].Add (v); 60 62 } 61 63 } -
binary-improvements/7dtd-server-fixes/src/LiveData/Animals.cs
r325 r326 4 4 5 5 protected override EntityAnimal predicate (Entity _e) { 6 if (_e is EntityAnimal) { 7 EntityAnimal ea = (EntityAnimal) _e; 8 9 if (ea.IsAlive ()) { 10 return ea; 11 } 6 EntityAnimal ea = _e as EntityAnimal; 7 if (ea != null && ea.IsAlive ()) { 8 return ea; 12 9 } 13 10 -
binary-improvements/7dtd-server-fixes/src/LiveData/Hostiles.cs
r325 r326 4 4 5 5 protected override EntityEnemy predicate (Entity _e) { 6 if (_e is EntityEnemy) { 7 if (_e.IsAlive ()) { 8 return _e as EntityEnemy; 9 } 6 EntityEnemy enemy = _e as EntityEnemy; 7 if (enemy != null && enemy.IsAlive ()) { 8 return enemy; 10 9 } 11 10 -
binary-improvements/7dtd-server-fixes/src/PersistentData/Attributes.cs
r325 r326 5 5 public class Attributes { 6 6 private bool hideChatCommands; 7 private String hideChatCommandPrefix;7 private string hideChatCommandPrefix; 8 8 9 9 public bool HideChatCommands { -
binary-improvements/7dtd-server-fixes/src/PersistentData/Inventory.cs
r325 r326 58 58 59 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 65 if (_count > maxAllowed) { 66 Log.Out ("Player with ID " + _playerId + " has stack for \"" + name + "\" greater than allowed (" + 67 _count + " > " + maxAllowed + ")"); 68 } 69 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 77 item.icon = itemClass.GetIconName (); 78 79 item.iconcolor = AllocsUtils.ColorToHex (itemClass.GetIconTint ()); 80 81 return item; 60 if (_count <= 0 || _itemValue == null || _itemValue.Equals (ItemValue.None)) { 61 return null; 82 62 } 83 63 84 return null; 64 ItemClass itemClass = ItemClass.list [_itemValue.type]; 65 int maxAllowed = itemClass.Stacknumber.Value; 66 string name = itemClass.GetItemName (); 67 68 if (_count > maxAllowed) { 69 Log.Out ("Player with ID " + _playerId + " has stack for \"" + name + "\" greater than allowed (" + 70 _count + " > " + maxAllowed + ")"); 71 } 72 73 InvItem item; 74 if (_itemValue.HasQuality) { 75 item = new InvItem (name, _count, _itemValue.Quality, _itemValue.MaxUseTimes, _itemValue.UseTimes); 76 } else { 77 item = new InvItem (name, _count, -1, _itemValue.MaxUseTimes, _itemValue.UseTimes); 78 } 79 80 item.icon = itemClass.GetIconName (); 81 82 item.iconcolor = AllocsUtils.ColorToHex (itemClass.GetIconTint ()); 83 84 return item; 85 85 } 86 86 } -
binary-improvements/7dtd-server-fixes/src/PersistentData/PersistentContainer.cs
r325 r326 53 53 54 54 public static bool Load () { 55 if (File.Exists (GameUtils.GetSaveGameDir () + "/AllocsPeristentData.bin")) { 56 try { 57 PersistentContainer obj; 58 Stream stream = File.Open (GameUtils.GetSaveGameDir () + "/AllocsPeristentData.bin", FileMode.Open); 59 BinaryFormatter bFormatter = new BinaryFormatter (); 60 obj = (PersistentContainer) bFormatter.Deserialize (stream); 61 stream.Close (); 62 instance = obj; 63 return true; 64 } catch (Exception e) { 65 Log.Error ("Exception in PersistentContainer.Load"); 66 Log.Exception (e); 67 } 55 if (!File.Exists (GameUtils.GetSaveGameDir () + "/AllocsPeristentData.bin")) { 56 return false; 57 } 58 59 try { 60 PersistentContainer obj; 61 Stream stream = File.Open (GameUtils.GetSaveGameDir () + "/AllocsPeristentData.bin", FileMode.Open); 62 BinaryFormatter bFormatter = new BinaryFormatter (); 63 obj = (PersistentContainer) bFormatter.Deserialize (stream); 64 stream.Close (); 65 instance = obj; 66 return true; 67 } catch (Exception e) { 68 Log.Error ("Exception in PersistentContainer.Load"); 69 Log.Exception (e); 68 70 } 69 71 -
binary-improvements/7dtd-server-fixes/src/PersistentData/Player.cs
r325 r326 174 174 175 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 } 176 if (clientInfo == null) { 177 return; 178 } 179 180 Log.Out ("Player set to offline: " + steamId); 181 lastOnline = DateTime.Now; 182 try { 183 Vector3i lastPos = new Vector3i (Entity.GetPosition ()); 184 lastPositionX = lastPos.x; 185 lastPositionY = lastPos.y; 186 lastPositionZ = lastPos.z; 187 totalPlayTime += (long) (Time.timeSinceLevelLoad - Entity.CreationTimeSinceLevelLoad); 188 } catch (NullReferenceException) { 189 Log.Out ("Entity not available. Something seems to be wrong here..."); 190 } 191 192 clientInfo = null; 191 193 } 192 194 … … 206 208 207 209 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 } 210 if (_pdf.progressionData.Length <= 0) { 211 return; 212 } 213 214 using (PooledBinaryReader pbr = MemoryPools.poolBinaryReader.AllocSync (false)) { 215 pbr.SetBaseStream (_pdf.progressionData); 216 Progression p = Progression.Read (pbr, null); 217 expToNextLevel = (uint) p.ExpToNextLevel; 218 level = p.Level; 215 219 } 216 220 } -
binary-improvements/7dtd-server-fixes/src/PersistentData/Players.cs
r325 r326 6 6 [Serializable] 7 7 public class Players { 8 private readonly Dictionary<string, Player> players = new Dictionary<string,Player> ();8 private readonly Dictionary<string, Player> players = new CaseInsensitiveStringDictionary<Player> (); 9 9 10 10 public Player this [string steamId, bool create] { … … 18 18 } 19 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; 20 if (!create || steamId.Length != 17) { 21 return null; 25 22 } 26 23 27 return null; 24 Log.Out ("Created new player entry for ID: " + steamId); 25 Player p = new Player (steamId); 26 players.Add (steamId, p); 27 return p; 28 28 } 29 29 } … … 56 56 } 57 57 58 int entityId = -1;58 int entityId; 59 59 if (int.TryParse (_nameOrId, out entityId)) { 60 60 foreach (KeyValuePair<string, Player> kvp in players) { … … 65 65 } 66 66 67 _nameOrId = _nameOrId.ToLower ();68 67 foreach (KeyValuePair<string, Player> kvp in players) { 69 string name = kvp.Value.Name .ToLower ();68 string name = kvp.Value.Name; 70 69 if (_ignoreColorCodes) { 71 70 name = Regex.Replace (name, "\\[[0-9a-fA-F]{6}\\]", ""); 72 71 } 73 72 74 if (kvp.Value.IsOnline && name.Equals (_nameOrId)) {73 if (kvp.Value.IsOnline && name.EqualsCaseInsensitive (_nameOrId)) { 75 74 return kvp.Key; 76 75 } -
binary-improvements/AllocsCommands/Commands/Give.cs
r325 r326 47 47 iv = new ItemValue (iv.type, true); 48 48 49 int n = int.MinValue;49 int n; 50 50 if (!int.TryParse (_params [2], out n) || n <= 0) { 51 51 SdtdConsole.Instance.Output ("Amount is not an integer or not greater than zero."); -
binary-improvements/AllocsCommands/Commands/ListKnownPlayers.cs
r325 r326 35 35 36 36 if (_params.Count == 1) { 37 long steamid = -1;38 if (_params [0]. ToLower ().Equals("-online")) {37 long steamid; 38 if (_params [0].EqualsCaseInsensitive ("-online")) { 39 39 onlineOnly = true; 40 } else if (_params [0]. ToLower ().Equals("-notbanned")) {40 } else if (_params [0].EqualsCaseInsensitive ("-notbanned")) { 41 41 notBannedOnly = true; 42 42 } else if (_params [0].Length == 17 && long.TryParse (_params [0], out steamid)) { 43 43 isSteamId = true; 44 44 } else { 45 nameFilter = _params [0] .ToLower ();45 nameFilter = _params [0]; 46 46 } 47 47 } … … 53 53 SdtdConsole.Instance.Output (string.Format ( 54 54 "{0}. {1}, id={2}, steamid={3}, online={4}, ip={5}, playtime={6} m, seen={7}", 55 0, p.Name, p.EntityID, nameFilter, p.IsOnline, p.IP,55 0, p.Name, p.EntityID, _params [0], p.IsOnline, p.IP, 56 56 p.TotalPlayTime / 60, 57 57 p.LastOnline.ToString ("yyyy-MM-dd HH:mm")) 58 58 ); 59 59 } else { 60 SdtdConsole.Instance.Output (string.Format ("SteamID {0} unknown!", nameFilter));60 SdtdConsole.Instance.Output (string.Format ("SteamID {0} unknown!", _params [0])); 61 61 } 62 62 } else { … … 68 68 (!onlineOnly || p.IsOnline) 69 69 && (!notBannedOnly || !admTools.IsBanned (sid)) 70 && (nameFilter.Length == 0 || p.Name. ToLower ().Contains(nameFilter))70 && (nameFilter.Length == 0 || p.Name.ContainsCaseInsensitive (nameFilter)) 71 71 ) { 72 72 SdtdConsole.Instance.Output (string.Format ( -
binary-improvements/AllocsCommands/Commands/ListLandProtection.cs
r325 r326 27 27 try { 28 28 if (_senderInfo.RemoteClientInfo != null) { 29 if (_params.Count >= 1 && _params [0]. ToLower ().Equals("nearby")) {29 if (_params.Count >= 1 && _params [0].EqualsCaseInsensitive ("nearby")) { 30 30 _params.Add (_senderInfo.RemoteClientInfo.playerId); 31 31 } … … 50 50 long tempLong; 51 51 52 if (_params [0]. ToLower ().Equals("summary")) {52 if (_params [0].EqualsCaseInsensitive ("summary")) { 53 53 summaryOnly = true; 54 54 } else if (_params [0].Length == 17 && long.TryParse (_params [0], out tempLong)) { … … 64 64 } 65 65 } else if (_params.Count >= 2) { 66 if (_params [0]. ToLower ().Equals("nearby")) {66 if (_params [0].EqualsCaseInsensitive ("nearby")) { 67 67 try { 68 68 if (_params.Count == 3) { … … 123 123 } 124 124 125 if (st eamIdFilter.Length == 0) {125 if (string.IsNullOrEmpty (steamIdFilter)) { 126 126 SdtdConsole.Instance.Output ("Total of " + ppl.m_lpBlockMap.Count + " keystones in the game"); 127 127 } -
binary-improvements/AllocsCommands/Commands/RemoveLandProtection.cs
r325 r326 59 59 private void removeByPosition (List<string> _coords) { 60 60 try { 61 int x = int.MinValue;61 int x, y, z; 62 62 int.TryParse (_coords [0], out x); 63 int y = int.MinValue;64 63 int.TryParse (_coords [1], out y); 65 int z = int.MinValue;66 64 int.TryParse (_coords [2], out z); 67 65 -
binary-improvements/AllocsCommands/PrivateMessageConnections.cs
r325 r326 11 11 12 12 public static ClientInfo GetLastPMSenderForPlayer (ClientInfo _player) { 13 if (senderOfLastPM.ContainsKey (_player.steamId)) { 14 CSteamID recSteamId = senderOfLastPM [_player.steamId]; 15 ClientInfo recInfo = ConnectionManager.Instance.Clients.ForSteamId (recSteamId); 16 return recInfo; 13 if (!senderOfLastPM.ContainsKey (_player.steamId)) { 14 return null; 17 15 } 18 16 19 return null; 17 CSteamID recSteamId = senderOfLastPM [_player.steamId]; 18 ClientInfo recInfo = ConnectionManager.Instance.Clients.ForSteamId (recSteamId); 19 return recInfo; 20 20 } 21 21 } -
binary-improvements/MapRendering/API.cs
r325 r326 14 14 // ReSharper disable once ObjectCreationAsStatement 15 15 new Web (); 16 LogBuffer.In stance.GetType();16 LogBuffer.Init (); 17 17 } 18 18 -
binary-improvements/MapRendering/Commands/WebPermissionsCmd.cs
r325 r326 23 23 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) { 24 24 if (_params.Count >= 1) { 25 switch (_params [0].ToLower ()) { 26 case "add": 27 ExecuteAdd (_params); 28 break; 29 case "remove": 30 ExecuteRemove (_params); 31 break; 32 case "list": 33 ExecuteList (); 34 break; 35 default: 36 SdtdConsole.Instance.Output ("Invalid sub command \"" + _params [0] + "\"."); 37 return; 25 if (_params [0].EqualsCaseInsensitive ("add")) { 26 ExecuteAdd (_params); 27 } else if (_params [0].EqualsCaseInsensitive ("remove")) { 28 ExecuteRemove (_params); 29 } else if (_params [0].EqualsCaseInsensitive ("list")) { 30 ExecuteList (); 31 } else { 32 SdtdConsole.Instance.Output ("Invalid sub command \"" + _params [0] + "\"."); 38 33 } 39 34 } else { -
binary-improvements/MapRendering/Commands/WebTokens.cs
r325 r326 25 25 public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) { 26 26 if (_params.Count >= 1) { 27 switch (_params [0].ToLower ()) { 28 case "add": 29 ExecuteAdd (_params); 30 break; 31 case "remove": 32 ExecuteRemove (_params); 33 break; 34 case "list": 35 ExecuteList (); 36 break; 37 default: 38 SdtdConsole.Instance.Output ("Invalid sub command \"" + _params [0] + "\"."); 39 return; 27 if (_params [0].EqualsCaseInsensitive ("add")) { 28 ExecuteAdd (_params); 29 } else if (_params [0].EqualsCaseInsensitive ("remove")) { 30 ExecuteRemove (_params); 31 } else if (_params [0].EqualsCaseInsensitive ("list")) { 32 ExecuteList (); 33 } else { 34 SdtdConsole.Instance.Output ("Invalid sub command \"" + _params [0] + "\"."); 40 35 } 41 36 } else { -
binary-improvements/MapRendering/MapRendering/MapRenderBlockBuffer.cs
r325 r326 71 71 private void loadTextureFromFile (string _fileName) { 72 72 byte[] array = cache.LoadTile (zoomLevel, _fileName); 73 if (array == null || !blockMap.LoadImage (array) || blockMap.height != Constants.MAP_BLOCK_SIZE || 74 blockMap.width != Constants.MAP_BLOCK_SIZE) { 75 if (array != null) { 76 Log.Error ("Map image tile " + _fileName + " has been corrupted, recreating tile"); 77 } 73 if (array != null && blockMap.LoadImage (array) && blockMap.height == Constants.MAP_BLOCK_SIZE && 74 blockMap.width == Constants.MAP_BLOCK_SIZE) { 75 return; 76 } 78 77 79 if (blockMap.height != Constants.MAP_BLOCK_SIZE || blockMap.width != Constants.MAP_BLOCK_SIZE) {80 blockMap.Resize (Constants.MAP_BLOCK_SIZE, Constants.MAP_BLOCK_SIZE);81 78 if (array != null) { 79 Log.Error ("Map image tile " + _fileName + " has been corrupted, recreating tile"); 80 } 82 81 83 for (int x = 0; x < Constants.MAP_BLOCK_SIZE; x++) { 84 for (int y = 0; y < Constants.MAP_BLOCK_SIZE; y++) { 85 blockMap.SetPixel (x, y, nullColor); 86 } 82 if (blockMap.height != Constants.MAP_BLOCK_SIZE || blockMap.width != Constants.MAP_BLOCK_SIZE) { 83 blockMap.Resize (Constants.MAP_BLOCK_SIZE, Constants.MAP_BLOCK_SIZE); 84 } 85 86 for (int x = 0; x < Constants.MAP_BLOCK_SIZE; x++) { 87 for (int y = 0; y < Constants.MAP_BLOCK_SIZE; y++) { 88 blockMap.SetPixel (x, y, nullColor); 87 89 } 88 90 } -
binary-improvements/MapRendering/MapRendering/MapRendering.cs
r325 r326 104 104 Texture2D fullMapTexture = null; 105 105 106 Vector2i minChunk = default (Vector2i), maxChunk = default (Vector2i);107 Vector2i minPos = default (Vector2i), maxPos = default (Vector2i);106 Vector2i minChunk, maxChunk; 107 Vector2i minPos, maxPos; 108 108 int widthChunks, heightChunks, widthPix, heightPix; 109 109 getWorldExtent (rfm, out minChunk, out maxChunk, out minPos, out maxPos, out widthChunks, out heightChunks, … … 181 181 File.WriteAllBytes (Constants.MAP_DIRECTORY + "/map.png", array); 182 182 Object.Destroy (fullMapTexture); 183 fullMapTexture = null;184 183 } 185 184 … … 190 189 } 191 190 192 private void SaveAllBlockMaps ( object source, ElapsedEventArgs e) {191 private void SaveAllBlockMaps () { 193 192 for (int i = 0; i < Constants.ZOOMLEVELS; i++) { 194 193 zoomLevelBuffers [i].SaveBlock (); … … 215 214 msw.ResetAndRestart (); 216 215 217 if (dirtyChunks.Count > 0) { 218 List<Vector2i> keys = new List<Vector2i> (dirtyChunks.Keys); 219 List<Vector2i> chunksDone = new List<Vector2i> (); 220 221 Vector2i chunkPos = keys [0]; 222 chunksDone.Add (chunkPos); 223 224 //Log.Out ("Start Dirty: " + chunkPos); 225 226 Vector2i block = default (Vector2i), blockOffset = default (Vector2i); 227 getBlockNumber (chunkPos, out block, out blockOffset, Constants.MAP_BLOCK_TO_CHUNK_DIV, 216 if (dirtyChunks.Count <= 0) { 217 return; 218 } 219 220 List<Vector2i> keys = new List<Vector2i> (dirtyChunks.Keys); 221 List<Vector2i> chunksDone = new List<Vector2i> (); 222 223 Vector2i chunkPos = keys [0]; 224 chunksDone.Add (chunkPos); 225 226 //Log.Out ("Start Dirty: " + chunkPos); 227 228 Vector2i block, blockOffset; 229 getBlockNumber (chunkPos, out block, out blockOffset, Constants.MAP_BLOCK_TO_CHUNK_DIV, 230 Constants.MAP_CHUNK_SIZE); 231 232 zoomLevelBuffers [Constants.ZOOMLEVELS - 1].LoadBlock (block); 233 234 Vector2i v_block, v_blockOffset; 235 foreach (Vector2i v in keys) { 236 getBlockNumber (v, out v_block, out v_blockOffset, Constants.MAP_BLOCK_TO_CHUNK_DIV, 228 237 Constants.MAP_CHUNK_SIZE); 229 230 zoomLevelBuffers [Constants.ZOOMLEVELS - 1].LoadBlock (block); 231 232 Vector2i v_block = default (Vector2i), v_blockOffset = default (Vector2i); 233 foreach (Vector2i v in keys) { 234 getBlockNumber (v, out v_block, out v_blockOffset, Constants.MAP_BLOCK_TO_CHUNK_DIV, 235 Constants.MAP_CHUNK_SIZE); 236 if (v_block.Equals (block)) { 237 //Log.Out ("Dirty: " + v + " render: true"); 238 chunksDone.Add (v); 239 if (dirtyChunks [v].Length != Constants.MAP_CHUNK_SIZE * Constants.MAP_CHUNK_SIZE) { 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) { 250 dirtyChunks.Remove (v); 251 } 252 253 RenderZoomLevel (Constants.ZOOMLEVELS - 1, block); 254 255 SaveAllBlockMaps (null, null); 256 } 257 } 258 259 private void RenderZoomLevel (int level, Vector2i innerBlock) { 260 if (level > 0) { 261 Vector2i block = default (Vector2i), blockOffset = default (Vector2i); 238 if (v_block.Equals (block)) { 239 //Log.Out ("Dirty: " + v + " render: true"); 240 chunksDone.Add (v); 241 if (dirtyChunks [v].Length != Constants.MAP_CHUNK_SIZE * Constants.MAP_CHUNK_SIZE) { 242 Log.Error (string.Format ("Rendering chunk has incorrect data size of {0} instead of {1}", 243 dirtyChunks [v].Length, Constants.MAP_CHUNK_SIZE * Constants.MAP_CHUNK_SIZE)); 244 } 245 246 zoomLevelBuffers [Constants.ZOOMLEVELS - 1] 247 .SetPart (v_blockOffset, Constants.MAP_CHUNK_SIZE, dirtyChunks [v]); 248 } 249 } 250 251 foreach (Vector2i v in chunksDone) { 252 dirtyChunks.Remove (v); 253 } 254 255 RenderZoomLevel (block); 256 257 SaveAllBlockMaps (); 258 } 259 260 private void RenderZoomLevel (Vector2i innerBlock) { 261 int level = Constants.ZOOMLEVELS - 1; 262 while (level > 0) { 263 Vector2i block, blockOffset; 262 264 getBlockNumber (innerBlock, out block, out blockOffset, 2, Constants.MAP_BLOCK_SIZE / 2); 263 265 264 266 zoomLevelBuffers [level - 1].LoadBlock (block); 265 zoomLevelBuffers [level - 1].SetPart (blockOffset, Constants.MAP_BLOCK_SIZE / 2, 266 zoomLevelBuffers [level].GetHalfScaled ()); 267 268 RenderZoomLevel (level - 1, block);267 zoomLevelBuffers [level - 1].SetPart (blockOffset, Constants.MAP_BLOCK_SIZE / 2, zoomLevelBuffers [level].GetHalfScaled ()); 268 269 level = level - 1; 270 innerBlock = block; 269 271 } 270 272 } … … 290 292 291 293 private bool LoadMapInfo () { 292 if (File.Exists (Constants.MAP_DIRECTORY + "/mapinfo.json")) { 293 string json = File.ReadAllText (Constants.MAP_DIRECTORY + "/mapinfo.json", Encoding.UTF8); 294 try { 295 JSONNode node = Parser.Parse (json); 296 if (node is JSONObject) { 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 306 return true; 307 } 308 } catch (MalformedJSONException e) { 309 Log.Out ("Exception in LoadMapInfo: " + e); 310 } catch (InvalidCastException e) { 311 Log.Out ("Exception in LoadMapInfo: " + e); 312 } 294 if (!File.Exists (Constants.MAP_DIRECTORY + "/mapinfo.json")) { 295 return false; 296 } 297 298 string json = File.ReadAllText (Constants.MAP_DIRECTORY + "/mapinfo.json", Encoding.UTF8); 299 try { 300 JSONNode node = Parser.Parse (json); 301 if (node is JSONObject) { 302 JSONObject jo = (JSONObject) node; 303 if (jo.ContainsKey ("blockSize")) { 304 Constants.MAP_BLOCK_SIZE = ((JSONNumber) jo ["blockSize"]).GetInt (); 305 } 306 307 if (jo.ContainsKey ("maxZoom")) { 308 Constants.ZOOMLEVELS = ((JSONNumber) jo ["maxZoom"]).GetInt () + 1; 309 } 310 311 return true; 312 } 313 } catch (MalformedJSONException e) { 314 Log.Out ("Exception in LoadMapInfo: " + e); 315 } catch (InvalidCastException e) { 316 Log.Out ("Exception in LoadMapInfo: " + e); 313 317 } 314 318 -
binary-improvements/MapRendering/Web/API/GetLandClaims.cs
r325 r326 50 50 51 51 foreach (KeyValuePair<Player, List<Vector3i>> kvp in claims) { 52 try {52 // try { 53 53 JSONObject owner = new JSONObject (); 54 54 claimOwners.Add (owner); … … 74 74 claimsJson.Add (claim); 75 75 } 76 } catch {77 }76 // } catch { 77 // } 78 78 } 79 79 -
binary-improvements/MapRendering/Web/API/GetPlayerInventory.cs
r325 r326 75 75 76 76 internal static JSONNode GetJsonForItem (InvItem _item) { 77 if (_item != null) { 78 JSONObject jsonItem = new JSONObject (); 79 jsonItem.Add ("count", new JSONNumber (_item.count)); 80 jsonItem.Add ("name", new JSONString (_item.itemName)); 81 jsonItem.Add ("icon", new JSONString (_item.icon)); 82 jsonItem.Add ("iconcolor", new JSONString (_item.iconcolor)); 83 jsonItem.Add ("quality", new JSONNumber (_item.quality)); 84 if (_item.quality >= 0) { 85 jsonItem.Add ("qualitycolor", new JSONString (QualityInfo.GetQualityColorHex (_item.quality))); 86 } 87 88 return jsonItem; 77 if (_item == null) { 78 return new JSONNull (); 89 79 } 90 80 91 return new JSONNull (); 81 JSONObject jsonItem = new JSONObject (); 82 jsonItem.Add ("count", new JSONNumber (_item.count)); 83 jsonItem.Add ("name", new JSONString (_item.itemName)); 84 jsonItem.Add ("icon", new JSONString (_item.icon)); 85 jsonItem.Add ("iconcolor", new JSONString (_item.iconcolor)); 86 jsonItem.Add ("quality", new JSONNumber (_item.quality)); 87 if (_item.quality >= 0) { 88 jsonItem.Add ("qualitycolor", new JSONString (QualityInfo.GetQualityColorHex (_item.quality))); 89 } 90 91 return jsonItem; 92 92 93 } 93 94 } -
binary-improvements/MapRendering/Web/API/GetPlayerList.cs
r325 r326 40 40 Player p = playersList [sid, false]; 41 41 42 ulong player_steam_ID = 0L;42 ulong player_steam_ID; 43 43 if (!ulong.TryParse (sid, out player_steam_ID)) { 44 44 player_steam_ID = 0L; … … 64 64 pJson.Add ("ping", new JSONNumber (p.IsOnline ? p.ClientInfo.ping : -1)); 65 65 66 JSONBoolean banned = null;66 JSONBoolean banned; 67 67 if (admTools != null) { 68 68 banned = new JSONBoolean (admTools.IsBanned (sid)); … … 132 132 133 133 if (colType == typeof (JSONBoolean)) { 134 bool value = _filterVal.Trim ().ToLower () == "true";135 return _list.Where (line => ( line [_filterCol] as JSONBoolean).GetBool () == value);134 bool value = StringParsers.ParseBool (_filterVal); 135 return _list.Where (line => ((JSONBoolean) line [_filterCol]).GetBool () == value); 136 136 } 137 137 … … 143 143 //Log.Out ("GetPlayerList: Filter on String with Regex '" + _filterVal + "'"); 144 144 Regex matcher = new Regex (_filterVal, RegexOptions.IgnoreCase); 145 return _list.Where (line => matcher.IsMatch (( line [_filterCol] as JSONString).GetString ()));145 return _list.Where (line => matcher.IsMatch (((JSONString) line [_filterCol]).GetString ())); 146 146 } 147 147 } … … 185 185 186 186 return _list.Where (delegate (JSONObject line) { 187 double objVal = ( line [_filterCol] as JSONNumber).GetDouble ();187 double objVal = ((JSONNumber) line [_filterCol]).GetDouble (); 188 188 switch (matchType) { 189 189 case NumberMatchType.Greater: … … 216 216 if (colType == typeof (JSONNumber)) { 217 217 if (_ascending) { 218 return _list.OrderBy (line => ( line [_sortCol] as JSONNumber).GetDouble ());219 } 220 221 return _list.OrderByDescending (line => ( line [_sortCol] as JSONNumber).GetDouble ());218 return _list.OrderBy (line => ((JSONNumber) line [_sortCol]).GetDouble ()); 219 } 220 221 return _list.OrderByDescending (line => ((JSONNumber) line [_sortCol]).GetDouble ()); 222 222 } 223 223 224 224 if (colType == typeof (JSONBoolean)) { 225 225 if (_ascending) { 226 return _list.OrderBy (line => ( line [_sortCol] as JSONBoolean).GetBool ());227 } 228 229 return _list.OrderByDescending (line => ( line [_sortCol] as JSONBoolean).GetBool ());226 return _list.OrderBy (line => ((JSONBoolean) line [_sortCol]).GetBool ()); 227 } 228 229 return _list.OrderByDescending (line => ((JSONBoolean) line [_sortCol]).GetBool ()); 230 230 } 231 231 -
binary-improvements/MapRendering/Web/API/GetPlayersLocation.cs
r325 r326 31 31 32 32 if (listOffline || p.IsOnline) { 33 ulong player_steam_ID = 0L;33 ulong player_steam_ID; 34 34 if (!ulong.TryParse (sid, out player_steam_ID)) { 35 35 player_steam_ID = 0L; -
binary-improvements/MapRendering/Web/API/GetPlayersOnline.cs
r325 r326 41 41 p.Add ("totalplaytime", new JSONNumber (player != null ? player.TotalPlayTime : -1)); 42 42 p.Add ("lastonline", new JSONString (player != null ? player.LastOnline.ToString ("s") : string.Empty)); 43 p.Add ("ping", new JSONNumber (ci != null ? ci.ping : -1));43 p.Add ("ping", new JSONNumber (ci.ping)); 44 44 45 45 players.Add (p); -
binary-improvements/MapRendering/Web/API/WebAPI.cs
r325 r326 5 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 6 6 public abstract class WebAPI { 7 public readonly string Name; 8 9 protected WebAPI () { 10 Name = GetType ().Name; 11 } 12 7 13 public static void WriteJSON (HttpListenerResponse resp, JSONNode root) { 8 14 StringBuilder sb = new StringBuilder (); -
binary-improvements/MapRendering/Web/ConnectionHandler.cs
r325 r326 5 5 public class ConnectionHandler { 6 6 private readonly Dictionary<string, WebConnection> connections = new Dictionary<string, WebConnection> (); 7 private Web parent;8 9 public ConnectionHandler (Web _parent) {10 parent = _parent;11 }12 7 13 8 public WebConnection IsLoggedIn (string _sessionId, string _endpoint) { -
binary-improvements/MapRendering/Web/Handlers/ApiHandler.cs
r325 r326 7 7 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { 8 8 public class ApiHandler : PathHandler { 9 private readonly Dictionary<string, WebAPI> apis = new Dictionary<string,WebAPI> ();9 private readonly Dictionary<string, WebAPI> apis = new CaseInsensitiveStringDictionary<WebAPI> (); 10 10 private readonly string staticPart; 11 11 … … 18 18 if (ctor != null) { 19 19 WebAPI apiInstance = (WebAPI) ctor.Invoke (new object [0]); 20 addApi ( t.Name.ToLower (), apiInstance);20 addApi (apiInstance.Name, apiInstance); 21 21 } 22 22 } … … 52 52 } 53 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; 64 } 54 WebAPI api; 55 if (apis.TryGetValue (apiName, out api)) { 56 try { 57 api.HandleRequest (req, resp, user, permissionLevel); 58 return; 59 } catch (Exception e) { 60 Log.Error ("Error in ApiHandler.HandleRequest(): Handler {0} threw an exception:", api.Name); 61 Log.Exception (e); 62 resp.StatusCode = (int) HttpStatusCode.InternalServerError; 63 return; 65 64 } 66 65 } 67 66 68 67 Log.Out ("Error in ApiHandler.HandleRequest(): No handler found for API \"" + apiName + "\""); 69 68 resp.StatusCode = (int) HttpStatusCode.NotFound; -
binary-improvements/MapRendering/Web/Handlers/ItemIconHandler.cs
r325 r326 37 37 requestFileName = requestFileName.Remove (requestFileName.LastIndexOf ('.')); 38 38 39 if (icons.ContainsKey (requestFileName) && req.Url.AbsolutePath. ToLower ().EndsWith (".png")) {39 if (icons.ContainsKey (requestFileName) && req.Url.AbsolutePath.EndsWith (".png", StringComparison.OrdinalIgnoreCase)) { 40 40 resp.ContentType = MimeType.GetMimeType (".png"); 41 41 … … 128 128 foreach (string file in Directory.GetFiles (modIconsPath)) { 129 129 try { 130 if (file. ToLower ().EndsWith (".png")) {130 if (file.EndsWith (".png", StringComparison.OrdinalIgnoreCase)) { 131 131 string name = Path.GetFileNameWithoutExtension (file); 132 132 Texture2D tex = new Texture2D (1, 1, TextureFormat.ARGB32, false); -
binary-improvements/MapRendering/Web/LogBuffer.cs
r325 r326 15 15 16 16 private int listOffset; 17 18 public static void Init () { 19 if (instance == null) { 20 instance = new LogBuffer (); 21 }; 22 } 17 23 18 24 private LogBuffer () { -
binary-improvements/MapRendering/Web/OpenID.cs
r325 r326 87 87 } 88 88 89 if (chainStatus.Status == X509ChainStatusFlags.UntrustedRoot && chainEl.Certificate == caCert) {89 if (chainStatus.Status == X509ChainStatusFlags.UntrustedRoot && chainEl.Certificate.Equals (caCert)) { 90 90 // This status is about the cert being an untrusted root certificate but the certificate is one of those we added, ignore 91 91 continue; … … 149 149 150 150 string steamIdString = getValue (_req, "openid.claimed_id"); 151 ulong steamId = 0;151 ulong steamId; 152 152 Match steamIdMatch = steamIdUrlMatcher.Match (steamIdString); 153 153 if (steamIdMatch.Success) { … … 190 190 191 191 HttpWebResponse response = (HttpWebResponse) request.GetResponse (); 192 string responseString = null;192 string responseString; 193 193 using (Stream st = response.GetResponseStream ()) { 194 194 using (StreamReader str = new StreamReader (st)) { … … 197 197 } 198 198 199 if (responseString. ToLower ().Contains("is_valid:true")) {199 if (responseString.ContainsCaseInsensitive ("is_valid:true")) { 200 200 return steamId; 201 201 } -
binary-improvements/MapRendering/Web/Web.cs
r325 r326 107 107 ); 108 108 109 connectionHandler = new ConnectionHandler ( this);109 connectionHandler = new ConnectionHandler (); 110 110 111 111 _listener.Prefixes.Add (string.Format ("http://*:{0}/", webPort + 2)); … … 149 149 150 150 private void HandleRequest (IAsyncResult result) { 151 if (_listener.IsListening) { 152 Interlocked.Increment (ref handlingCount); 153 Interlocked.Increment (ref currentHandlers); 151 if (!_listener.IsListening) { 152 return; 153 } 154 155 Interlocked.Increment (ref handlingCount); 156 Interlocked.Increment (ref currentHandlers); 154 157 155 158 // MicroStopwatch msw = new MicroStopwatch (); 156 HttpListenerContext ctx = _listener.EndGetContext (result); 157 _listener.BeginGetContext (HandleRequest, _listener); 158 try { 159 HttpListenerRequest request = ctx.Request; 160 HttpListenerResponse response = ctx.Response; 161 response.SendChunked = false; 162 163 response.ProtocolVersion = new Version ("1.1"); 164 165 WebConnection conn; 166 int permissionLevel = DoAuthentication (request, out conn); 167 168 169 //Log.Out ("Login status: conn!=null: {0}, permissionlevel: {1}", conn != null, permissionLevel); 170 171 172 if (conn != null) { 173 Cookie cookie = new Cookie ("sid", conn.SessionID, "/"); 174 cookie.Expired = false; 175 cookie.Expires = new DateTime (2020, 1, 1); 176 cookie.HttpOnly = true; 177 cookie.Secure = false; 178 response.AppendCookie (cookie); 179 } 180 181 // No game yet -> fail request 182 if (GameManager.Instance.World == null) { 183 response.StatusCode = (int) HttpStatusCode.ServiceUnavailable; 184 return; 185 } 186 187 if (request.Url.AbsolutePath.Length < 2) { 188 handlers ["/index.htm"].HandleRequest (request, response, conn, permissionLevel); 189 return; 190 } else { 191 foreach (KeyValuePair<string, PathHandler> kvp in handlers) { 192 if (request.Url.AbsolutePath.StartsWith (kvp.Key)) { 193 if (!kvp.Value.IsAuthorizedForHandler (conn, permissionLevel)) { 194 response.StatusCode = (int) HttpStatusCode.Forbidden; 195 if (conn != null) { 196 //Log.Out ("Web.HandleRequest: user '{0}' not allowed to access '{1}'", conn.SteamID, kvp.Value.ModuleName); 197 } 198 } else { 199 kvp.Value.HandleRequest (request, response, conn, permissionLevel); 159 HttpListenerContext ctx = _listener.EndGetContext (result); 160 _listener.BeginGetContext (HandleRequest, _listener); 161 try { 162 HttpListenerRequest request = ctx.Request; 163 HttpListenerResponse response = ctx.Response; 164 response.SendChunked = false; 165 166 response.ProtocolVersion = new Version ("1.1"); 167 168 WebConnection conn; 169 int permissionLevel = DoAuthentication (request, out conn); 170 171 172 //Log.Out ("Login status: conn!=null: {0}, permissionlevel: {1}", conn != null, permissionLevel); 173 174 175 if (conn != null) { 176 Cookie cookie = new Cookie ("sid", conn.SessionID, "/"); 177 cookie.Expired = false; 178 cookie.Expires = new DateTime (2020, 1, 1); 179 cookie.HttpOnly = true; 180 cookie.Secure = false; 181 response.AppendCookie (cookie); 182 } 183 184 // No game yet -> fail request 185 if (GameManager.Instance.World == null) { 186 response.StatusCode = (int) HttpStatusCode.ServiceUnavailable; 187 return; 188 } 189 190 if (request.Url.AbsolutePath.Length < 2) { 191 handlers ["/index.htm"].HandleRequest (request, response, conn, permissionLevel); 192 return; 193 } else { 194 foreach (KeyValuePair<string, PathHandler> kvp in handlers) { 195 if (request.Url.AbsolutePath.StartsWith (kvp.Key)) { 196 if (!kvp.Value.IsAuthorizedForHandler (conn, permissionLevel)) { 197 response.StatusCode = (int) HttpStatusCode.Forbidden; 198 if (conn != null) { 199 //Log.Out ("Web.HandleRequest: user '{0}' not allowed to access '{1}'", conn.SteamID, kvp.Value.ModuleName); 200 200 } 201 202 return;201 } else { 202 kvp.Value.HandleRequest (request, response, conn, permissionLevel); 203 203 } 204 205 return; 204 206 } 205 207 } 206 207 // Not really relevant for non-debugging purposes: 208 //Log.Out ("Error in Web.HandleRequest(): No handler found for path \"" + request.Url.AbsolutePath + "\""); 209 response.StatusCode = (int) HttpStatusCode.NotFound; 210 } catch (IOException e) { 211 if (e.InnerException is SocketException) { 212 Log.Out ("Error in Web.HandleRequest(): Remote host closed connection: " + 213 e.InnerException.Message); 214 } else { 215 Log.Out ("Error (IO) in Web.HandleRequest(): " + e); 216 } 217 } catch (Exception e) { 218 Log.Out ("Error in Web.HandleRequest(): " + e); 219 } finally { 220 if (ctx != null && !ctx.Response.SendChunked) { 221 ctx.Response.Close (); 222 } 208 } 209 210 // Not really relevant for non-debugging purposes: 211 //Log.Out ("Error in Web.HandleRequest(): No handler found for path \"" + request.Url.AbsolutePath + "\""); 212 response.StatusCode = (int) HttpStatusCode.NotFound; 213 } catch (IOException e) { 214 if (e.InnerException is SocketException) { 215 Log.Out ("Error in Web.HandleRequest(): Remote host closed connection: " + 216 e.InnerException.Message); 217 } else { 218 Log.Out ("Error (IO) in Web.HandleRequest(): " + e); 219 } 220 } catch (Exception e) { 221 Log.Out ("Error in Web.HandleRequest(): " + e); 222 } finally { 223 if (ctx != null && !ctx.Response.SendChunked) { 224 ctx.Response.Close (); 225 } 223 226 224 227 // msw.Stop (); 225 228 // totalHandlingTime += msw.ElapsedMicroseconds; 226 229 // Log.Out ("Web.HandleRequest(): Took {0} µs", msw.ElapsedMicroseconds); 227 Interlocked.Decrement (ref currentHandlers); 228 } 230 Interlocked.Decrement (ref currentHandlers); 229 231 } 230 232 } -
binary-improvements/MapRendering/Web/WebConnection.cs
r325 r326 6 6 public class WebConnection : ConsoleConnectionAbstract { 7 7 private readonly DateTime login; 8 private readonly List<string> outputLines = new List<string> ();8 // private readonly List<string> outputLines = new List<string> (); 9 9 private DateTime lastAction; 10 10 private readonly string conDescription; … … 30 30 31 31 public static bool CanViewAllPlayers (int _permissionLevel) { 32 bool val = false;32 const int defaultPermissionLevel = 0; 33 33 34 try { 35 const int defaultPermissionLevel = 0; 34 bool val = _permissionLevel <= defaultPermissionLevel; 36 35 37 val = _permissionLevel <= defaultPermissionLevel; 38 39 foreach (WebPermissions.WebModulePermission wap in WebPermissions.Instance.GetModules ()) { 40 if (wap.module.Trim ().ToLower () == "webapi.viewallplayers") { 41 val = _permissionLevel <= wap.permissionLevel; 42 } 36 foreach (WebPermissions.WebModulePermission wap in WebPermissions.Instance.GetModules ()) { 37 if (wap.module.EqualsCaseInsensitive ("webapi.viewallplayers")) { 38 val = _permissionLevel <= wap.permissionLevel; 43 39 } 44 } catch {45 40 } 46 41 … … 49 44 50 45 public static bool CanViewAllClaims (int _permissionLevel) { 51 bool val = false;46 const int defaultPermissionLevel = 0; 52 47 53 try { 54 const int defaultPermissionLevel = 0; 48 bool val = _permissionLevel <= defaultPermissionLevel; 55 49 56 val = _permissionLevel <= defaultPermissionLevel; 57 58 foreach (WebPermissions.WebModulePermission wap in WebPermissions.Instance.GetModules ()) { 59 if (wap.module.Trim ().ToLower () == "webapi.viewallclaims") { 60 val = _permissionLevel <= wap.permissionLevel; 61 } 50 foreach (WebPermissions.WebModulePermission wap in WebPermissions.Instance.GetModules ()) { 51 if (wap.module.EqualsCaseInsensitive ("webapi.viewallclaims")) { 52 val = _permissionLevel <= wap.permissionLevel; 62 53 } 63 } catch {64 54 } 65 55 … … 76 66 77 67 public override void SendLine (string _text) { 78 outputLines.Add (_text);68 // outputLines.Add (_text); 79 69 } 80 70 81 71 public override void SendLines (List<string> _output) { 82 outputLines.AddRange (_output);72 // outputLines.AddRange (_output); 83 73 } 84 74 -
binary-improvements/MapRendering/Web/WebPermissions.cs
r325 r326 12 12 new Dictionary<string, WebModulePermission> (); 13 13 14 private Dictionary<string, AdminToken> admintokens;14 private readonly Dictionary<string, AdminToken> admintokens = new CaseInsensitiveStringDictionary<AdminToken> (); 15 15 private FileSystemWatcher fileWatcher; 16 16 17 private Dictionary<string, WebModulePermission> modules;17 private readonly Dictionary<string, WebModulePermission> modules = new CaseInsensitiveStringDictionary<WebModulePermission> (); 18 18 19 19 public WebPermissions () { … … 49 49 50 50 public WebModulePermission GetModulePermission (string _module) { 51 if (modules.ContainsKey (_module.ToLower ())) { 52 return modules [_module.ToLower ()]; 51 WebModulePermission result; 52 if (modules.TryGetValue (_module, out result)) { 53 return result; 53 54 } 54 55 … … 83 84 public AdminToken[] GetAdmins () { 84 85 AdminToken[] result = new AdminToken[admintokens.Count]; 85 admintokens. Values.CopyTo (result, 0);86 admintokens.CopyValuesTo (result); 86 87 return result; 87 88 } … … 90 91 // Commands 91 92 public void AddModulePermission (string _module, int _permissionLevel, bool _save = true) { 92 WebModulePermission p = new WebModulePermission (_module .ToLower (), _permissionLevel);93 WebModulePermission p = new WebModulePermission (_module, _permissionLevel); 93 94 lock (this) { 94 95 modules [_module] = p; … … 100 101 101 102 public void AddKnownModule (string _module, int _defaultPermission) { 102 if (!string.IsNullOrEmpty (_module)) { 103 lock (this) { 104 if (!IsKnownModule (_module)) { 105 knownModules.Add (_module, new WebModulePermission (_module, _defaultPermission)); 106 } 107 108 if (_defaultPermission > 0 && !modules.ContainsKey (_module.ToLower ())) { 109 AddModulePermission (_module, _defaultPermission); 110 } 103 if (string.IsNullOrEmpty (_module)) { 104 return; 105 } 106 107 lock (this) { 108 if (!IsKnownModule (_module)) { 109 knownModules.Add (_module, new WebModulePermission (_module, _defaultPermission)); 110 } 111 112 if (_defaultPermission > 0 && !modules.ContainsKey (_module)) { 113 AddModulePermission (_module, _defaultPermission); 111 114 } 112 115 } … … 114 117 115 118 public bool IsKnownModule (string _module) { 116 if (!string.IsNullOrEmpty (_module)) { 117 lock (this) { 118 return knownModules.ContainsKey (_module); 119 } 120 } 121 122 return false; 119 if (string.IsNullOrEmpty (_module)) { 120 return false; 121 } 122 123 lock (this) { 124 return knownModules.ContainsKey (_module); 125 } 126 123 127 } 124 128 125 129 public void RemoveModulePermission (string _module, bool _save = true) { 126 130 lock (this) { 127 modules.Remove (_module .ToLower ());131 modules.Remove (_module); 128 132 if (_save) { 129 133 Save (); … … 174 178 175 179 public void Load () { 176 admintokens = new Dictionary<string, AdminToken>();177 modules = new Dictionary<string, WebModulePermission>();180 admintokens.Clear (); 181 modules.Clear (); 178 182 179 183 if (!Utils.FileExists (GetFullPath ())) { … … 190 194 xmlDoc.Load (GetFullPath ()); 191 195 } catch (XmlException e) { 192 Log.Error ( string.Format ("Failed loading permissions file: {0}", e.Message));196 Log.Error ("Failed loading permissions file: " + e.Message); 193 197 return; 194 198 } … … 196 200 XmlNode adminToolsNode = xmlDoc.DocumentElement; 197 201 202 if (adminToolsNode == null) { 203 Log.Error ("Failed loading permissions file: No DocumentElement found"); 204 return; 205 } 206 198 207 foreach (XmlNode childNode in adminToolsNode.ChildNodes) { 199 208 if (childNode.Name == "admintokens") { … … 230 239 string name = lineItem.GetAttribute ("name"); 231 240 string token = lineItem.GetAttribute ("token"); 232 int permissionLevel = 2000;241 int permissionLevel; 233 242 if (!int.TryParse (lineItem.GetAttribute ("permission_level"), out permissionLevel)) { 234 243 Log.Warning ( … … 267 276 } 268 277 269 int permissionLevel = 0;278 int permissionLevel; 270 279 if (!int.TryParse (lineItem.GetAttribute ("permission_level"), out permissionLevel)) { 271 280 Log.Warning ( … … 275 284 } 276 285 277 AddModulePermission (lineItem.GetAttribute ("module") .ToLower (), permissionLevel, false);286 AddModulePermission (lineItem.GetAttribute ("module"), permissionLevel, false); 278 287 } 279 288 }
Note:
See TracChangeset
for help on using the changeset viewer.