feat: MediaController
This commit is contained in:
@@ -0,0 +1,24 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
|
|
||||||
|
namespace MemeVault.Api.Auth;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Scoped-сервис: идентификатор аутентифицированного пользователя из JWT.
|
||||||
|
/// Доступен во всех контроллерах через DI.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class CurrentUser(IHttpContextAccessor httpContextAccessor)
|
||||||
|
{
|
||||||
|
private ClaimsPrincipal Principal =>
|
||||||
|
httpContextAccessor.HttpContext?.User
|
||||||
|
?? throw new InvalidOperationException("No active HTTP context.");
|
||||||
|
|
||||||
|
public long TelegramId =>
|
||||||
|
long.Parse(Principal.FindFirstValue(ClaimTypes.NameIdentifier)
|
||||||
|
?? throw new InvalidOperationException("sub claim missing."));
|
||||||
|
|
||||||
|
public string? Username =>
|
||||||
|
Principal.FindFirstValue(ClaimTypes.Name);
|
||||||
|
|
||||||
|
public bool IsAuthenticated =>
|
||||||
|
Principal.Identity?.IsAuthenticated is true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
using MediatR;
|
||||||
|
using MemeVault.Api.Auth;
|
||||||
|
using MemeVault.Application.Commands.DeleteMedia;
|
||||||
|
using MemeVault.Application.Commands.UpdateMedia;
|
||||||
|
using MemeVault.Application.Queries.GetUserMedia;
|
||||||
|
using MemeVault.Application.Queries.SearchMedia;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace MemeVault.Api.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Authorize]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public sealed class MediaController(IMediator mediator, CurrentUser currentUser) : ControllerBase
|
||||||
|
{
|
||||||
|
// GET /api/media?q=...
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<IActionResult> GetAll([FromQuery] string? q, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var items = string.IsNullOrWhiteSpace(q)
|
||||||
|
? await mediator.Send(new GetUserMediaQuery(currentUser.TelegramId), ct)
|
||||||
|
: await mediator.Send(new SearchMediaQuery(currentUser.TelegramId, q), ct);
|
||||||
|
|
||||||
|
return Ok(items);
|
||||||
|
}
|
||||||
|
|
||||||
|
// PATCH /api/media/{id}
|
||||||
|
[HttpPatch("{id:guid}")]
|
||||||
|
public async Task<IActionResult> Update(
|
||||||
|
Guid id,
|
||||||
|
[FromBody] UpdateMediaRequest request,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
var ok = await mediator.Send(
|
||||||
|
new UpdateMediaCommand(id, currentUser.TelegramId, request.Caption, request.Tags),
|
||||||
|
ct);
|
||||||
|
|
||||||
|
return ok ? NoContent() : NotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
// DELETE /api/media/{id}
|
||||||
|
[HttpDelete("{id:guid}")]
|
||||||
|
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await mediator.Send(new DeleteMediaCommand(id, currentUser.TelegramId), ct);
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record UpdateMediaRequest(
|
||||||
|
string? Caption,
|
||||||
|
IReadOnlyList<string> Tags
|
||||||
|
);
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
using MemeVault.Domain.Exceptions;
|
||||||
|
using Microsoft.AspNetCore.Diagnostics;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace MemeVault.Api.Middleware;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Конвертирует DomainException в 400 Problem Details.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class DomainExceptionHandler : IExceptionHandler
|
||||||
|
{
|
||||||
|
public async ValueTask<bool> TryHandleAsync(
|
||||||
|
HttpContext ctx,
|
||||||
|
Exception ex,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (ex is not DomainException domain)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
var problem = new ProblemDetails
|
||||||
|
{
|
||||||
|
Title = "Business rule violation",
|
||||||
|
Detail = domain.Message,
|
||||||
|
Status = StatusCodes.Status400BadRequest,
|
||||||
|
};
|
||||||
|
|
||||||
|
ctx.Response.StatusCode = problem.Status!.Value;
|
||||||
|
await ctx.Response.WriteAsJsonAsync(problem, ct);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using MemeVault.Api.Middleware;
|
||||||
using MemeVault.Api.Auth;
|
using MemeVault.Api.Auth;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using MemeVault.Api.Options;
|
using MemeVault.Api.Options;
|
||||||
@@ -24,6 +25,8 @@ builder.Services.Configure<JwtOptions>(
|
|||||||
|
|
||||||
builder.Services.AddSingleton<TelegramInitDataValidator>();
|
builder.Services.AddSingleton<TelegramInitDataValidator>();
|
||||||
builder.Services.AddSingleton<JwtTokenService>();
|
builder.Services.AddSingleton<JwtTokenService>();
|
||||||
|
builder.Services.AddHttpContextAccessor();
|
||||||
|
builder.Services.AddScoped<CurrentUser>();
|
||||||
|
|
||||||
var jwtOpts = builder.Configuration.GetSection(JwtOptions.Section).Get<JwtOptions>()!;
|
var jwtOpts = builder.Configuration.GetSection(JwtOptions.Section).Get<JwtOptions>()!;
|
||||||
|
|
||||||
@@ -45,6 +48,8 @@ builder.Services
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
builder.Services.AddProblemDetails();
|
||||||
|
builder.Services.AddExceptionHandler<DomainExceptionHandler>();
|
||||||
builder.Services.AddAuthorization();
|
builder.Services.AddAuthorization();
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
|
|
||||||
@@ -53,16 +58,12 @@ builder.Services.AddEndpointsApiExplorer();
|
|||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
|
|
||||||
|
app.UseExceptionHandler();
|
||||||
app.UseHttpMetrics();
|
app.UseHttpMetrics();
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
|
||||||
app.MapGet("/health", () => Results.Ok(new { status = "ok" }));
|
app.MapGet("/health", () => Results.Ok(new { status = "ok" }));
|
||||||
// TODO: /api/media GET — список медиа пользователя
|
|
||||||
// TODO: /api/media/{id} PATCH — обновить caption / теги
|
|
||||||
// TODO: /api/media/{id} DELETE
|
|
||||||
// TODO: /api/tags GET — теги пользователя
|
|
||||||
// TODO: /api/collections GET/POST — коллекции
|
|
||||||
|
|
||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
app.MapMetrics();
|
app.MapMetrics();
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using MediatR;
|
||||||
|
|
||||||
|
namespace MemeVault.Application.Commands.UpdateMedia;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Обновляет caption и/или теги медиа-элемента.
|
||||||
|
/// Tags — полная замена: пустой список очищает все теги.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record UpdateMediaCommand(
|
||||||
|
Guid MediaItemId,
|
||||||
|
long RequestingTelegramId,
|
||||||
|
string? Caption,
|
||||||
|
IReadOnlyList<string> Tags
|
||||||
|
) : IRequest<bool>;
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
using MediatR;
|
||||||
|
using MemeVault.Domain.Repositories;
|
||||||
|
using MemeVault.Domain.ValueObjects;
|
||||||
|
using MemeVault.Application.Common;
|
||||||
|
|
||||||
|
namespace MemeVault.Application.Commands.UpdateMedia;
|
||||||
|
|
||||||
|
public sealed class UpdateMediaCommandHandler(
|
||||||
|
IMediaItemRepository mediaItems,
|
||||||
|
IUnitOfWork unitOfWork)
|
||||||
|
: IRequestHandler<UpdateMediaCommand, bool>
|
||||||
|
{
|
||||||
|
public async Task<bool> Handle(UpdateMediaCommand request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var item = await mediaItems.GetByIdAsync(request.MediaItemId, ct);
|
||||||
|
|
||||||
|
if (item is null || item.OwnerTelegramId != request.RequestingTelegramId)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
item.UpdateCaption(request.Caption);
|
||||||
|
|
||||||
|
// Полная замена тегов
|
||||||
|
foreach (var tag in item.Tags.ToList())
|
||||||
|
item.RemoveTag(tag);
|
||||||
|
|
||||||
|
foreach (var raw in request.Tags)
|
||||||
|
item.AddTag(new Tag(raw));
|
||||||
|
|
||||||
|
await unitOfWork.SaveChangesAsync(ct);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user