|
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Threading.Tasks;
- using IllusionPlugin;
- using TechbloxModdingAPI.App;
- using TechbloxModdingAPI.Commands;
- using TechbloxModdingAPI.Utility;
- using UnityEngine;
-
- namespace TBConsole
- {
- public class TBConsoleMod : IEnhancedPlugin
- {
- public override string Name => "TBConsole";
- public override string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version.ToString();
-
- private WebServer _server;
- private UnityLogHandler _logHandler;
- public override void OnApplicationStart()
- {
- TechbloxModdingAPI.Main.Init();
- Game.Enter += async (sender, e) =>
- {
- while (_server?.Running ?? false)
- {
- Logging.LogWarning("A previous web server is still running");
- _server?.Stop();
- await Task.Delay(500);
- }
-
- _server = new WebServer(CommandReceived, GetCommandList);
- _server.Start();
- };
- Game.Exit += (sender, e) => _server?.Stop();
- }
-
- private string CommandReceived(string command)
- {
- if (_logHandler == null)
- Debug.unityLogger.logHandler = _logHandler = new UnityLogHandler(Debug.unityLogger.logHandler);
- _logHandler.StartCollectingLogMessages();
- try
- {
- bool inString = false;
- var cmdparts = new List<string>();
- command = command.Trim();
- int lastIndex = 0;
- for (int i = 0; i <= command.Length; i++)
- {
- if (i < command.Length && command[i] == '"') inString = !inString;
- else if (!inString && (i == command.Length || command[i] == ' '))
- {
- cmdparts.Add(command.Substring(lastIndex, i - lastIndex).Trim('"'));
- lastIndex = i + 1;
- }
- }
-
- switch (cmdparts.Count)
- {
- case 1:
- ExistingCommands.Call(cmdparts[0]);
- break;
- case 2:
- ExistingCommands.Call(cmdparts[0], cmdparts[1]);
- break;
- case 3:
- ExistingCommands.Call(cmdparts[0], cmdparts[1], cmdparts[2]);
- break;
- case 4:
- ExistingCommands.Call(cmdparts[0], cmdparts[1], cmdparts[2], cmdparts[3]);
- break;
- default:
- return "Too many arguments! Maximum for default commands is 3";
- }
- }
- catch (Exception e) when (e is CommandException || e is TargetParameterCountException)
- {
- Logging.CommandLogWarning(e.Message);
- }
- catch (Exception e)
- {
- Logging.CommandLogWarning(e);
- }
- string result = _logHandler.FinishCollectingLogMessages();
- return $"Got it: {command}\n{result}";
- }
-
- public string GetCommandList()
- {
- return ExistingCommands.GetCommandNamesAndDescriptions()
- .Select(command => command.Name + " - " + command.Description).Aggregate((a, b) => a + "\n" + b);
- }
-
- public override void OnApplicationQuit()
- {
- _server?.Stop();
- TechbloxModdingAPI.Main.Shutdown();
- }
-
- public static void Main(string[] args)
- {
- var mod = new TBConsoleMod();
- mod._server = new WebServer(mod.CommandReceived, mod.GetCommandList);
- mod._server.Start();
- Console.ReadLine();
- }
- }
- }
|