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.

89 lines
3.1KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Threading.Tasks;
  6. using IllusionPlugin;
  7. using TechbloxModdingAPI.Commands;
  8. using UnityEngine;
  9. namespace TBConsole
  10. {
  11. public class TBConsoleMod : IEnhancedPlugin
  12. {
  13. public override string Name => "TBConsole";
  14. public override string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version.ToString();
  15. private WebServer _server;
  16. private UnityLogHandler _logHandler;
  17. public override void OnApplicationStart()
  18. {
  19. TechbloxModdingAPI.Main.Init();
  20. _server = new WebServer(CommandReceived, GetCommandList);
  21. _server.Start();
  22. }
  23. private string CommandReceived(string command)
  24. {
  25. if (_logHandler == null)
  26. Debug.unityLogger.logHandler = _logHandler = new UnityLogHandler(Debug.unityLogger.logHandler);
  27. _logHandler.StartCollectingLogMessages();
  28. bool inString = false;
  29. var cmdparts = new List<string>();
  30. command = command.Trim();
  31. int lastIndex = 0;
  32. for (int i = 0; i <= command.Length; i++)
  33. {
  34. if (i < command.Length && command[i] == '"') inString = !inString;
  35. else if (!inString && (i == command.Length || command[i] == ' '))
  36. {
  37. cmdparts.Add(command.Substring(lastIndex, i - lastIndex).Trim('"'));
  38. lastIndex = i + 1;
  39. }
  40. }
  41. //Console.WriteLine("Command parts: " + cmdparts.Aggregate((a, b) => a + ", " + b));
  42. switch (cmdparts.Count)
  43. {
  44. case 1:
  45. ExistingCommands.Call(cmdparts[0]);
  46. break;
  47. case 2:
  48. ExistingCommands.Call(cmdparts[0], cmdparts[1]);
  49. break;
  50. case 3:
  51. ExistingCommands.Call(cmdparts[0], cmdparts[1], cmdparts[2]);
  52. break;
  53. case 4:
  54. ExistingCommands.Call(cmdparts[0], cmdparts[1], cmdparts[2], cmdparts[3]);
  55. break;
  56. default:
  57. return "Too many arguments! Maximum for default commands is 3";
  58. }
  59. string result = _logHandler.FinishCollectingLogMessages();
  60. return $"Got it: {command}\n{result}";
  61. }
  62. public string GetCommandList()
  63. {
  64. return ExistingCommands.GetCommandNamesAndDescriptions()
  65. .Select(command => command.Name + " - " + command.Description).Aggregate((a, b) => a + "\n" + b);
  66. }
  67. public override void OnApplicationQuit()
  68. {
  69. _server.Stop();
  70. TechbloxModdingAPI.Main.Shutdown();
  71. }
  72. public static void Main(string[] args)
  73. {
  74. var mod = new TBConsoleMod();
  75. mod._server = new WebServer(mod.CommandReceived, mod.GetCommandList);
  76. mod._server.Start();
  77. Console.ReadLine();
  78. }
  79. }
  80. }