diff --git a/src/Core/GeekbotExitCode.cs b/src/Core/GeekbotExitCode.cs index 5598f48..51006e1 100644 --- a/src/Core/GeekbotExitCode.cs +++ b/src/Core/GeekbotExitCode.cs @@ -8,6 +8,7 @@ // Geekbot Internals TranslationsFailed = 201, + KilledByApiCall = 210, // Dependent Services /* 301 not in use anymore (redis) */ diff --git a/src/Web/Controllers/KillController.cs b/src/Web/Controllers/KillController.cs new file mode 100644 index 0000000..2492b0d --- /dev/null +++ b/src/Web/Controllers/KillController.cs @@ -0,0 +1,64 @@ +using System; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Geekbot.Core; +using Geekbot.Core.GlobalSettings; +using Microsoft.AspNetCore.Mvc; + +namespace Geekbot.Web.Controllers +{ + /* + * Sometimes for some unknown reason command responses may become incredibly slow. + * Because i don't have time to debug it and may not always know directly when it happens, + * i want to give some trusted people the possibility to restart the bot. + * The kill code must be set manually in the db, it should end it `---1' + * + * ToDo: Actually fix the underlying issue + */ + public class KillController : Controller + { + private readonly IGlobalSettings _globalSettings; + private const string KillCodeDbKey = "KillCode"; + + public KillController(IGlobalSettings globalSettings) + { + _globalSettings = globalSettings; + } + + [HttpGet("/v1/kill/{providedKillCode}")] + public async Task KillTheBot([FromRoute] string providedKillCode) + { + var killCode = _globalSettings.GetKey(KillCodeDbKey); + if (providedKillCode != killCode) + { + return Unauthorized(new ApiError { Message = $"Go Away ({GetKillCodeInt(killCode)})" }); + } + + await UpdateKillCode(killCode); +#pragma warning disable CS4014 + Kill(); +#pragma warning restore CS4014 + return Ok(); + } + + private int GetKillCodeInt(string code) + { + var group = Regex.Match(code, @".+(\-\-\-(?\d+))").Groups["int"]; + return group.Success ? int.Parse(group.Value) : 0; + } + + private async Task UpdateKillCode(string oldCode) + { + var newKillCodeInt = new Random().Next(1, 100); + var newCode = oldCode.Replace($"---{GetKillCodeInt(oldCode)}", $"---{newKillCodeInt}"); + await _globalSettings.SetKey(KillCodeDbKey, newCode); + } + + private async Task Kill() + { + // wait a second so the http response can still be sent successfully + await Task.Delay(1000); + Environment.Exit(GeekbotExitCode.KilledByApiCall.GetHashCode()); + } + } +} \ No newline at end of file