too many changes

This commit is contained in:
2026-10-07 02:17:30 +04:00
parent 0c7f3bce90
commit bcf985c17d
74 changed files with 4048 additions and 78 deletions
@@ -1,6 +1,5 @@
using MediatR;
using MemeVault.Application.Common;
using MemeVault.Domain.Enums;
using MemeVault.Domain.Exceptions;
using MemeVault.Domain.Repositories;
@@ -27,25 +26,19 @@ public sealed class AcceptCollectionInviteCommandHandler
AcceptCollectionInviteCommand request, CancellationToken cancellationToken)
{
var invite = await _invites.GetByTokenAsync(request.Token, cancellationToken);
if (invite is null || invite.IsRevoked)
if (invite is null || invite.IsRevoked || invite.IsExpired)
return null;
var collection = await _collections.GetByIdAsync(invite.CollectionId, cancellationToken)
?? throw new DomainException("Collection no longer exists.");
// Владелец не может принять инвайт в собственную коллекцию
if (collection.OwnerTelegramId == request.AcceptingTelegramId)
return collection.Id;
// Если уже участник — просто возвращаем коллекцию (идемпотентность)
if (collection.GetRole(request.AcceptingTelegramId) is not null)
return collection.Id;
// Owner создаёт инвайт с правами requestingTelegramId, добавляем участника
collection.AddMember(request.AcceptingTelegramId, invite.Role, collection.OwnerTelegramId);
await _collections.UpdateAsync(collection, cancellationToken);
await _uow.SaveChangesAsync(cancellationToken);
// Инвариант "уже участник/владелец → идемпотентно" живёт на агрегате.
var added = collection.TryAcceptInvite(request.AcceptingTelegramId, invite.Role);
if (added)
{
await _collections.UpdateAsync(collection, cancellationToken);
await _uow.SaveChangesAsync(cancellationToken);
}
return collection.Id;
}
@@ -19,7 +19,7 @@ public sealed class CopyMediaToCollectionCommandHandler(
return null;
var target = await collections.GetByIdAsync(request.TargetCollectionId, ct);
if (target is null || target.OwnerTelegramId != request.RequestingTelegramId)
if (target is null || !target.CanWrite(request.RequestingTelegramId))
throw new DomainException("Target collection not found.");
var copy = MediaItem.Create(
@@ -6,9 +6,11 @@ namespace MemeVault.Application.Commands.CreateCollectionInvite;
/// <param name="CollectionId">Коллекция, для которой создаётся инвайт.</param>
/// <param name="RequestingTelegramId">Telegram ID запрашивающего (должен быть Owner).</param>
/// <param name="Role">Роль, которую получит принявший (Viewer или Manager).</param>
/// <param name="ExpiresAt">Срок действия инвайта. null — инвайт бессрочный.</param>
/// <returns>Токен инвайта, или null если коллекция не найдена / нет прав.</returns>
public sealed record CreateCollectionInviteCommand(
Guid CollectionId,
long RequestingTelegramId,
CollectionRole Role
CollectionRole Role,
DateTimeOffset? ExpiresAt = null
) : IRequest<string?>;
@@ -37,7 +37,8 @@ public sealed class CreateCollectionInviteCommandHandler
var invite = CollectionInvite.Create(
collection.Id,
request.RequestingTelegramId,
request.Role);
request.Role,
request.ExpiresAt);
await _invites.AddAsync(invite, cancellationToken);
await _uow.SaveChangesAsync(cancellationToken);
@@ -1,6 +1,6 @@
using MediatR;
using MemeVault.Application.Common;
using MemeVault.Domain.Exceptions;
using MemeVault.Domain.Enums;
using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Commands.DeleteCollection;
@@ -13,12 +13,10 @@ public sealed class DeleteCollectionCommandHandler(
public async Task<bool> Handle(DeleteCollectionCommand request, CancellationToken ct)
{
var collection = await collections.GetByIdAsync(request.CollectionId, ct);
if (collection is null || collection.OwnerTelegramId != request.RequestingTelegramId)
if (collection is null || collection.GetRole(request.RequestingTelegramId) != CollectionRole.Owner)
return false;
if (collection.IsInbox)
throw new DomainException("Cannot delete the Inbox collection.");
collection.Delete(request.RequestingTelegramId); // бросает DomainException если IsInbox
await collections.RemoveAsync(collection, ct);
await unitOfWork.SaveChangesAsync(ct);
return true;
@@ -32,7 +32,7 @@ public sealed class SaveMediaCommandHandler : IRequestHandler<SaveMediaCommand,
if (request.CollectionId.HasValue)
{
var col = await _collections.GetByIdAsync(request.CollectionId.Value, cancellationToken);
if (col is null || col.OwnerTelegramId != request.OwnerTelegramId)
if (col is null || !col.CanWrite(request.OwnerTelegramId))
throw new DomainException("Target collection not found.");
collectionId = col.Id;
}
@@ -0,0 +1,15 @@
using MediatR;
namespace MemeVault.Application.Commands.SendMediaToChat;
/// <summary>
/// Отправляет сохранённый MediaItem в чат через Telegram answerWebAppQuery.
/// Вызывается когда Mini App открыта из меню «Приложить» и пользователь тапает по элементу.
/// </summary>
/// <param name="MediaItemId">Элемент для отправки.</param>
/// <param name="RequestingUserTelegramId">Telegram ID пользователя (для проверки владения).</param>
/// <param name="QueryId">query_id из Telegram WebApp initData.</param>
public record SendMediaToChatCommand(
Guid MediaItemId,
long RequestingUserTelegramId,
string QueryId) : IRequest<bool>;
@@ -0,0 +1,22 @@
using MediatR;
using MemeVault.Application.Common;
using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Commands.SendMediaToChat;
public sealed class SendMediaToChatCommandHandler(
IMediaItemRepository mediaItems,
ITelegramQueryAnswerer queryAnswerer)
: IRequestHandler<SendMediaToChatCommand, bool>
{
public async Task<bool> Handle(SendMediaToChatCommand request, CancellationToken ct)
{
var item = await mediaItems.GetByIdAsync(request.MediaItemId, ct);
if (item is null || item.OwnerTelegramId != request.RequestingUserTelegramId)
return false;
await queryAnswerer.AnswerAsync(request.QueryId, item, ct);
return true;
}
}
@@ -0,0 +1,12 @@
using MediatR;
namespace MemeVault.Application.Commands.SetCollectionInbox;
/// <summary>
/// Делает указанную коллекцию основной (Inbox) для пользователя.
/// Возвращает false, если коллекция не найдена или пользователь не владелец.
/// </summary>
public sealed record SetCollectionInboxCommand(
Guid CollectionId,
long RequestingTelegramId
) : IRequest<bool>;
@@ -0,0 +1,33 @@
using MediatR;
using MemeVault.Application.Common;
using MemeVault.Domain.Enums;
using MemeVault.Domain.Exceptions;
using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Commands.SetCollectionInbox;
public sealed class SetCollectionInboxCommandHandler(
ICollectionRepository collections,
IUnitOfWork unitOfWork)
: IRequestHandler<SetCollectionInboxCommand, bool>
{
public async Task<bool> Handle(SetCollectionInboxCommand request, CancellationToken ct)
{
var target = await collections.GetByIdAsync(request.CollectionId, ct);
if (target is null || target.GetRole(request.RequestingTelegramId) != CollectionRole.Owner)
return false;
if (target.IsInbox)
throw new DomainException("Collection is already the Inbox.");
// Снимаем флаг с текущего Inbox
var currentInbox = await collections.GetInboxAsync(request.RequestingTelegramId, ct);
currentInbox?.DemoteFromInbox();
// Промоция целевой коллекции
target.PromoteToInbox(request.RequestingTelegramId);
await unitOfWork.SaveChangesAsync(ct);
return true;
}
}
@@ -0,0 +1,9 @@
using MediatR;
namespace MemeVault.Application.Commands.SetCollectionNsfw;
public sealed record SetCollectionNsfwCommand(
Guid CollectionId,
long RequestingTelegramId,
bool IsNsfw
) : IRequest<bool>;
@@ -0,0 +1,26 @@
using MediatR;
using MemeVault.Application.Common;
using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Commands.SetCollectionNsfw;
public sealed class SetCollectionNsfwCommandHandler(
ICollectionRepository collections,
IUnitOfWork unitOfWork)
: IRequestHandler<SetCollectionNsfwCommand, bool>
{
public async Task<bool> Handle(SetCollectionNsfwCommand request, CancellationToken ct)
{
var collection = await collections.GetByIdAsync(request.CollectionId, ct);
// Коллекция не найдена или пользователь — не участник
if (collection is null || collection.GetRole(request.RequestingTelegramId) is null)
return false;
// Проверка роли Owner делегирована домену (бросит DomainException при нарушении)
collection.SetNsfw(request.IsNsfw, request.RequestingTelegramId);
await unitOfWork.SaveChangesAsync(ct);
return true;
}
}
@@ -12,7 +12,9 @@ public sealed class UpdateCollectionCommandHandler(
public async Task<bool> Handle(UpdateCollectionCommand request, CancellationToken ct)
{
var collection = await collections.GetByIdAsync(request.CollectionId, ct);
if (collection is null || collection.OwnerTelegramId != request.RequestingTelegramId)
// Если коллекции нет или пользователь — не участник, возвращаем 404.
// Если роль ниже Manager — domain.Rename() бросит DomainException.
if (collection is null || collection.GetRole(request.RequestingTelegramId) is null)
return false;
collection.Rename(request.Name, request.RequestingTelegramId);
@@ -20,19 +20,13 @@ public sealed class UpdateMediaCommandHandler(
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));
item.ReplaceTags(request.Tags.Select(r => new Tag(r)));
// Перемещение в другую коллекцию
if (request.CollectionId.HasValue && request.CollectionId.Value != item.CollectionId)
{
var target = await collections.GetByIdAsync(request.CollectionId.Value, ct);
if (target is null || target.OwnerTelegramId != request.RequestingTelegramId)
if (target is null || !target.CanWrite(request.RequestingTelegramId))
throw new DomainException("Target collection not found.");
item.MoveToCollection(target.Id);