using System; using System.Collections.Generic; using System.IO; using System.Net.Sockets; using System.Text; using AllocsFixes.JSON; using UnityEngine; using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse; namespace Webserver { public class WebCommandResult : IConsoleConnection { public enum ResultType { Full, ResultOnly, Raw } private readonly string command; private readonly string parameters; private readonly HttpListenerResponse response; private readonly ResultType responseType; public WebCommandResult (string _command, string _parameters, ResultType _responseType, HttpListenerResponse _response) { response = _response; command = _command; parameters = _parameters; responseType = _responseType; } public void SendLines (List _output) { StringBuilder sb = new StringBuilder (); foreach (string line in _output) { sb.AppendLine (line); } try { response.SendChunked = false; if (responseType == ResultType.Raw) { WebUtils.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; } WebUtils.WriteJson (response, result); } } catch (IOException e) { if (e.InnerException is SocketException) { Log.Warning ("[Web] Error in WebCommandResult.SendLines(): Remote host closed connection: " + e.InnerException.Message); } else { Log.Warning ("[Web] Error (IO) in WebCommandResult.SendLines(): " + e); } } catch (Exception e) { Log.Warning ("[Web] Error in WebCommandResult.SendLines(): " + e); } finally { response?.Close (); } } public void SendLine (string _text) { //throw new NotImplementedException (); } public void SendLog (string _formattedMessage, string _plainMessage, string _trace, LogType _type, DateTime _timestamp, long _uptime) { //throw new NotImplementedException (); } public void EnableLogLevel (LogType _type, bool _enable) { //throw new NotImplementedException (); } public string GetDescription () { return "WebCommandResult_for_" + command; } } }