Newsbot.Collector/Newsbot.Collector.Api/Controllers/v1/DiscordWebHooksController.cs

98 lines
2.8 KiB
C#

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newsbot.Collector.Api.Middleware;
using Newsbot.Collector.Domain.Dto;
using Newsbot.Collector.Domain.Entities;
using Newsbot.Collector.Domain.Interfaces;
using Newsbot.Collector.Domain.Models;
namespace Newsbot.Collector.Api.Controllers.v1;
[ApiController]
[Route("api/v1/discord/webhooks")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class DiscordWebHookController : ControllerBase
{
private readonly ILogger<DiscordWebHookController> _logger;
private readonly IDiscordWebHooksRepository _webhooks;
public DiscordWebHookController(ILogger<DiscordWebHookController> logger, IOptions<ConnectionStrings> settings, IDiscordWebHooksRepository webhooks)
{
_logger = logger;
_webhooks = webhooks;
}
[HttpGet(Name = "GetDiscordWebhooks")]
public ActionResult<IEnumerable<DiscordWebHookDto>> Get(int page)
{
var userId = HttpContext.GetUserId();
if (userId.Equals(string.Empty))
{
_logger.LogWarning("Unable to find the user ID in the JWD Token");
return new BadRequestResult();
}
var items = new List<DiscordWebHookDto>();
var res = _webhooks.ListByUserId(userId, page);
foreach (var item in res)
{
items.Add(DiscordWebHookDto.Convert(item));
}
return new OkObjectResult(items);
}
[HttpPost(Name = "New")]
public DiscordWebHookDto New(string url, string server, string channel)
{
var exists = _webhooks.GetByUrl(url);
if (exists.Id != Guid.Empty)
{
return DiscordWebHookDto.Convert(exists);
}
var res = _webhooks.New(new DiscordWebhookEntity
{
Url = url,
Server = server,
Channel = channel,
Enabled = true,
});
return DiscordWebHookDto.Convert(res);
}
[HttpGet("by/serverAndChannel")]
public IEnumerable<DiscordWebHookDto> GetByServerAndChannel(string server, string channel)
{
var items = new List<DiscordWebHookDto>();
var res = _webhooks.ListByServerAndChannel(server, channel, 25);
foreach (var item in res)
{
items.Add(DiscordWebHookDto.Convert(item));
}
return items;
}
[HttpGet("{id}")]
public DiscordWebHookDto GetById(Guid id)
{
var res = _webhooks.GetById(id);
return DiscordWebHookDto.Convert(res);
}
[HttpPost("{id}/disable")]
public void DisableById(Guid id)
{
_webhooks.Disable(id);
}
[HttpPost("{id}/enable")]
public void EnableById(Guid id)
{
_webhooks.Enable(id);
}
}