Web server mod for Techblox to run commands
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.3KB

  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Threading.Tasks;
  5. namespace TBConsole
  6. {
  7. public class WebServer
  8. {
  9. private bool _running;
  10. private readonly HttpListener _listener = new HttpListener();
  11. private readonly Func<string, string> _commandReceiver;
  12. private readonly Func<string> _commandsListSender;
  13. public WebServer(Func<string, string> commandReceiver, Func<string> commandsListSender)
  14. {
  15. _commandReceiver = commandReceiver;
  16. _commandsListSender = commandsListSender;
  17. }
  18. public void Start()
  19. {
  20. _running = true;
  21. KeepListening();
  22. }
  23. public void Stop()
  24. {
  25. _running = false;
  26. _listener.Stop();
  27. }
  28. private async void KeepListening()
  29. {
  30. _listener.Prefixes.Add("http://localhost:8019/");
  31. _listener.Start();
  32. while (_running)
  33. {
  34. try
  35. {
  36. var context = await _listener.GetContextAsync();
  37. string request = await new StreamReader(context.Request.InputStream).ReadToEndAsync();
  38. string resp;
  39. switch (context.Request.Url.AbsolutePath)
  40. {
  41. case "/command":
  42. resp = _commandReceiver(request);
  43. break;
  44. case "/commands":
  45. resp = _commandsListSender();
  46. break;
  47. default:
  48. resp = "<img src=\"https://http.cat/404\">";
  49. break;
  50. }
  51. string origin = context.Request.Headers["Origin"];
  52. if (origin == "http://localhost:4200" || origin == "https://tb-console.web.app")
  53. context.Response.AddHeader("Access-Control-Allow-Origin", origin);
  54. var sw = new StreamWriter(context.Response.OutputStream);
  55. await sw.WriteLineAsync(resp);
  56. sw.Close();
  57. }
  58. catch (Exception e)
  59. {
  60. Console.WriteLine(e);
  61. }
  62. }
  63. }
  64. }
  65. }