using System; using System.Collections.Generic; using System.Net; using System.Text; using AllocsFixes.JSON; using System.IO; using System.Net.Sockets; using System.Threading; using AllocsFixes.NetConnections.Servers.Web.API; namespace AllocsFixes.NetConnections.Servers.Web { public class WebCommandResult : IConsoleConnection { public enum ResultType { Full, ResultOnly, Raw } public static int handlingCount = 0; public static int currentHandlers = 0; public static long totalHandlingTime = 0; private HttpListenerResponse response; private string command; private string parameters; private ResultType responseType; public WebCommandResult (string _command, string _parameters, ResultType _responseType, HttpListenerResponse _response) { Interlocked.Increment (ref handlingCount); Interlocked.Increment (ref currentHandlers); response = _response; command = _command; parameters = _parameters; responseType = _responseType; } public void SendLines (List _output) { MicroStopwatch msw = new MicroStopwatch (); StringBuilder sb = new StringBuilder (); foreach (string line in _output) { sb.AppendLine (line); } try { response.SendChunked = false; if (responseType == ResultType.Raw) { WebAPI.WriteText (response, sb.ToString ()); } else { JSONNode result; if (responseType == ResultType.ResultOnly) { result = new JSONString (sb.ToString ()); } else { JSONObject resultObj = new JSONObject (); resultObj.Add ("command", new JSONString (command)); resultObj.Add ("parameters", new JSONString (parameters)); resultObj.Add ("result", new JSONString (sb.ToString ())); result = resultObj; } WebAPI.WriteJSON (response, result); } } catch (IOException e) { if (e.InnerException is SocketException) { Log.Out ("Error in WebCommandResult.SendLines(): Remote host closed connection: " + e.InnerException.Message); } else { Log.Out ("Error (IO) in WebCommandResult.SendLines(): " + e); } } catch (Exception e) { Log.Out ("Error in WebCommandResult.SendLines(): " + e); } finally { if (response != null) { response.Close (); } msw.Stop (); if (GamePrefs.GetInt (EnumGamePrefs.HideCommandExecutionLog) < 1) { totalHandlingTime += msw.ElapsedMicroseconds; Log.Out ("WebCommandResult.SendLines(): Took {0} µs", msw.ElapsedMicroseconds); } Interlocked.Decrement (ref currentHandlers); } } public void SendLine (string _text) { //throw new NotImplementedException (); } public void SendLog (string _msg, string _trace, UnityEngine.LogType _type) { //throw new NotImplementedException (); } public void EnableLogLevel (UnityEngine.LogType _type, bool _enable) { //throw new NotImplementedException (); } public string GetDescription () { return "WebCommandResult_for_" + command; } } }