diff --git a/src/MemeVault.Api/Auth/CurrentUser.cs b/src/MemeVault.Api/Auth/CurrentUser.cs
new file mode 100644
index 0000000..79be6c3
--- /dev/null
+++ b/src/MemeVault.Api/Auth/CurrentUser.cs
@@ -0,0 +1,24 @@
+using System.Security.Claims;
+
+namespace MemeVault.Api.Auth;
+
+///
+/// Scoped-сервис: идентификатор аутентифицированного пользователя из JWT.
+/// Доступен во всех контроллерах через DI.
+///
+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;
+}
diff --git a/src/MemeVault.Api/Controllers/MediaController.cs b/src/MemeVault.Api/Controllers/MediaController.cs
new file mode 100644
index 0000000..129542e
--- /dev/null
+++ b/src/MemeVault.Api/Controllers/MediaController.cs
@@ -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 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 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 Delete(Guid id, CancellationToken ct)
+ {
+ await mediator.Send(new DeleteMediaCommand(id, currentUser.TelegramId), ct);
+ return NoContent();
+ }
+}
+
+public sealed record UpdateMediaRequest(
+ string? Caption,
+ IReadOnlyList Tags
+);
diff --git a/src/MemeVault.Api/Middleware/DomainExceptionHandler.cs b/src/MemeVault.Api/Middleware/DomainExceptionHandler.cs
new file mode 100644
index 0000000..6c12a22
--- /dev/null
+++ b/src/MemeVault.Api/Middleware/DomainExceptionHandler.cs
@@ -0,0 +1,31 @@
+using MemeVault.Domain.Exceptions;
+using Microsoft.AspNetCore.Diagnostics;
+using Microsoft.AspNetCore.Mvc;
+
+namespace MemeVault.Api.Middleware;
+
+///
+/// Конвертирует DomainException в 400 Problem Details.
+///
+public sealed class DomainExceptionHandler : IExceptionHandler
+{
+ public async ValueTask 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;
+ }
+}
diff --git a/src/MemeVault.Api/Program.cs b/src/MemeVault.Api/Program.cs
index 3965a9b..63ed42f 100644
--- a/src/MemeVault.Api/Program.cs
+++ b/src/MemeVault.Api/Program.cs
@@ -1,3 +1,4 @@
+using MemeVault.Api.Middleware;
using MemeVault.Api.Auth;
using System.Text;
using MemeVault.Api.Options;
@@ -24,6 +25,8 @@ builder.Services.Configure(
builder.Services.AddSingleton();
builder.Services.AddSingleton();
+builder.Services.AddHttpContextAccessor();
+builder.Services.AddScoped();
var jwtOpts = builder.Configuration.GetSection(JwtOptions.Section).Get()!;
@@ -45,6 +48,8 @@ builder.Services
};
});
+builder.Services.AddProblemDetails();
+builder.Services.AddExceptionHandler();
builder.Services.AddAuthorization();
builder.Services.AddControllers();
@@ -53,16 +58,12 @@ builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();
+app.UseExceptionHandler();
app.UseHttpMetrics();
app.UseAuthentication();
app.UseAuthorization();
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.MapMetrics();
diff --git a/src/MemeVault.Application/Commands/UpdateMedia/UpdateMediaCommand.cs b/src/MemeVault.Application/Commands/UpdateMedia/UpdateMediaCommand.cs
new file mode 100644
index 0000000..deabf81
--- /dev/null
+++ b/src/MemeVault.Application/Commands/UpdateMedia/UpdateMediaCommand.cs
@@ -0,0 +1,14 @@
+using MediatR;
+
+namespace MemeVault.Application.Commands.UpdateMedia;
+
+///
+/// Обновляет caption и/или теги медиа-элемента.
+/// Tags — полная замена: пустой список очищает все теги.
+///
+public sealed record UpdateMediaCommand(
+ Guid MediaItemId,
+ long RequestingTelegramId,
+ string? Caption,
+ IReadOnlyList Tags
+) : IRequest;
diff --git a/src/MemeVault.Application/Commands/UpdateMedia/UpdateMediaCommandHandler.cs b/src/MemeVault.Application/Commands/UpdateMedia/UpdateMediaCommandHandler.cs
new file mode 100644
index 0000000..b30d2bc
--- /dev/null
+++ b/src/MemeVault.Application/Commands/UpdateMedia/UpdateMediaCommandHandler.cs
@@ -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
+{
+ public async Task 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;
+ }
+}