source: binary-improvements2/WebServer/src/WebCommandResult.cs@ 397

Last change on this file since 397 was 391, checked in by alloc, 2 years ago

Major refactoring/cleanup

File size: 2.4 KB
RevLine 
[391]1using System;
2using System.Collections.Generic;
3using System.IO;
4using System.Net.Sockets;
5using System.Text;
6using AllocsFixes.JSON;
7using UnityEngine;
8using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;
9
10namespace Webserver {
11 public class WebCommandResult : IConsoleConnection {
12 public enum ResultType {
13 Full,
14 ResultOnly,
15 Raw
16 }
17
18 private readonly string command;
19 private readonly string parameters;
20
21 private readonly HttpListenerResponse response;
22 private readonly ResultType responseType;
23
24 public WebCommandResult (string _command, string _parameters, ResultType _responseType, HttpListenerResponse _response) {
25 response = _response;
26 command = _command;
27 parameters = _parameters;
28 responseType = _responseType;
29 }
30
31 public void SendLines (List<string> _output) {
32 StringBuilder sb = new StringBuilder ();
33 foreach (string line in _output) {
34 sb.AppendLine (line);
35 }
36
37 try {
38 response.SendChunked = false;
39
40 if (responseType == ResultType.Raw) {
41 WebUtils.WriteText (response, sb.ToString ());
42 } else {
43 JsonNode result;
44 if (responseType == ResultType.ResultOnly) {
45 result = new JsonString (sb.ToString ());
46 } else {
47 JsonObject resultObj = new JsonObject ();
48
49 resultObj.Add ("command", new JsonString (command));
50 resultObj.Add ("parameters", new JsonString (parameters));
51 resultObj.Add ("result", new JsonString (sb.ToString ()));
52
53 result = resultObj;
54 }
55
56 WebUtils.WriteJson (response, result);
57 }
58 } catch (IOException e) {
59 if (e.InnerException is SocketException) {
60 Log.Out ("Error in WebCommandResult.SendLines(): Remote host closed connection: " +
61 e.InnerException.Message);
62 } else {
63 Log.Out ("Error (IO) in WebCommandResult.SendLines(): " + e);
64 }
65 } catch (Exception e) {
66 Log.Out ("Error in WebCommandResult.SendLines(): " + e);
67 } finally {
68 response?.Close ();
69 }
70 }
71
72 public void SendLine (string _text) {
73 //throw new NotImplementedException ();
74 }
75
76 public void SendLog (string _formattedMessage, string _plainMessage, string _trace, LogType _type, DateTime _timestamp, long _uptime) {
77 //throw new NotImplementedException ();
78 }
79
80 public void EnableLogLevel (LogType _type, bool _enable) {
81 //throw new NotImplementedException ();
82 }
83
84 public string GetDescription () {
85 return "WebCommandResult_for_" + command;
86 }
87 }
88}
Note: See TracBrowser for help on using the repository browser.