too many changes
This commit is contained in:
+8
-15
@@ -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;
|
||||
}
|
||||
|
||||
+1
-1
@@ -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(
|
||||
|
||||
+3
-1
@@ -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?>;
|
||||
|
||||
+2
-1
@@ -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);
|
||||
|
||||
+3
-5
@@ -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>;
|
||||
+33
@@ -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>;
|
||||
+26
@@ -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;
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -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);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace MemeVault.Application.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Fetches a Telegram file, caches it in S3, and returns a pre-signed download URL.
|
||||
/// </summary>
|
||||
public interface ITelegramFileCacheService
|
||||
{
|
||||
/// <param name="telegramFileId">Telegram file_id to fetch and cache.</param>
|
||||
/// <param name="urlExpiry">How long the returned pre-signed URL should remain valid.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A temporary pre-signed URL pointing to the cached file in S3.</returns>
|
||||
Task<string> GetCachedUrlAsync(string telegramFileId, TimeSpan urlExpiry, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using MemeVault.Domain.Aggregates.MediaItem;
|
||||
|
||||
namespace MemeVault.Application.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Отправляет медиа-элемент в Telegram-чат через answerWebAppQuery.
|
||||
/// Используется когда Mini App открыта из меню «Приложить».
|
||||
/// </summary>
|
||||
public interface ITelegramQueryAnswerer
|
||||
{
|
||||
Task AnswerAsync(string queryId, MediaItem item, CancellationToken ct = default);
|
||||
}
|
||||
@@ -15,5 +15,6 @@ public sealed record CollectionInviteDto(
|
||||
CollectionRole Role,
|
||||
bool IsRevoked,
|
||||
DateTimeOffset CreatedAt,
|
||||
DateTimeOffset? RevokedAt
|
||||
DateTimeOffset? RevokedAt,
|
||||
DateTimeOffset? ExpiresAt
|
||||
);
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ public sealed class GetCollectionInvitesQueryHandler
|
||||
|
||||
return invites
|
||||
.Select(i => new CollectionInviteDto(
|
||||
i.Id, i.Token, i.Role, i.IsRevoked, i.CreatedAt, i.RevokedAt))
|
||||
i.Id, i.Token, i.Role, i.IsRevoked, i.CreatedAt, i.RevokedAt, i.ExpiresAt))
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ public sealed record GetCollectionItemsQuery(
|
||||
public sealed record CollectionMediaItemDto(
|
||||
Guid Id,
|
||||
string? Reference,
|
||||
MediaType Type,
|
||||
MediaType MediaType,
|
||||
string? Caption,
|
||||
IReadOnlyList<string> Tags,
|
||||
DateTimeOffset CreatedAt
|
||||
|
||||
+2
-2
@@ -23,8 +23,8 @@ public sealed class GetCollectionItemsQueryHandler
|
||||
{
|
||||
var collection = await _collections.GetByIdAsync(request.CollectionId, cancellationToken);
|
||||
|
||||
// Return null → 404 when collection missing or belongs to someone else
|
||||
if (collection is null || collection.OwnerTelegramId != request.RequestingTelegramId)
|
||||
// null → 404: коллекция не найдена или пользователь не является участником/публичный доступ
|
||||
if (collection is null || !collection.CanView(request.RequestingTelegramId))
|
||||
return null;
|
||||
|
||||
var items = await _mediaItems.GetByCollectionAsync(request.CollectionId, cancellationToken);
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
using MediatR;
|
||||
|
||||
namespace MemeVault.Application.Queries.GetMediaDownloadUrl;
|
||||
|
||||
/// <summary>
|
||||
/// Returns a short-lived pre-signed URL so the Mini App can display a media item.
|
||||
/// </summary>
|
||||
/// <param name="MediaItemId">Id of the MediaItem to fetch.</param>
|
||||
/// <param name="RequestingUserTelegramId">Telegram id of the caller (for ownership check).</param>
|
||||
public record GetMediaDownloadUrlQuery(Guid MediaItemId, long RequestingUserTelegramId)
|
||||
: IRequest<string>;
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
using MediatR;
|
||||
using MemeVault.Application.Common;
|
||||
using MemeVault.Domain.Enums;
|
||||
using MemeVault.Domain.Exceptions;
|
||||
using MemeVault.Domain.Repositories;
|
||||
using MemeVault.Domain.ValueObjects;
|
||||
|
||||
namespace MemeVault.Application.Queries.GetMediaDownloadUrl;
|
||||
|
||||
public sealed class GetMediaDownloadUrlQueryHandler
|
||||
: IRequestHandler<GetMediaDownloadUrlQuery, string>
|
||||
{
|
||||
private static readonly TimeSpan UrlExpiry = TimeSpan.FromMinutes(15);
|
||||
|
||||
private readonly IMediaItemRepository _mediaItems;
|
||||
private readonly ITelegramFileCacheService _cache;
|
||||
|
||||
public GetMediaDownloadUrlQueryHandler(
|
||||
IMediaItemRepository mediaItems,
|
||||
ITelegramFileCacheService cache)
|
||||
{
|
||||
_mediaItems = mediaItems;
|
||||
_cache = cache;
|
||||
}
|
||||
|
||||
public async Task<string> Handle(GetMediaDownloadUrlQuery request, CancellationToken ct)
|
||||
{
|
||||
var item = await _mediaItems.GetByIdAsync(request.MediaItemId, ct)
|
||||
?? throw new DomainException("Media item not found.");
|
||||
|
||||
if (item.OwnerTelegramId != request.RequestingUserTelegramId)
|
||||
throw new DomainException("Access denied.");
|
||||
|
||||
if (item.Type == MediaType.Text || item.Source is null)
|
||||
throw new DomainException("This media item has no downloadable file.");
|
||||
|
||||
if (item.Source.Origin == MediaOrigin.S3)
|
||||
{
|
||||
// Already stored in S3 — just generate a presigned URL directly.
|
||||
return await _cache.GetCachedUrlAsync(item.Source.Reference!, UrlExpiry, ct);
|
||||
}
|
||||
|
||||
// Telegram source — go through cache (lock → S3 check → fetch → upload → presign).
|
||||
return await _cache.GetCachedUrlAsync(item.Source.Reference!, UrlExpiry, ct);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ public sealed record CollectionDto(
|
||||
string? Description,
|
||||
bool IsInbox,
|
||||
CollectionVisibility Visibility,
|
||||
bool IsNsfw,
|
||||
string? ShareToken,
|
||||
int ItemCount,
|
||||
DateTimeOffset CreatedAt
|
||||
|
||||
+6
-6
@@ -12,13 +12,12 @@ public sealed class GetUserCollectionsQueryHandler(
|
||||
GetUserCollectionsQuery request,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var cols = await collections.GetByOwnerAsync(request.OwnerTelegramId, ct);
|
||||
// Все коллекции, в которых пользователь — участник (любая роль), включая шаренные
|
||||
var cols = await collections.GetByMemberAsync(request.OwnerTelegramId, ct);
|
||||
|
||||
// Подсчёт элементов по коллекциям за один запрос
|
||||
var allItems = await mediaItems.GetByOwnerAsync(request.OwnerTelegramId, ct);
|
||||
var countByCollection = allItems
|
||||
.GroupBy(i => i.CollectionId)
|
||||
.ToDictionary(g => g.Key, g => g.Count());
|
||||
// Подсчёт элементов по всем коллекциям за один GROUP BY запрос
|
||||
var collectionIds = cols.Select(c => c.Id).ToList();
|
||||
var countByCollection = await mediaItems.GetCountsByCollectionIdsAsync(collectionIds, ct);
|
||||
|
||||
return cols.Select(c => new CollectionDto(
|
||||
c.Id,
|
||||
@@ -26,6 +25,7 @@ public sealed class GetUserCollectionsQueryHandler(
|
||||
c.Description,
|
||||
c.IsInbox,
|
||||
c.Visibility,
|
||||
c.IsNsfw,
|
||||
c.ShareToken,
|
||||
countByCollection.GetValueOrDefault(c.Id, 0),
|
||||
c.CreatedAt
|
||||
|
||||
@@ -10,14 +10,15 @@ namespace MemeVault.Application.Queries.SearchMedia;
|
||||
public sealed record SearchMediaQuery(
|
||||
long OwnerTelegramId,
|
||||
string RawQuery,
|
||||
int Limit = 50
|
||||
int Limit = 50,
|
||||
bool IncludeNsfw = true
|
||||
) : IRequest<IReadOnlyList<MediaItemDto>>;
|
||||
|
||||
public sealed record MediaItemDto(
|
||||
Guid Id,
|
||||
Guid CollectionId,
|
||||
string? FileId,
|
||||
MediaType Type,
|
||||
MediaType MediaType,
|
||||
string? Caption,
|
||||
IReadOnlyList<string> Tags,
|
||||
DateTimeOffset CreatedAt
|
||||
|
||||
@@ -23,6 +23,7 @@ public sealed class SearchMediaQueryHandler : IRequestHandler<SearchMediaQuery,
|
||||
request.OwnerTelegramId,
|
||||
query,
|
||||
request.Limit,
|
||||
request.IncludeNsfw,
|
||||
cancellationToken);
|
||||
|
||||
return items.Select(i => new MediaItemDto(
|
||||
|
||||
Reference in New Issue
Block a user