Skip to content

Commit

Permalink
Better infractions
Browse files Browse the repository at this point in the history
- Moved them to the admin area
- Added moderator message logging
- Some minor other changes
  • Loading branch information
Atulin committed Apr 29, 2024
1 parent 6adb278 commit 5751f87
Show file tree
Hide file tree
Showing 11 changed files with 66 additions and 47 deletions.
21 changes: 6 additions & 15 deletions Ogma3/Areas/Admin/Api/V1/Cache/CacheController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,12 @@ namespace Ogma3.Areas.Admin.Api.V1.Cache;
[Route("admin/api/[controller]", Name = nameof(CacheController))]
[ApiController]
[Authorize(Roles = RoleNames.Admin)]
public class CacheController : ControllerBase
public class CacheController(IMemoryCache cache, ILogger<CacheController> logger) : ControllerBase
{
private readonly IMemoryCache _cache;
private readonly ILogger<CacheController> _logger;

public CacheController(IMemoryCache cache, ILogger<CacheController> logger)
{
_cache = cache;
_logger = logger;
}

[HttpGet]
public ActionResult<int> GetCache()
{
if (_cache is MemoryCache mc)
if (cache is MemoryCache mc)
{
return Ok(mc.Count);
}
Expand All @@ -36,16 +27,16 @@ public ActionResult<int> GetCache()
[IgnoreAntiforgeryToken]
public ActionResult<string> DeleteCache()
{
_logger.LogWarning("Purging all caches...");
logger.LogWarning("Purging all caches...");

if (_cache is MemoryCache mc)
if (cache is MemoryCache mc)
{
mc.Compact(1.0);
_logger.LogWarning("Cache purged!");
logger.LogWarning("Cache purged!");
return Ok("Cache purged!");
}

_logger.LogWarning("Could not purge cache!");
logger.LogWarning("Could not purge cache!");
return new ServerErrorObjectResult("Could not purge cache!");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
using Microsoft.Extensions.Caching.Memory;
using Ogma3.Data;
using Ogma3.Data.Infractions;
using Ogma3.Data.ModeratorActions;
using Ogma3.Infrastructure.Constants;
using Ogma3.Infrastructure.Extensions;
using Ogma3.Infrastructure.Mediator.Bases;
using Ogma3.Infrastructure.Middleware;
using Ogma3.Services.UserService;

namespace Ogma3.Api.V1.Infractions.Commands;
namespace Ogma3.Areas.Admin.Api.V1.Infractions.Commands;

public static class CreateInfraction
{
Expand All @@ -35,6 +37,7 @@ public class Handler(ApplicationDbContext context, IUserService userService, IMe
public async ValueTask<ActionResult<Response>> Handle(Command request, CancellationToken cancellationToken)
{
if (userService.User?.GetNumericId() is not { } uid) return Unauthorized();
if (userService.User?.GetUsername() is not { } modName) return Unauthorized();

var (userId, reason, dateTime, type) = request;
var infraction = new Infraction
Expand All @@ -46,6 +49,14 @@ public async ValueTask<ActionResult<Response>> Handle(Command request, Cancellat
Type = type,
};
context.Infractions.Add(infraction);

var action = new ModeratorAction
{
StaffMemberId = uid,
Description = ModeratorActionTemplates.Infractions.Create(uid, modName, infraction.Id, reason, type),
};
context.ModeratorActions.Add(action);

await context.SaveChangesAsync(cancellationToken);

if (infraction.Type == InfractionType.Ban)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Ogma3.Data;
using Ogma3.Data.ModeratorActions;
using Ogma3.Infrastructure.Constants;
using Ogma3.Infrastructure.Extensions;
using Ogma3.Infrastructure.Mediator.Bases;
using Ogma3.Services.UserService;

namespace Ogma3.Api.V1.Infractions.Commands;
namespace Ogma3.Areas.Admin.Api.V1.Infractions.Commands;

public static class DeactivateInfraction
{
Expand All @@ -20,7 +22,8 @@ public class Handler(ApplicationDbContext context, IUserService userService) : B
{
public async ValueTask<ActionResult<Response>> Handle(Command request, CancellationToken cancellationToken)
{
if (userService.User?.GetNumericId() is not { } _uid) return Unauthorized();
if (userService.User?.GetNumericId() is not { } uid) return Unauthorized();
if (userService.User?.GetUsername() is not { } modName) return Unauthorized();

var infraction = await context.Infractions
.Where(i => i.Id == request.InfractionId)
Expand All @@ -29,11 +32,18 @@ public async ValueTask<ActionResult<Response>> Handle(Command request, Cancellat
if (infraction is null) return NotFound();

infraction.RemovedAt = DateTime.Now;
infraction.RemovedById = _uid;
infraction.RemovedById = uid;

var action = new ModeratorAction
{
StaffMemberId = uid,
Description = ModeratorActionTemplates.Infractions.Lift(uid, modName, infraction.Id, infraction.Type),
};
context.ModeratorActions.Add(action);

await context.SaveChangesAsync(cancellationToken);

return Ok(new Response(infraction.Id, _uid, infraction.UserId));
return Ok(new Response(infraction.Id, uid, infraction.UserId));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,32 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Ogma3.Api.V1.Infractions.Commands;
using Ogma3.Api.V1.Infractions.Queries;
using Ogma3.Areas.Admin.Api.V1.Infractions.Commands;
using Ogma3.Areas.Admin.Api.V1.Infractions.Queries;
using Ogma3.Infrastructure.Constants;

namespace Ogma3.Api.V1.Infractions;
namespace Ogma3.Areas.Admin.Api.V1.Infractions;

[Route("api/[controller]", Name = nameof(InfractionsController))]
[ApiController]
[Authorize(Roles = $"{RoleNames.Admin},{RoleNames.Moderator}")]
public class InfractionsController : ControllerBase
public class InfractionsController(IMediator mediator) : ControllerBase
{
private readonly IMediator _mediator;
public InfractionsController(IMediator mediator) => _mediator = mediator;

[HttpGet]
public async Task<ActionResult<List<GetUserInfractions.Result>>> GetInfractionsAsync([FromQuery] long id)
=> await _mediator.Send(new GetUserInfractions.Query(id));
public async Task<ActionResult<List<GetUserInfractions.Result>>> GetInfractionsAsync([FromQuery] GetUserInfractions.Query query)
=> await mediator.Send(query);

[HttpGet("details")]
public async Task<ActionResult<GetInfractionDetails.Result>> GetInfractionDetails([FromQuery] long id)
=> await _mediator.Send(new GetInfractionDetails.Query(id));
public async Task<ActionResult<GetInfractionDetails.Result>> GetInfractionDetails([FromQuery] GetInfractionDetails.Query query)
=> await mediator.Send(query);

[HttpPost]
public async Task<ActionResult<CreateInfraction.Response>> AddInfraction(CreateInfraction.Command command)
=> await _mediator.Send(command);
=> await mediator.Send(command);

[HttpDelete("{id:long}")]
[HttpDelete("{InfractionId:long}")]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(DeactivateInfraction.Response), StatusCodes.Status200OK)]
public async Task<ActionResult<DeactivateInfraction.Response>> DeactivateInfraction(long id)
=> await _mediator.Send(new DeactivateInfraction.Command(id));
public async Task<ActionResult<DeactivateInfraction.Response>> DeactivateInfraction([FromRoute] DeactivateInfraction.Command command)
=> await mediator.Send(command);
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
using Ogma3.Data.Infractions;
using Ogma3.Infrastructure.Mediator.Bases;

namespace Ogma3.Api.V1.Infractions.Queries;
namespace Ogma3.Areas.Admin.Api.V1.Infractions.Queries;

public static class GetInfractionDetails
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
using Ogma3.Data;
using Ogma3.Infrastructure.Mediator.Bases;

namespace Ogma3.Api.V1.Infractions.Queries;
namespace Ogma3.Areas.Admin.Api.V1.Infractions.Queries;

public static class GetUserInfractions
{
Expand Down
9 changes: 3 additions & 6 deletions Ogma3/Areas/Admin/Api/V1/Telemetry/TelemetryController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,13 @@ namespace Ogma3.Areas.Admin.Api.V1.Telemetry;
[Route("admin/api/[controller]", Name = nameof(TelemetryController))]
[ApiController]
[Authorize]
public class TelemetryController : ControllerBase
public class TelemetryController(IMediator mediator) : ControllerBase
{
private readonly IMediator _mediator;
public TelemetryController(IMediator mediator) => _mediator = mediator;

[HttpGet(nameof(GetTableInfo))]
public async Task<ActionResult<List<GetTableInfo.Response>>> GetTableInfo()
=> await _mediator.Send(new GetTableInfo.Query());
=> await mediator.Send(new GetTableInfo.Query());

[HttpGet(nameof(GetImportantItemCounts))]
public async Task<ActionResult<Dictionary<string, int>>> GetImportantItemCounts()
=> await _mediator.Send(new GetImportantItemCounts.Query());
=> await mediator.Send(new GetImportantItemCounts.Query());
}
2 changes: 1 addition & 1 deletion Ogma3/Areas/Admin/Pages/Infractions.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
@foreach (var infraction in Model.Infractions)
{
<tr>
<td>@infraction.UserUserName</td>
<td>@infraction.UserUserName [@infraction.UserId]</td>
<td>@infraction.Type.ToStringFast()</td>
<td>@infraction.Reason</td>
<td>@infraction.ActiveUntil</td>
Expand Down
2 changes: 1 addition & 1 deletion Ogma3/Areas/Admin/Pages/Users.cshtml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
@page
@using Ogma3.Api.V1.Infractions
@using Ogma3.Areas.Admin.Api.V1.Infractions
@using Ogma3.Api.V1.Users
@model Users

Expand Down
11 changes: 11 additions & 0 deletions Ogma3/Infrastructure/Constants/ModeratorActionTemplates.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Globalization;
using Humanizer;
using Humanizer.Localisation;
using Ogma3.Data.Infractions;
using Ogma3.Data.Users;

namespace Ogma3.Infrastructure.Constants;
Expand Down Expand Up @@ -49,4 +50,14 @@ public static string UserBan(string bannedName, string modName, string reason)

public static string UserUnban(string bannedName, string modName)
=> $"User **{bannedName}** was unbanned by **{modName}**";

public static class Infractions
{
public static string Create(long userId, string modName, long infractionId, string reason, InfractionType type)
=> $"User **{userId}** was given a **{type.ToStringFast()}** infraction ({infractionId}) by **{modName}** for the following reason:\n*{reason}*";

public static string Lift(long userId, string modName, long infractionId, InfractionType type)
=> $"User **{userId}** had their **{type.ToStringFast()}** infraction ({infractionId}) lifted by **{modName}**.";

}
}
6 changes: 4 additions & 2 deletions Ogma3/Infrastructure/Logging/Telegram.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace Ogma3.Infrastructure.Logging;

public static class Telegram
{
public static async Task<(string Token, string Id)> GetCredentials()
public static async Task<TelegramToken> GetCredentials()
{
var telegramToken = Environment.GetEnvironmentVariable("TELEGRAM_TOKEN");

Expand All @@ -27,9 +27,11 @@ public static class Telegram

var split = telegramToken.Split('|');

if (split.Length >= 2) return (Token: split[0], Id: split[1]);
if (split is [string token, string id]) return new(token, id);

Log.Fatal("Expected two elements of the token, {Count} found", split.Length);
throw new ArgumentException($"Expected two elements of the Telegram token, {split.Length} found");
}

public record TelegramToken(string Token, string Id);
}

0 comments on commit 5751f87

Please sign in to comment.