using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ChaosBot.Discord; using ChaosBot.Models; using ChaosBot.WebServer.Models; using ChaosBot.WebServer.Services; using Discord.WebSocket; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace ChaosBot.WebServer.App { [ApiController] [Route("/api/custom-commands")] public class CustomCommandController : Controller { private readonly AccessTokenCache _accessTokenCache; public CustomCommandController( AccessTokenCache accessTokenCache ) { _accessTokenCache = accessTokenCache; } [HttpGet] [Route("{guildId}")] public async Task GetCustomCommands([FromRoute]ulong guildId) { if (!CheckPermissions.GetResult(_accessTokenCache, Request, guildId, out IActionResult result)) return result; await using ChaosbotContext dbContext = new ChaosbotContext(); IQueryable customCommandsQuery = dbContext.CustomCommands; List customCommands = customCommandsQuery .Where(cc => cc.DiscordGuildId == guildId) .ToList(); List response = customCommands.Select(e => new CustomCommandResponse(e)).ToList(); return Json(response); } [HttpPost] [Route("{guildId}")] public async Task UpsertCustomCommands([FromRoute]ulong guildId, [FromBody]CustomCommandRequest customCommandRequest) { if (!CheckPermissions.GetResult(_accessTokenCache, Request, guildId, out IActionResult result)) return result; await using ChaosbotContext dbContext = new ChaosbotContext(); CustomCommand customCommand = new CustomCommand { DiscordGuildId = guildId, Command = customCommandRequest.Command, Type = customCommandRequest.Type, Content = customCommandRequest.Content }; await dbContext.CustomCommands.Upsert(customCommand) .On(cc => new {cc.DiscordGuildId, cc.Command}).RunAsync(); await dbContext.SaveChangesAsync(); return NoContent(); } [HttpDelete] [Route("{guildId}/{command}")] public async Task DeleteCustomCommands([FromRoute]ulong guildId, [FromRoute]string command) { if (!CheckPermissions.GetResult(_accessTokenCache, Request, guildId, out IActionResult result)) return result; await using ChaosbotContext dbContext = new ChaosbotContext(); IQueryable customCommandQuery = dbContext.CustomCommands; CustomCommand customCommand = customCommandQuery .Where(cc => cc.DiscordGuildId == guildId) .First(cc => cc.Command == command); if (customCommand == null) return NotFound(); dbContext.CustomCommands.Remove(customCommand); await dbContext.SaveChangesAsync(); return NoContent(); } } }