Refactor WebApi Controllers to take advantage of new .net6 features

This commit is contained in:
Daan Boerlage 2021-11-07 00:08:08 +01:00
parent 6b3a3a9ec2
commit e01a066920
Signed by: daan
GPG key ID: FCE070E1E4956606
21 changed files with 452 additions and 472 deletions

View file

@ -1,7 +1,6 @@
namespace Geekbot.Web namespace Geekbot.Web;
public record ApiError
{ {
public class ApiError
{
public string Message { get; set; } public string Message { get; set; }
}
} }

View file

@ -1,16 +1,13 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text.Json; using System.Text.Json;
using System.Threading.Tasks;
using Geekbot.Core.GlobalSettings; using Geekbot.Core.GlobalSettings;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace Geekbot.Web.Controllers.Callback namespace Geekbot.Web.Controllers.Callback;
[ApiController]
public class CallbackController : ControllerBase
{ {
public class CallbackController : Controller
{
private readonly IGlobalSettings _globalSettings; private readonly IGlobalSettings _globalSettings;
public CallbackController(IGlobalSettings globalSettings) public CallbackController(IGlobalSettings globalSettings)
@ -31,12 +28,12 @@ namespace Geekbot.Web.Controllers.Callback
var form = new Dictionary<string, string> var form = new Dictionary<string, string>
{ {
{"client_id", appId}, { "client_id", appId },
{"client_secret", accessToken}, { "client_secret", accessToken },
{"grant_type", "authorization_code"}, { "grant_type", "authorization_code" },
{"code", code}, { "code", code },
{"scope", "identify email guilds"}, { "scope", "identify email guilds" },
{"redirect_uri", callbackUrl} { "redirect_uri", callbackUrl }
}; };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
@ -44,11 +41,10 @@ namespace Geekbot.Web.Controllers.Callback
result.EnsureSuccessStatusCode(); result.EnsureSuccessStatusCode();
var stringResponse = await result.Content.ReadAsStringAsync(); var stringResponse = await result.Content.ReadAsStringAsync();
var responseData = JsonSerializer.Deserialize<CallbackTokenResponseDto>(stringResponse); var responseData = JsonSerializer.Deserialize<CallbackTokenResponse>(stringResponse);
token = responseData.AccessToken; token = responseData.AccessToken;
} }
return new RedirectResult($"https://geekbot.pizzaandcoffee.rocks/login?token={token}", false); return new RedirectResult($"https://geekbot.pizzaandcoffee.rocks/login?token={token}", false);
} }
}
} }

View file

@ -0,0 +1,21 @@
using System.Text.Json.Serialization;
namespace Geekbot.Web.Controllers.Callback;
public record CallbackTokenResponse
{
[JsonPropertyName("access_token")]
public string AccessToken { get; set; }
[JsonPropertyName("token_type")]
public string TokenType { get; set; }
[JsonPropertyName("expires_in")]
public int ExpiresIn { get; set; }
[JsonPropertyName("refresh_token")]
public string RefreshToken { get; set; }
[JsonPropertyName("scope")]
public string Scope { get; set; }
}

View file

@ -1,22 +0,0 @@
using System.Text.Json.Serialization;
namespace Geekbot.Web.Controllers.Callback
{
public class CallbackTokenResponseDto
{
[JsonPropertyName("access_token")]
public string AccessToken { get; set; }
[JsonPropertyName("token_type")]
public string TokenType { get; set; }
[JsonPropertyName("expires_in")]
public int ExpiresIn { get; set; }
[JsonPropertyName("refresh_token")]
public string RefreshToken { get; set; }
[JsonPropertyName("scope")]
public string Scope { get; set; }
}
}

View file

@ -1,13 +1,13 @@
using System.Linq; using Discord.Commands;
using Discord.Commands;
using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace Geekbot.Web.Controllers.Commands namespace Geekbot.Web.Controllers.Commands;
[ApiController]
[EnableCors("AllowSpecificOrigin")]
public class CommandController : ControllerBase
{ {
[EnableCors("AllowSpecificOrigin")]
public class CommandController : Controller
{
private readonly CommandService _commands; private readonly CommandService _commands;
public CommandController(CommandService commands) public CommandController(CommandService commands)
@ -15,11 +15,11 @@ namespace Geekbot.Web.Controllers.Commands
_commands = commands; _commands = commands;
} }
[Route("/v1/commands")] [HttpGet("/v1/commands")]
public IActionResult GetCommands() public IActionResult GetCommands()
{ {
var commandList = (from cmd in _commands.Commands var commandList = (from cmd in _commands.Commands
let cmdParamsObj = cmd.Parameters.Select(cmdParam => new CommandParamDto let cmdParamsObj = cmd.Parameters.Select(cmdParam => new ResponseCommandParam
{ {
Summary = cmdParam.Summary, Summary = cmdParam.Summary,
Default = cmdParam.DefaultValue?.ToString(), Default = cmdParam.DefaultValue?.ToString(),
@ -27,7 +27,7 @@ namespace Geekbot.Web.Controllers.Commands
}) })
.ToList() .ToList()
let param = string.Join(", !", cmd.Aliases) let param = string.Join(", !", cmd.Aliases)
select new CommandDto select new ResponseCommand
{ {
Name = cmd.Name, Name = cmd.Name,
Summary = cmd.Summary, Summary = cmd.Summary,
@ -37,5 +37,4 @@ namespace Geekbot.Web.Controllers.Commands
}).ToList(); }).ToList();
return Ok(commandList.FindAll(e => !e.Aliases[0].StartsWith("owner"))); return Ok(commandList.FindAll(e => !e.Aliases[0].StartsWith("owner")));
} }
}
} }

View file

@ -1,13 +0,0 @@
using System.Collections.Generic;
namespace Geekbot.Web.Controllers.Commands
{
public class CommandDto
{
public string Name { get; set; }
public string Summary { get; set; }
public bool IsAdminCommand { get; set; }
public List<string> Aliases { get; set; }
public List<CommandParamDto> Params { get; set; }
}
}

View file

@ -1,9 +0,0 @@
namespace Geekbot.Web.Controllers.Commands
{
public class CommandParamDto
{
public string Summary { get; set; }
public string Default { get; set; }
public string Type { get; set; }
}
}

View file

@ -0,0 +1,10 @@
namespace Geekbot.Web.Controllers.Commands;
public record ResponseCommand
{
public string Name { get; set; }
public string Summary { get; set; }
public bool IsAdminCommand { get; set; }
public List<string> Aliases { get; set; }
public List<ResponseCommandParam> Params { get; set; }
}

View file

@ -0,0 +1,8 @@
namespace Geekbot.Web.Controllers.Commands;
public record ResponseCommandParam
{
public string Summary { get; set; }
public string Default { get; set; }
public string Type { get; set; }
}

View file

@ -1,13 +1,13 @@
using System.Collections.Generic;
using Geekbot.Core.Highscores; using Geekbot.Core.Highscores;
using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace Geekbot.Web.Controllers.Highscores namespace Geekbot.Web.Controllers.Highscores;
[ApiController]
[EnableCors("AllowSpecificOrigin")]
public class HighscoreController : ControllerBase
{ {
[EnableCors("AllowSpecificOrigin")]
public class HighscoreController : Controller
{
private readonly IHighscoreManager _highscoreManager; private readonly IHighscoreManager _highscoreManager;
public HighscoreController(IHighscoreManager highscoreManager) public HighscoreController(IHighscoreManager highscoreManager)
@ -17,7 +17,7 @@ namespace Geekbot.Web.Controllers.Highscores
[HttpPost] [HttpPost]
[Route("/v1/highscore")] [Route("/v1/highscore")]
public IActionResult GetHighscores([FromBody] HighscoreControllerPostBodyDto body) public IActionResult GetHighscores([FromBody] HighscoreControllerPostBody body)
{ {
if (!ModelState.IsValid || body == null) if (!ModelState.IsValid || body == null)
{ {
@ -50,7 +50,7 @@ namespace Geekbot.Web.Controllers.Highscores
}); });
counter++; counter++;
} }
return Ok(response); return Ok(response);
} }
}
} }

View file

@ -0,0 +1,15 @@
using System.ComponentModel.DataAnnotations;
using Geekbot.Core.Highscores;
namespace Geekbot.Web.Controllers.Highscores;
public record HighscoreControllerPostBody
{
[Required]
public ulong GuildId { get; set; }
public HighscoreTypes Type { get; } = HighscoreTypes.messages;
[Range(1, 150)]
public int Amount { get; } = 50;
}

View file

@ -1,16 +0,0 @@
using System.ComponentModel.DataAnnotations;
using Geekbot.Core.Highscores;
namespace Geekbot.Web.Controllers.Highscores
{
public class HighscoreControllerPostBodyDto
{
[Required]
public ulong GuildId { get; set; }
public HighscoreTypes Type { get; } = HighscoreTypes.messages;
[Range(1, 150)]
public int Amount { get; } = 50;
}
}

View file

@ -1,11 +1,12 @@
using Geekbot.Core.Highscores; using Geekbot.Core.Highscores;
namespace Geekbot.Web.Controllers.Highscores namespace Geekbot.Web.Controllers.Highscores;
public record HighscoreControllerReponseBody
{ {
public class HighscoreControllerReponseBody
{
public int rank { get; set; } public int rank { get; set; }
public HighscoreUserDto user { get; set; } public HighscoreUserDto user { get; set; }
public int count { get; set; } public int count { get; set; }
}
} }

View file

@ -1,20 +1,17 @@
using System;
using System.IO;
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Threading.Tasks;
using Geekbot.Core.GlobalSettings; using Geekbot.Core.GlobalSettings;
using Geekbot.Core.Interactions; using Geekbot.Core.Interactions;
using Geekbot.Core.Interactions.Request; using Geekbot.Core.Interactions.Request;
using Geekbot.Core.Interactions.Response; using Geekbot.Core.Interactions.Response;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Sodium; using Sodium;
namespace Geekbot.Web.Controllers.Interactions namespace Geekbot.Web.Controllers.Interactions;
[ApiController]
public class InteractionController : ControllerBase
{ {
public class InteractionController : Controller
{
private readonly IInteractionCommandManager _interactionCommandManager; private readonly IInteractionCommandManager _interactionCommandManager;
private readonly byte[] _publicKeyBytes; private readonly byte[] _publicKeyBytes;
@ -28,8 +25,10 @@ namespace Geekbot.Web.Controllers.Interactions
[HttpPost] [HttpPost]
[Route("/interactions")] [Route("/interactions")]
public async Task<IActionResult> HandleInteraction( public async Task<IActionResult> HandleInteraction(
[FromHeader(Name = "X-Signature-Ed25519")] string signature, [FromHeader(Name = "X-Signature-Ed25519")]
[FromHeader(Name = "X-Signature-Timestamp")] string timestamp string signature,
[FromHeader(Name = "X-Signature-Timestamp")]
string timestamp
) )
{ {
if (string.IsNullOrEmpty(signature) || string.IsNullOrEmpty(timestamp)) if (string.IsNullOrEmpty(signature) || string.IsNullOrEmpty(timestamp))
@ -97,5 +96,4 @@ namespace Geekbot.Web.Controllers.Interactions
return PublicKeyAuth.VerifyDetached(signatureBytes, timestampBytes, _publicKeyBytes); return PublicKeyAuth.VerifyDetached(signatureBytes, timestampBytes, _publicKeyBytes);
} }
}
} }

View file

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Threading.Tasks;
using Geekbot.Core; using Geekbot.Core;
using Geekbot.Core.GlobalSettings; using Geekbot.Core.GlobalSettings;
using Geekbot.Core.Interactions; using Geekbot.Core.Interactions;
@ -11,12 +6,12 @@ using Geekbot.Core.Interactions.ApplicationCommand;
using Geekbot.Core.Logger; using Geekbot.Core.Logger;
using Geekbot.Web.Controllers.Interactions.Model; using Geekbot.Web.Controllers.Interactions.Model;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Sentry.Protocol;
namespace Geekbot.Web.Controllers.Interactions namespace Geekbot.Web.Controllers.Interactions;
[ApiController]
public class InteractionRegistrarController : ControllerBase
{ {
public class InteractionRegistrarController : Controller
{
private readonly IGeekbotLogger _logger; private readonly IGeekbotLogger _logger;
private readonly IInteractionCommandManager _interactionCommandManager; private readonly IInteractionCommandManager _interactionCommandManager;
private readonly string _discordToken; private readonly string _discordToken;
@ -135,5 +130,4 @@ namespace Geekbot.Web.Controllers.Interactions
return await HttpAbstractions.Get<List<RegisteredInteraction>>(_guildCommandUri, httpClient); return await HttpAbstractions.Get<List<RegisteredInteraction>>(_guildCommandUri, httpClient);
} }
}
} }

View file

@ -1,12 +1,12 @@
using System.Collections.Generic;
using Geekbot.Core.Interactions.ApplicationCommand; using Geekbot.Core.Interactions.ApplicationCommand;
namespace Geekbot.Web.Controllers.Interactions.Model namespace Geekbot.Web.Controllers.Interactions.Model;
public record InteractionRegistrationOperations
{ {
public record InteractionRegistrationOperations
{
public List<Command> Create { get; set; } = new(); public List<Command> Create { get; set; } = new();
public Dictionary<string, Command> Update { get; set; } = new(); public Dictionary<string, Command> Update { get; set; } = new();
public List<string> Remove { get; set; } = new(); public List<string> Remove { get; set; } = new();
}
} }

View file

@ -1,10 +1,10 @@
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using Geekbot.Core.Interactions.Request; using Geekbot.Core.Interactions.Request;
namespace Geekbot.Web.Controllers.Interactions.Model namespace Geekbot.Web.Controllers.Interactions.Model;
public record RegisteredInteraction
{ {
public record RegisteredInteraction
{
[JsonPropertyName("id")] [JsonPropertyName("id")]
public string Id { get; set; } public string Id { get; set; }
@ -28,5 +28,4 @@ namespace Geekbot.Web.Controllers.Interactions.Model
[JsonPropertyName("guild_id")] [JsonPropertyName("guild_id")]
public string GuildId { get; set; } public string GuildId { get; set; }
}
} }

View file

@ -1,13 +1,11 @@
using System;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Geekbot.Core; using Geekbot.Core;
using Geekbot.Core.GlobalSettings; using Geekbot.Core.GlobalSettings;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace Geekbot.Web.Controllers namespace Geekbot.Web.Controllers;
{
/* /*
* Sometimes for some unknown reason command responses may become incredibly slow. * 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, * 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. * i want to give some trusted people the possibility to restart the bot.
@ -15,8 +13,10 @@ namespace Geekbot.Web.Controllers
* *
* ToDo: Actually fix the underlying issue * ToDo: Actually fix the underlying issue
*/ */
public class KillController : Controller
{ [ApiController]
public class KillController : ControllerBase
{
private readonly IGlobalSettings _globalSettings; private readonly IGlobalSettings _globalSettings;
private const string KillCodeDbKey = "KillCode"; private const string KillCodeDbKey = "KillCode";
@ -60,5 +60,4 @@ namespace Geekbot.Web.Controllers
await Task.Delay(1000); await Task.Delay(1000);
Environment.Exit(GeekbotExitCode.KilledByApiCall.GetHashCode()); Environment.Exit(GeekbotExitCode.KilledByApiCall.GetHashCode());
} }
}
} }

View file

@ -0,0 +1,10 @@
namespace Geekbot.Web.Controllers.Status;
public record ApiStatus
{
public string GeekbotVersion { get; set; }
public string ApiVersion { get; set; }
public string Status { get; set; }
}

View file

@ -1,9 +0,0 @@
namespace Geekbot.Web.Controllers.Status
{
public class ApiStatusDto
{
public string GeekbotVersion { get; set; }
public string ApiVersion { get; set; }
public string Status { get; set; }
}
}

View file

@ -3,15 +3,16 @@ using Geekbot.Core;
using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace Geekbot.Web.Controllers.Status namespace Geekbot.Web.Controllers.Status;
[ApiController]
[EnableCors("AllowSpecificOrigin")]
public class StatusController : ControllerBase
{ {
[EnableCors("AllowSpecificOrigin")]
public class StatusController : Controller
{
[Route("/")] [Route("/")]
public IActionResult GetCommands() public IActionResult GetCommands()
{ {
var responseBody = new ApiStatusDto var responseBody = new ApiStatus
{ {
GeekbotVersion = Constants.BotVersion(), GeekbotVersion = Constants.BotVersion(),
ApiVersion = Constants.ApiVersion.ToString(CultureInfo.InvariantCulture), ApiVersion = Constants.ApiVersion.ToString(CultureInfo.InvariantCulture),
@ -19,5 +20,4 @@ namespace Geekbot.Web.Controllers.Status
}; };
return Ok(responseBody); return Ok(responseBody);
} }
}
} }