chaosbot/ChaosBot/WebServer/App/CustomCommandApi.cs

81 lines
2.8 KiB
C#

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 CustomCommandApi : Controller
{
[HttpGet]
[Route("{guildId}")]
public async Task<IActionResult> GetCustomCommands([FromRoute]ulong guildId)
{
if (!CheckPermissions.GetResult(Request, guildId, out IActionResult result))
return result;
await using ChaosbotContext dbContext = new ChaosbotContext();
IQueryable<CustomCommand> customCommandsQuery = dbContext.CustomCommands;
List<CustomCommand> customCommands = customCommandsQuery
.Where(cc => cc.DiscordGuildId == guildId)
.ToList();
return Json(customCommands);
}
[HttpPost]
[Route("{guildId}")]
public async Task<IActionResult> UpsertCustomCommands([FromRoute]ulong guildId, [FromBody]CustomCommandRequest customCommandRequest)
{
if (!CheckPermissions.GetResult(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}")]
public async Task<IActionResult> DeleteCustomCommands([FromRoute]ulong guildId, [FromBody]CustomCommandRequest customCommandRequest)
{
if (!CheckPermissions.GetResult(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
};
dbContext.CustomCommands.Remove(customCommand);
await dbContext.SaveChangesAsync();
return NoContent();
}
}
}