Changeset 326 for binary-improvements/MapRendering
- Timestamp:
- Sep 4, 2018, 2:33:52 PM (6 years ago)
- Location:
- binary-improvements/MapRendering
- Files:
-
- 19 edited
Legend:
- Unmodified
- Added
- Removed
-
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.