61 lines
2.0 KiB
C#
61 lines
2.0 KiB
C#
using MediatR;
|
|
using MemeVault.Application.Common;
|
|
using MemeVault.Domain.Aggregates.MediaItem;
|
|
using MemeVault.Domain.Exceptions;
|
|
using MemeVault.Domain.Repositories;
|
|
using MemeVault.Domain.ValueObjects;
|
|
|
|
namespace MemeVault.Application.Commands.SaveMedia;
|
|
|
|
public sealed class SaveMediaCommandHandler : IRequestHandler<SaveMediaCommand, Guid>
|
|
{
|
|
private readonly IMediaItemRepository _mediaItems;
|
|
private readonly ICollectionRepository _collections;
|
|
private readonly IUnitOfWork _uow;
|
|
|
|
public SaveMediaCommandHandler(
|
|
IMediaItemRepository mediaItems,
|
|
ICollectionRepository collections,
|
|
IUnitOfWork uow)
|
|
{
|
|
_mediaItems = mediaItems;
|
|
_collections = collections;
|
|
_uow = uow;
|
|
}
|
|
|
|
public async Task<Guid> Handle(SaveMediaCommand request, CancellationToken cancellationToken)
|
|
{
|
|
var tags = request.Tags.Select(t => new Tag(t));
|
|
|
|
// Определяем целевую коллекцию: явно указанная или Inbox
|
|
Guid collectionId;
|
|
if (request.CollectionId.HasValue)
|
|
{
|
|
var col = await _collections.GetByIdAsync(request.CollectionId.Value, cancellationToken);
|
|
if (col is null || col.OwnerTelegramId != request.OwnerTelegramId)
|
|
throw new DomainException("Target collection not found.");
|
|
collectionId = col.Id;
|
|
}
|
|
else
|
|
{
|
|
var inbox = await _collections.GetInboxAsync(request.OwnerTelegramId, cancellationToken)
|
|
?? throw new DomainException("User inbox not found.");
|
|
collectionId = inbox.Id;
|
|
}
|
|
|
|
var item = MediaItem.Create(
|
|
request.OwnerTelegramId,
|
|
collectionId,
|
|
request.Source,
|
|
request.MediaType,
|
|
request.Caption,
|
|
request.MediaGroupId,
|
|
tags);
|
|
|
|
await _mediaItems.AddAsync(item, cancellationToken);
|
|
await _uow.SaveChangesAsync(cancellationToken);
|
|
|
|
return item.Id;
|
|
}
|
|
}
|