too many changes
This commit is contained in:
@@ -4,6 +4,8 @@ using MemeVault.Application.Commands.CreateCollection;
|
||||
using MemeVault.Application.Commands.CreateCollectionInvite;
|
||||
using MemeVault.Application.Commands.DeleteCollection;
|
||||
using MemeVault.Application.Commands.RevokeCollectionInvite;
|
||||
using MemeVault.Application.Commands.SetCollectionInbox;
|
||||
using MemeVault.Application.Commands.SetCollectionNsfw;
|
||||
using MemeVault.Application.Commands.ShareCollection;
|
||||
using MemeVault.Application.Commands.UpdateCollection;
|
||||
using MemeVault.Application.Queries.GetCollectionInvites;
|
||||
@@ -96,7 +98,7 @@ public sealed class CollectionsController(IMediator mediator, CurrentUser curren
|
||||
CancellationToken ct)
|
||||
{
|
||||
var token = await mediator.Send(
|
||||
new CreateCollectionInviteCommand(id, currentUser.TelegramId, request.Role), ct);
|
||||
new CreateCollectionInviteCommand(id, currentUser.TelegramId, request.Role, request.ExpiresAt), ct);
|
||||
return token is null ? NotFound() : Ok(new { token });
|
||||
}
|
||||
|
||||
@@ -109,6 +111,28 @@ public sealed class CollectionsController(IMediator mediator, CurrentUser curren
|
||||
return ok ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
// PUT /api/collections/{id}/inbox
|
||||
[HttpPut("{id:guid}/inbox")]
|
||||
public async Task<IActionResult> SetInbox(Guid id, CancellationToken ct)
|
||||
{
|
||||
var ok = await mediator.Send(new SetCollectionInboxCommand(id, currentUser.TelegramId), ct);
|
||||
return ok ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
// PUT /api/collections/{id}/nsfw
|
||||
[HttpPut("{id:guid}/nsfw")]
|
||||
public async Task<IActionResult> SetNsfw(
|
||||
Guid id,
|
||||
[FromBody] SetNsfwRequest request,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var ok = await mediator.Send(
|
||||
new SetCollectionNsfwCommand(id, currentUser.TelegramId, request.IsNsfw),
|
||||
ct);
|
||||
|
||||
return ok ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
// PUT /api/collections/{id}/visibility
|
||||
[HttpPut("{id:guid}/visibility")]
|
||||
public async Task<IActionResult> SetVisibility(
|
||||
@@ -126,5 +150,6 @@ public sealed class CollectionsController(IMediator mediator, CurrentUser curren
|
||||
|
||||
public sealed record CreateCollectionRequest(string Name, string? Description);
|
||||
public sealed record UpdateCollectionRequest(string Name, string? Description);
|
||||
public sealed record SetNsfwRequest(bool IsNsfw);
|
||||
public sealed record SetVisibilityRequest(CollectionVisibility Visibility);
|
||||
public sealed record CreateInviteRequest(CollectionRole Role);
|
||||
public sealed record CreateInviteRequest(CollectionRole Role, DateTimeOffset? ExpiresAt = null);
|
||||
|
||||
@@ -3,6 +3,8 @@ using MemeVault.Api.Auth;
|
||||
using MemeVault.Application.Commands.CopyMediaToCollection;
|
||||
using MemeVault.Application.Commands.DeleteMedia;
|
||||
using MemeVault.Application.Commands.UpdateMedia;
|
||||
using MemeVault.Application.Commands.SendMediaToChat;
|
||||
using MemeVault.Application.Queries.GetMediaDownloadUrl;
|
||||
using MemeVault.Application.Queries.GetUserMedia;
|
||||
using MemeVault.Application.Queries.SearchMedia;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
@@ -15,17 +17,45 @@ namespace MemeVault.Api.Controllers;
|
||||
[Route("api/[controller]")]
|
||||
public sealed class MediaController(IMediator mediator, CurrentUser currentUser) : ControllerBase
|
||||
{
|
||||
// GET /api/media?q=...
|
||||
// GET /api/media?q=...&includeNsfw=true
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll([FromQuery] string? q, CancellationToken ct)
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] string? q,
|
||||
[FromQuery] bool includeNsfw = true,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var items = string.IsNullOrWhiteSpace(q)
|
||||
? await mediator.Send(new GetUserMediaQuery(currentUser.TelegramId), ct)
|
||||
: await mediator.Send(new SearchMediaQuery(currentUser.TelegramId, q), ct);
|
||||
: await mediator.Send(new SearchMediaQuery(currentUser.TelegramId, q, IncludeNsfw: includeNsfw), ct);
|
||||
|
||||
return Ok(items);
|
||||
}
|
||||
|
||||
// GET /api/media/{id}/download-url
|
||||
// Returns a short-lived pre-signed URL for displaying the media file.
|
||||
[HttpGet("{id:guid}/download-url")]
|
||||
public async Task<IActionResult> GetDownloadUrl(Guid id, CancellationToken ct)
|
||||
{
|
||||
var url = await mediator.Send(
|
||||
new GetMediaDownloadUrlQuery(id, currentUser.TelegramId), ct);
|
||||
|
||||
return Ok(new { url });
|
||||
}
|
||||
|
||||
// POST /api/media/{id}/send
|
||||
// Отправляет элемент в Telegram-чат через answerWebAppQuery (режим аттачмента).
|
||||
[HttpPost("{id:guid}/send")]
|
||||
public async Task<IActionResult> SendToChat(
|
||||
Guid id,
|
||||
[FromBody] SendToChatRequest request,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var ok = await mediator.Send(
|
||||
new SendMediaToChatCommand(id, currentUser.TelegramId, request.QueryId), ct);
|
||||
|
||||
return ok ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
// PATCH /api/media/{id}
|
||||
// Обновляет caption, теги и/или перемещает в другую коллекцию
|
||||
[HttpPatch("{id:guid}")]
|
||||
@@ -67,6 +97,8 @@ public sealed class MediaController(IMediator mediator, CurrentUser currentUser)
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record SendToChatRequest(string QueryId);
|
||||
|
||||
public sealed record UpdateMediaRequest(
|
||||
string? Caption,
|
||||
IReadOnlyList<string> Tags,
|
||||
|
||||
@@ -38,8 +38,8 @@ builder.Services
|
||||
{
|
||||
o.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateIssuer = false,
|
||||
ValidateAudience = false,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = jwtOpts.Issuer,
|
||||
@@ -53,7 +53,10 @@ builder.Services
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddExceptionHandler<DomainExceptionHandler>();
|
||||
builder.Services.AddAuthorization();
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddControllers()
|
||||
.AddJsonOptions(o =>
|
||||
o.JsonSerializerOptions.Converters.Add(
|
||||
new System.Text.Json.Serialization.JsonStringEnumConverter()));
|
||||
|
||||
// ── OpenAPI ───────────────────────────────────────────────────────────────────
|
||||
builder.Services.AddHealthChecks()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"Telegram": {
|
||||
"BotToken": ""
|
||||
"BotToken": "",
|
||||
"ApiBaseUrl": "https://api.telegram.org"
|
||||
},
|
||||
"Jwt": {
|
||||
"SecretKey": "",
|
||||
@@ -8,6 +9,13 @@
|
||||
"Audience": "memevault-miniapp",
|
||||
"ExpiryHours": 24
|
||||
},
|
||||
"S3": {
|
||||
"ServiceUrl": "http://minio:9000",
|
||||
"AccessKey": "memevault",
|
||||
"SecretKey": "changeme123",
|
||||
"BucketName": "memevault",
|
||||
"PublicUrl": "http://localhost:9000"
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"Postgres": "Host=localhost;Database=memevault;Username=memevault;Password=changeme",
|
||||
"Redis": "localhost:6379"
|
||||
|
||||
+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(
|
||||
|
||||
@@ -6,7 +6,6 @@ using MemeVault.Bot.Telegram.Handlers;
|
||||
using MemeVault.Bot.Telegram.InlineMode;
|
||||
using MemeVault.Infrastructure;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
@@ -24,14 +23,6 @@ builder.Services.AddSingleton<BotMetrics>();
|
||||
|
||||
builder.Services.Configure<BotOptions>(builder.Configuration.GetSection(BotOptions.Section));
|
||||
|
||||
builder.Services.AddSingleton<ITelegramBotClient>(sp =>
|
||||
{
|
||||
var opts = sp.GetRequiredService<IOptions<BotOptions>>().Value;
|
||||
var clientOptions = new TelegramBotClientOptions(
|
||||
token: opts.Token,
|
||||
baseUrl: string.IsNullOrWhiteSpace(opts.ApiBaseUrl) ? null : opts.ApiBaseUrl);
|
||||
return new TelegramBotClient(clientOptions);
|
||||
});
|
||||
|
||||
builder.Services.AddScoped<MessageHandler>();
|
||||
builder.Services.AddScoped<InlineQueryHandler>();
|
||||
|
||||
@@ -24,7 +24,7 @@ public sealed class InlineQueryHandler
|
||||
public async Task HandleAsync(InlineQuery inlineQuery, CancellationToken ct)
|
||||
{
|
||||
var results = await _mediator.Send(
|
||||
new SearchMediaQuery(inlineQuery.From.Id, inlineQuery.Query, Limit: 50), ct);
|
||||
new SearchMediaQuery(inlineQuery.From.Id, inlineQuery.Query, Limit: 10, IncludeNsfw: false), ct);
|
||||
|
||||
var answers = results
|
||||
.Select(ToInlineResult)
|
||||
@@ -43,7 +43,7 @@ public sealed class InlineQueryHandler
|
||||
{
|
||||
var id = item.Id.ToString();
|
||||
|
||||
return item.Type switch
|
||||
return item.MediaType switch
|
||||
{
|
||||
MediaType.Photo => new InlineQueryResultCachedPhoto(id, item.FileId!)
|
||||
{
|
||||
|
||||
@@ -26,6 +26,9 @@ public sealed class Collection
|
||||
/// <summary>Системная коллекция входящих. Нельзя удалить или переименовать.</summary>
|
||||
public bool IsInbox { get; private set; }
|
||||
|
||||
/// <summary>Коллекция содержит контент 18+. Скрывается в inline-режиме.</summary>
|
||||
public bool IsNsfw { get; private set; }
|
||||
|
||||
/// <summary>Токен для доступа по ссылке (для Visibility = LinkOnly и Public).</summary>
|
||||
public string? ShareToken { get; private set; }
|
||||
|
||||
@@ -102,7 +105,15 @@ public sealed class Collection
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
// ── Видимость и шаринг ────────────────────────────────────────────────────
|
||||
// ── Видимость, NSFW и шаринг ─────────────────────────────────────────────
|
||||
|
||||
/// <summary>Устанавливает NSFW-флаг коллекции. Только Owner.</summary>
|
||||
public void SetNsfw(bool isNsfw, long requestingTelegramId)
|
||||
{
|
||||
EnsureRole(requestingTelegramId, CollectionRole.Owner);
|
||||
IsNsfw = isNsfw;
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
public void SetVisibility(CollectionVisibility visibility, long requestingTelegramId)
|
||||
{
|
||||
@@ -132,6 +143,58 @@ public sealed class Collection
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
// ── Удаление ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Проверяет, что коллекцию можно удалить, и бросает <see cref="DomainException"/> если нет.
|
||||
/// Фактическое удаление из хранилища выполняет репозиторий.
|
||||
/// </summary>
|
||||
public void Delete(long requestingTelegramId)
|
||||
{
|
||||
EnsureRole(requestingTelegramId, CollectionRole.Owner);
|
||||
if (IsInbox)
|
||||
throw new DomainException("Cannot delete the Inbox collection.");
|
||||
}
|
||||
|
||||
// ── Inbox ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Делает коллекцию основной (Inbox). Вызывать только после снятия флага с текущего Inbox.
|
||||
/// </summary>
|
||||
public void PromoteToInbox(long requestingTelegramId)
|
||||
{
|
||||
EnsureRole(requestingTelegramId, CollectionRole.Owner);
|
||||
if (IsInbox)
|
||||
throw new DomainException("Collection is already the Inbox.");
|
||||
IsInbox = true;
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
/// <summary>Снимает флаг Inbox. Вызывать перед промоцией другой коллекции.</summary>
|
||||
public void DemoteFromInbox()
|
||||
{
|
||||
IsInbox = false;
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
// ── Инвайты ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Добавляет принимающего инвайт как участника коллекции.
|
||||
/// Если пользователь уже является участником (или владельцем) — ничего не делает (идемпотентно).
|
||||
/// Авторизация производится через инвайт-токен, а не через requestingTelegramId.
|
||||
/// </summary>
|
||||
/// <returns>true — участник добавлен; false — уже был участником, изменений нет.</returns>
|
||||
public bool TryAcceptInvite(long acceptingTelegramId, CollectionRole inviteRole)
|
||||
{
|
||||
if (GetRole(acceptingTelegramId) is not null)
|
||||
return false;
|
||||
|
||||
_members.Add(new CollectionMember(Id, acceptingTelegramId, inviteRole));
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Доступ ────────────────────────────────────────────────────────────────
|
||||
|
||||
public bool CanView(long telegramId)
|
||||
@@ -140,6 +203,13 @@ public sealed class Collection
|
||||
return _members.Any(m => m.TelegramId == telegramId);
|
||||
}
|
||||
|
||||
/// <summary>Пользователь может добавлять/изменять элементы коллекции (Менеджер или Владелец).</summary>
|
||||
public bool CanWrite(long telegramId)
|
||||
{
|
||||
var role = GetRole(telegramId);
|
||||
return role is not null && role >= CollectionRole.Manager;
|
||||
}
|
||||
|
||||
public CollectionRole? GetRole(long telegramId) =>
|
||||
_members.FirstOrDefault(m => m.TelegramId == telegramId)?.Role;
|
||||
|
||||
|
||||
@@ -24,10 +24,16 @@ public sealed class CollectionInvite
|
||||
public bool IsRevoked { get; private set; }
|
||||
public DateTimeOffset? RevokedAt { get; private set; }
|
||||
|
||||
/// <summary>Дата истечения инвайта. null — инвайт бессрочный (действует до отзыва).</summary>
|
||||
public DateTimeOffset? ExpiresAt { get; private set; }
|
||||
|
||||
/// <summary>Инвайт истёк по сроку (не связан с ручным отзывом).</summary>
|
||||
public bool IsExpired => ExpiresAt.HasValue && DateTimeOffset.UtcNow > ExpiresAt.Value;
|
||||
|
||||
// EF Core constructor
|
||||
private CollectionInvite() { }
|
||||
|
||||
private CollectionInvite(Guid collectionId, long createdBy, CollectionRole role)
|
||||
private CollectionInvite(Guid collectionId, long createdBy, CollectionRole role, DateTimeOffset? expiresAt)
|
||||
{
|
||||
Id = Guid.NewGuid();
|
||||
CollectionId = collectionId;
|
||||
@@ -35,15 +41,23 @@ public sealed class CollectionInvite
|
||||
Role = role;
|
||||
Token = GenerateToken();
|
||||
CreatedAt = DateTimeOffset.UtcNow;
|
||||
ExpiresAt = expiresAt;
|
||||
IsRevoked = false;
|
||||
}
|
||||
|
||||
public static CollectionInvite Create(Guid collectionId, long createdBy, CollectionRole role)
|
||||
public static CollectionInvite Create(
|
||||
Guid collectionId,
|
||||
long createdBy,
|
||||
CollectionRole role,
|
||||
DateTimeOffset? expiresAt = null)
|
||||
{
|
||||
if (role == CollectionRole.Owner)
|
||||
throw new DomainException("Cannot create an invite with Owner role.");
|
||||
|
||||
return new CollectionInvite(collectionId, createdBy, role);
|
||||
if (expiresAt.HasValue && expiresAt.Value <= DateTimeOffset.UtcNow)
|
||||
throw new DomainException("Invite expiry must be in the future.");
|
||||
|
||||
return new CollectionInvite(collectionId, createdBy, role, expiresAt);
|
||||
}
|
||||
|
||||
public void Revoke()
|
||||
|
||||
@@ -11,6 +11,7 @@ namespace MemeVault.Domain.Aggregates.MediaItem;
|
||||
/// </summary>
|
||||
public sealed class MediaItem
|
||||
{
|
||||
// Не readonly: EF Core перезаписывает ссылку при материализации из text[] через value conversion.
|
||||
private List<Tag> _tags = [];
|
||||
private readonly List<IDomainEvent> _domainEvents = [];
|
||||
|
||||
@@ -122,5 +123,17 @@ public sealed class MediaItem
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
/// <summary>Полностью заменяет набор тегов. Дубли игнорируются. Лимит — 20 тегов.</summary>
|
||||
public void ReplaceTags(IEnumerable<Tag> newTags)
|
||||
{
|
||||
var distinct = newTags.Distinct().ToList();
|
||||
if (distinct.Count > 20)
|
||||
throw new DomainException("Cannot have more than 20 tags per item.");
|
||||
|
||||
_tags.Clear();
|
||||
_tags.AddRange(distinct);
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
public void ClearDomainEvents() => _domainEvents.Clear();
|
||||
}
|
||||
|
||||
@@ -8,6 +8,9 @@ public interface ICollectionRepository
|
||||
Task<Collection?> GetByShareTokenAsync(string shareToken, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<Collection>> GetByOwnerAsync(long ownerTelegramId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Все коллекции, в которых пользователь является участником (любая роль).</summary>
|
||||
Task<IReadOnlyList<Collection>> GetByMemberAsync(long telegramId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Возвращает системную коллекцию Inbox пользователя.</summary>
|
||||
Task<Collection?> GetInboxAsync(long ownerTelegramId, CancellationToken ct = default);
|
||||
|
||||
|
||||
@@ -12,13 +12,19 @@ public interface IMediaItemRepository
|
||||
|
||||
/// <summary>
|
||||
/// Поиск с поддержкой тег-фильтров (#tag, -#tag) и полнотекстового поиска по caption.
|
||||
/// <paramref name="includeNsfw"/> = false исключает элементы из коллекций с флагом IsNsfw.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<MediaItem>> SearchAsync(
|
||||
long ownerTelegramId,
|
||||
TagSearchQuery query,
|
||||
int limit = 50,
|
||||
bool includeNsfw = true,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>Количество элементов в каждой из указанных коллекций за один запрос.</summary>
|
||||
Task<Dictionary<Guid, int>> GetCountsByCollectionIdsAsync(
|
||||
IReadOnlyList<Guid> collectionIds, CancellationToken ct = default);
|
||||
|
||||
Task AddAsync(MediaItem item, CancellationToken ct = default);
|
||||
Task RemoveAsync(MediaItem item, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using MemeVault.Domain.Exceptions;
|
||||
|
||||
namespace MemeVault.Domain.ValueObjects;
|
||||
|
||||
public sealed record Tag
|
||||
@@ -7,12 +9,12 @@ public sealed record Tag
|
||||
public Tag(string value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
throw new ArgumentException("Tag cannot be empty.", nameof(value));
|
||||
throw new DomainException("Tag cannot be empty.");
|
||||
|
||||
Value = value.Trim().ToLowerInvariant();
|
||||
|
||||
if (Value.Length > 50)
|
||||
throw new ArgumentException("Tag must be 50 characters or less.", nameof(value));
|
||||
throw new DomainException("Tag must be 50 characters or less.");
|
||||
}
|
||||
|
||||
public static implicit operator string(Tag tag) => tag.Value;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using MemeVault.Domain.Exceptions;
|
||||
|
||||
namespace MemeVault.Domain.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
@@ -11,7 +13,7 @@ public sealed record TelegramFileId
|
||||
public TelegramFileId(string value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
throw new ArgumentException("FileId cannot be empty.", nameof(value));
|
||||
throw new DomainException("FileId cannot be empty.");
|
||||
|
||||
Value = value;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
using Amazon.Runtime;
|
||||
using Amazon.S3;
|
||||
using MemeVault.Application.Common;
|
||||
using MemeVault.Domain.Repositories;
|
||||
using MemeVault.Infrastructure.Options;
|
||||
using MemeVault.Infrastructure.Persistence;
|
||||
using MemeVault.Infrastructure.Persistence.Repositories;
|
||||
using MemeVault.Infrastructure.Persistence.Repositories;
|
||||
using MemeVault.Infrastructure.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StackExchange.Redis;
|
||||
using Telegram.Bot;
|
||||
|
||||
namespace MemeVault.Infrastructure;
|
||||
|
||||
@@ -15,6 +21,7 @@ public static class InfrastructureServiceExtensions
|
||||
this IServiceCollection services,
|
||||
IConfiguration config)
|
||||
{
|
||||
// ── PostgreSQL / EF Core ──────────────────────────────────────────────
|
||||
services.AddDbContext<AppDbContext>(opts =>
|
||||
opts.UseNpgsql(config.GetConnectionString("Postgres")));
|
||||
|
||||
@@ -24,8 +31,57 @@ public static class InfrastructureServiceExtensions
|
||||
services.AddScoped<ICollectionRepository, CollectionRepository>();
|
||||
services.AddScoped<ICollectionInviteRepository, CollectionInviteRepository>();
|
||||
|
||||
var redisConn = config.GetConnectionString("Redis") ?? "localhost:6379";
|
||||
services.AddStackExchangeRedisCache(opts => opts.Configuration = redisConn);
|
||||
// ── Redis ─────────────────────────────────────────────────────────────
|
||||
var redisConn = config.GetConnectionString("Redis")
|
||||
?? throw new InvalidOperationException(
|
||||
"Required configuration value 'ConnectionStrings:Redis' is missing or empty.");
|
||||
|
||||
var multiplexer = ConnectionMultiplexer.Connect(redisConn);
|
||||
services.AddSingleton<IConnectionMultiplexer>(multiplexer);
|
||||
services.AddStackExchangeRedisCache(opts =>
|
||||
{
|
||||
opts.ConnectionMultiplexerFactory = () => Task.FromResult<IConnectionMultiplexer>(multiplexer);
|
||||
});
|
||||
|
||||
// ── Options ───────────────────────────────────────────────────────────
|
||||
services.AddOptions<S3Options>()
|
||||
.BindConfiguration(S3Options.Section)
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddOptions<TelegramApiOptions>()
|
||||
.BindConfiguration(TelegramApiOptions.Section)
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
|
||||
// ── S3 / MinIO ────────────────────────────────────────────────────────
|
||||
services.AddSingleton<IAmazonS3>(sp =>
|
||||
{
|
||||
var opts = sp.GetRequiredService<IOptions<S3Options>>().Value;
|
||||
var credentials = new BasicAWSCredentials(opts.AccessKey, opts.SecretKey);
|
||||
var cfg = new AmazonS3Config
|
||||
{
|
||||
ServiceURL = opts.ServiceUrl,
|
||||
ForcePathStyle = true,
|
||||
UseHttp = opts.ServiceUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase),
|
||||
};
|
||||
return new AmazonS3Client(credentials, cfg);
|
||||
});
|
||||
|
||||
services.AddScoped<IFileStorage, S3FileStorage>();
|
||||
|
||||
// ── Telegram Bot Client ───────────────────────────────────────────────
|
||||
services.AddSingleton<ITelegramBotClient>(sp =>
|
||||
{
|
||||
var opts = sp.GetRequiredService<IOptions<TelegramApiOptions>>().Value;
|
||||
var clientOptions = new TelegramBotClientOptions(
|
||||
token: opts.BotToken,
|
||||
baseUrl: opts.ApiBaseUrl);
|
||||
return new TelegramBotClient(clientOptions);
|
||||
});
|
||||
|
||||
services.AddScoped<ITelegramFileCacheService, TelegramFileCacheService>();
|
||||
services.AddScoped<ITelegramQueryAnswerer, TelegramQueryAnswererService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -11,9 +11,13 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AWSSDK.S3" Version="3.7.*" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.12" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.DataAnnotations" Version="10.0.12" />
|
||||
<PackageReference Include="Telegram.Bot" Version="22.10.3.2" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using MemeVault.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MemeVault.Infrastructure.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20261006171407_AddCollectionNsfw")]
|
||||
partial class AddCollectionNsfw
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.12")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.BotUser.BotUser", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("FirstName")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("first_name");
|
||||
|
||||
b.Property<DateTimeOffset>("LastSeenAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("last_seen_at");
|
||||
|
||||
b.Property<long>("TelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("telegram_id");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("username");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TelegramId")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_bot_users_telegram_id");
|
||||
|
||||
b.ToTable("bot_users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)")
|
||||
.HasColumnName("description");
|
||||
|
||||
b.Property<bool>("IsInbox")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_inbox");
|
||||
|
||||
b.Property<bool>("IsNsfw")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("boolean")
|
||||
.HasDefaultValue(false)
|
||||
.HasColumnName("is_nsfw");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<string>("ShareToken")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("share_token");
|
||||
|
||||
b.Property<DateTimeOffset?>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string>("Visibility")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("visibility");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ShareToken")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collections_share_token")
|
||||
.HasFilter("share_token IS NOT NULL");
|
||||
|
||||
b.ToTable("collections", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.CollectionInvite.CollectionInvite", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<long>("CreatedByTelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("created_by_telegram_id");
|
||||
|
||||
b.Property<bool>("IsRevoked")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_revoked");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("revoked_at");
|
||||
|
||||
b.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("role");
|
||||
|
||||
b.Property<string>("Token")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)")
|
||||
.HasColumnName("token");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CollectionId")
|
||||
.HasDatabaseName("ix_collection_invites_collection_id");
|
||||
|
||||
b.HasIndex("Token")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collection_invites_token");
|
||||
|
||||
b.ToTable("collection_invites", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Caption")
|
||||
.HasMaxLength(4096)
|
||||
.HasColumnType("character varying(4096)")
|
||||
.HasColumnName("caption");
|
||||
|
||||
b.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("MediaGroupId")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("media_group_id");
|
||||
|
||||
b.Property<long>("OwnerTelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("owner_telegram_id");
|
||||
|
||||
b.Property<string>("Type")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("type");
|
||||
|
||||
b.Property<DateTimeOffset?>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string[]>("_tags")
|
||||
.IsRequired()
|
||||
.HasColumnType("text[]")
|
||||
.HasColumnName("tags");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CollectionId")
|
||||
.HasDatabaseName("ix_media_items_collection");
|
||||
|
||||
b.HasIndex("OwnerTelegramId")
|
||||
.HasDatabaseName("ix_media_items_owner");
|
||||
|
||||
b.HasIndex("_tags")
|
||||
.HasDatabaseName("ix_media_items_tags");
|
||||
|
||||
NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("_tags"), "gin");
|
||||
|
||||
b.ToTable("media_items", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
|
||||
{
|
||||
b.OwnsMany("MemeVault.Domain.Aggregates.Collection.CollectionMember", "Members", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b1.Property<DateTimeOffset>("AddedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("added_at");
|
||||
|
||||
b1.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b1.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("role");
|
||||
|
||||
b1.Property<long>("TelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("telegram_id");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("CollectionId", "TelegramId")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collection_members_unique");
|
||||
|
||||
b1.ToTable("collection_members", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("CollectionId");
|
||||
});
|
||||
|
||||
b.Navigation("Members");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
|
||||
{
|
||||
b.OwnsOne("MemeVault.Domain.ValueObjects.MediaSource", "Source", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("MediaItemId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b1.Property<string>("Origin")
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("source_origin");
|
||||
|
||||
b1.Property<string>("Reference")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)")
|
||||
.HasColumnName("source_reference");
|
||||
|
||||
b1.HasKey("MediaItemId");
|
||||
|
||||
b1.ToTable("media_items");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("MediaItemId");
|
||||
});
|
||||
|
||||
b.Navigation("Source");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MemeVault.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddCollectionNsfw : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "is_nsfw",
|
||||
table: "collections",
|
||||
type: "boolean",
|
||||
nullable: false,
|
||||
defaultValue: false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "is_nsfw",
|
||||
table: "collections");
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+306
@@ -0,0 +1,306 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using MemeVault.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MemeVault.Infrastructure.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20261006221608_AddCollectionInviteExpiry")]
|
||||
partial class AddCollectionInviteExpiry
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.12")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.BotUser.BotUser", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("FirstName")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("first_name");
|
||||
|
||||
b.Property<DateTimeOffset>("LastSeenAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("last_seen_at");
|
||||
|
||||
b.Property<long>("TelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("telegram_id");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("username");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TelegramId")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_bot_users_telegram_id");
|
||||
|
||||
b.ToTable("bot_users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)")
|
||||
.HasColumnName("description");
|
||||
|
||||
b.Property<bool>("IsInbox")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_inbox");
|
||||
|
||||
b.Property<bool>("IsNsfw")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("boolean")
|
||||
.HasDefaultValue(false)
|
||||
.HasColumnName("is_nsfw");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<string>("ShareToken")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("share_token");
|
||||
|
||||
b.Property<DateTimeOffset?>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string>("Visibility")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("visibility");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ShareToken")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collections_share_token")
|
||||
.HasFilter("share_token IS NOT NULL");
|
||||
|
||||
b.ToTable("collections", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.CollectionInvite.CollectionInvite", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<long>("CreatedByTelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("created_by_telegram_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("expires_at");
|
||||
|
||||
b.Property<bool>("IsRevoked")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_revoked");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("revoked_at");
|
||||
|
||||
b.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("role");
|
||||
|
||||
b.Property<string>("Token")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)")
|
||||
.HasColumnName("token");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CollectionId")
|
||||
.HasDatabaseName("ix_collection_invites_collection_id");
|
||||
|
||||
b.HasIndex("Token")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collection_invites_token");
|
||||
|
||||
b.ToTable("collection_invites", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Caption")
|
||||
.HasMaxLength(4096)
|
||||
.HasColumnType("character varying(4096)")
|
||||
.HasColumnName("caption");
|
||||
|
||||
b.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("MediaGroupId")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("media_group_id");
|
||||
|
||||
b.Property<long>("OwnerTelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("owner_telegram_id");
|
||||
|
||||
b.Property<string>("Type")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("type");
|
||||
|
||||
b.Property<DateTimeOffset?>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string[]>("_tags")
|
||||
.IsRequired()
|
||||
.HasColumnType("text[]")
|
||||
.HasColumnName("tags");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CollectionId")
|
||||
.HasDatabaseName("ix_media_items_collection");
|
||||
|
||||
b.HasIndex("OwnerTelegramId")
|
||||
.HasDatabaseName("ix_media_items_owner");
|
||||
|
||||
b.HasIndex("_tags")
|
||||
.HasDatabaseName("ix_media_items_tags");
|
||||
|
||||
NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("_tags"), "gin");
|
||||
|
||||
b.ToTable("media_items", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
|
||||
{
|
||||
b.OwnsMany("MemeVault.Domain.Aggregates.Collection.CollectionMember", "Members", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b1.Property<DateTimeOffset>("AddedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("added_at");
|
||||
|
||||
b1.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b1.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("role");
|
||||
|
||||
b1.Property<long>("TelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("telegram_id");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("CollectionId", "TelegramId")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collection_members_unique");
|
||||
|
||||
b1.ToTable("collection_members", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("CollectionId");
|
||||
});
|
||||
|
||||
b.Navigation("Members");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
|
||||
{
|
||||
b.OwnsOne("MemeVault.Domain.ValueObjects.MediaSource", "Source", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("MediaItemId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b1.Property<string>("Origin")
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("source_origin");
|
||||
|
||||
b1.Property<string>("Reference")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)")
|
||||
.HasColumnName("source_reference");
|
||||
|
||||
b1.HasKey("MediaItemId");
|
||||
|
||||
b1.ToTable("media_items");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("MediaItemId");
|
||||
});
|
||||
|
||||
b.Navigation("Source");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MemeVault.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddCollectionInviteExpiry : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "expires_at",
|
||||
table: "collection_invites",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "expires_at",
|
||||
table: "collection_invites");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,12 @@ namespace MemeVault.Infrastructure.Migrations
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_inbox");
|
||||
|
||||
b.Property<bool>("IsNsfw")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("boolean")
|
||||
.HasDefaultValue(false)
|
||||
.HasColumnName("is_nsfw");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
@@ -130,6 +136,10 @@ namespace MemeVault.Infrastructure.Migrations
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("created_by_telegram_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("expires_at");
|
||||
|
||||
b.Property<bool>("IsRevoked")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_revoked");
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace MemeVault.Infrastructure.Options;
|
||||
|
||||
public sealed class S3Options
|
||||
{
|
||||
public const string Section = "S3";
|
||||
|
||||
/// <summary>
|
||||
/// S3/MinIO endpoint — used both by the .NET SDK for uploads/downloads
|
||||
/// and as the base URL in generated presigned links.
|
||||
/// Must be reachable both from the server and from the browser.
|
||||
/// </summary>
|
||||
[Required]
|
||||
public string ServiceUrl { get; set; } = string.Empty;
|
||||
|
||||
[Required]
|
||||
public string AccessKey { get; set; } = string.Empty;
|
||||
|
||||
[Required]
|
||||
public string SecretKey { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Bucket where cached Telegram files are stored.</summary>
|
||||
[Required]
|
||||
public string BucketName { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace MemeVault.Infrastructure.Options;
|
||||
|
||||
/// <summary>
|
||||
/// Options for calling the Telegram Bot API from Infrastructure services.
|
||||
/// Reads from the same "Telegram" config section as MemeVault.Api.
|
||||
/// </summary>
|
||||
public sealed class TelegramApiOptions
|
||||
{
|
||||
public const string Section = "Telegram";
|
||||
|
||||
[Required]
|
||||
public string BotToken { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Custom Telegram Bot API server base URL (e.g. a local server).
|
||||
/// Null means the official https://api.telegram.org — the library handles the default.
|
||||
/// </summary>
|
||||
public string? ApiBaseUrl { get; set; }
|
||||
}
|
||||
@@ -29,6 +29,11 @@ public sealed class CollectionConfiguration : IEntityTypeConfiguration<Collectio
|
||||
.HasColumnName("is_inbox")
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(x => x.IsNsfw)
|
||||
.HasColumnName("is_nsfw")
|
||||
.IsRequired()
|
||||
.HasDefaultValue(false);
|
||||
|
||||
builder.Property(x => x.Visibility)
|
||||
.HasColumnName("visibility")
|
||||
.HasConversion<string>()
|
||||
|
||||
+1
@@ -39,6 +39,7 @@ public sealed class CollectionInviteConfiguration : IEntityTypeConfiguration<Col
|
||||
.HasDatabaseName("ix_collection_invites_collection_id");
|
||||
|
||||
builder.Property(x => x.CreatedAt).HasColumnName("created_at");
|
||||
builder.Property(x => x.ExpiresAt).HasColumnName("expires_at");
|
||||
builder.Property(x => x.IsRevoked).HasColumnName("is_revoked");
|
||||
builder.Property(x => x.RevokedAt).HasColumnName("revoked_at");
|
||||
}
|
||||
|
||||
@@ -32,6 +32,16 @@ public sealed class CollectionRepository : ICollectionRepository
|
||||
.ToListAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<Collection>> GetByMemberAsync(long telegramId, CancellationToken ct)
|
||||
{
|
||||
return await _db.Collections
|
||||
.Include(c => c.Members)
|
||||
.Where(c => c.Members.Any(m => m.TelegramId == telegramId))
|
||||
.OrderBy(x => x.IsInbox ? 0 : 1) // Inbox всегда первым
|
||||
.ThenBy(x => x.Name)
|
||||
.ToListAsync(ct);
|
||||
}
|
||||
|
||||
public Task<Collection?> GetInboxAsync(long ownerTelegramId, CancellationToken ct) =>
|
||||
_db.Collections
|
||||
.Include(c => c.Members)
|
||||
|
||||
@@ -42,12 +42,16 @@ public sealed class MediaItemRepository : IMediaItemRepository
|
||||
long ownerTelegramId,
|
||||
TagSearchQuery query,
|
||||
int limit,
|
||||
bool includeNsfw,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var sql = _db.MediaItems.Where(x => x.OwnerTelegramId == ownerTelegramId);
|
||||
|
||||
if (query.IsEmpty)
|
||||
{
|
||||
if (!includeNsfw)
|
||||
sql = sql.Where(x => !_db.Collections.Any(c => c.Id == x.CollectionId && c.IsNsfw));
|
||||
|
||||
return await sql
|
||||
.OrderByDescending(x => x.CreatedAt)
|
||||
.Take(limit)
|
||||
@@ -79,6 +83,9 @@ public sealed class MediaItemRepository : IMediaItemRepository
|
||||
conditions.Add($"caption ILIKE {{{idx}}}");
|
||||
}
|
||||
|
||||
if (!includeNsfw)
|
||||
conditions.Add("NOT EXISTS (SELECT 1 FROM collections c WHERE c.id = collection_id AND c.is_nsfw = true)");
|
||||
|
||||
var where = string.Join(" AND ", conditions);
|
||||
var rawSql = $"SELECT * FROM media_items WHERE {where} ORDER BY created_at DESC LIMIT {limit}";
|
||||
|
||||
@@ -87,6 +94,16 @@ public sealed class MediaItemRepository : IMediaItemRepository
|
||||
.ToListAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<Dictionary<Guid, int>> GetCountsByCollectionIdsAsync(
|
||||
IReadOnlyList<Guid> collectionIds, CancellationToken ct)
|
||||
{
|
||||
return await _db.MediaItems
|
||||
.Where(x => collectionIds.Contains(x.CollectionId))
|
||||
.GroupBy(x => x.CollectionId)
|
||||
.Select(g => new { CollectionId = g.Key, Count = g.Count() })
|
||||
.ToDictionaryAsync(x => x.CollectionId, x => x.Count, ct);
|
||||
}
|
||||
|
||||
public async Task AddAsync(MediaItem item, CancellationToken ct)
|
||||
{
|
||||
await _db.MediaItems.AddAsync(item, ct);
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
using Amazon.S3;
|
||||
using Amazon.S3.Model;
|
||||
using MemeVault.Application.Common;
|
||||
using MemeVault.Domain.ValueObjects;
|
||||
using MemeVault.Infrastructure.Options;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace MemeVault.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// S3/MinIO-backed implementation of <see cref="IFileStorage"/>.
|
||||
/// </summary>
|
||||
public sealed class S3FileStorage : IFileStorage
|
||||
{
|
||||
private readonly IAmazonS3 _s3;
|
||||
private readonly S3Options _opts;
|
||||
|
||||
public S3FileStorage(IAmazonS3 s3, IOptions<S3Options> opts)
|
||||
{
|
||||
_s3 = s3;
|
||||
_opts = opts.Value;
|
||||
}
|
||||
|
||||
public async Task<MediaSource> UploadAsync(
|
||||
Stream content,
|
||||
string objectKey,
|
||||
string contentType,
|
||||
long ownerTelegramId,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var request = new PutObjectRequest
|
||||
{
|
||||
BucketName = _opts.BucketName,
|
||||
Key = objectKey,
|
||||
InputStream = content,
|
||||
ContentType = contentType,
|
||||
// CalcMD5 + autoCloseStream defaults are fine
|
||||
};
|
||||
|
||||
await _s3.PutObjectAsync(request, ct);
|
||||
return MediaSource.FromS3(objectKey);
|
||||
}
|
||||
|
||||
public async Task<string> GetDownloadUrlAsync(
|
||||
string objectKey,
|
||||
TimeSpan expiry,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var request = new GetPreSignedUrlRequest
|
||||
{
|
||||
BucketName = _opts.BucketName,
|
||||
Key = objectKey,
|
||||
Expires = DateTime.UtcNow.Add(expiry),
|
||||
Protocol = _opts.ServiceUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
|
||||
? Protocol.HTTPS
|
||||
: Protocol.HTTP,
|
||||
};
|
||||
|
||||
return await _s3.GetPreSignedURLAsync(request);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(string objectKey, CancellationToken ct = default)
|
||||
{
|
||||
await _s3.DeleteObjectAsync(_opts.BucketName, objectKey, ct);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
using System.IO.Pipelines;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Amazon.S3;
|
||||
using Amazon.S3.Model;
|
||||
using MemeVault.Application.Common;
|
||||
using MemeVault.Infrastructure.Options;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StackExchange.Redis;
|
||||
using Telegram.Bot;
|
||||
|
||||
namespace MemeVault.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Fetches a Telegram file, caches it in S3, and returns a pre-signed download URL.
|
||||
///
|
||||
/// Flow per request:
|
||||
/// 1. Acquire Redis lock (SET … NX EX 60).
|
||||
/// 2. Check whether the object already exists in S3 (HeadObject).
|
||||
/// 3. If cache miss: call Telegram getFile → stream to S3 with ContentLength.
|
||||
/// 4. Generate and return a pre-signed URL regardless of cache hit/miss.
|
||||
/// 5. Release Redis lock.
|
||||
/// </summary>
|
||||
public sealed class TelegramFileCacheService : ITelegramFileCacheService
|
||||
{
|
||||
private const string CacheKeyPrefix = "cache/";
|
||||
private const string LockKeyPrefix = "lock:file:";
|
||||
private const int LockTtlSeconds = 60;
|
||||
|
||||
private readonly IConnectionMultiplexer _redis;
|
||||
private readonly IAmazonS3 _s3;
|
||||
private readonly IFileStorage _storage;
|
||||
private readonly ITelegramBotClient _botClient;
|
||||
private readonly S3Options _s3Opts;
|
||||
private readonly ILogger<TelegramFileCacheService> _logger;
|
||||
|
||||
public TelegramFileCacheService(
|
||||
IConnectionMultiplexer redis,
|
||||
IAmazonS3 s3,
|
||||
IFileStorage storage,
|
||||
ITelegramBotClient botClient,
|
||||
IOptions<S3Options> s3Opts,
|
||||
ILogger<TelegramFileCacheService> logger)
|
||||
{
|
||||
_redis = redis;
|
||||
_s3 = s3;
|
||||
_storage = storage;
|
||||
_botClient = botClient;
|
||||
_s3Opts = s3Opts.Value;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<string> GetCachedUrlAsync(
|
||||
string telegramFileId,
|
||||
TimeSpan urlExpiry,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var hash = ComputeHash(telegramFileId);
|
||||
var s3Key = $"{CacheKeyPrefix}{hash}";
|
||||
var lockKey = $"{LockKeyPrefix}{hash}";
|
||||
var db = _redis.GetDatabase();
|
||||
|
||||
// ── 1. Acquire Redis lock ─────────────────────────────────────────────
|
||||
var lockAcquired = await db.StringSetAsync(
|
||||
lockKey, "1",
|
||||
TimeSpan.FromSeconds(LockTtlSeconds),
|
||||
When.NotExists);
|
||||
|
||||
try
|
||||
{
|
||||
// ── 2. Check S3 ───────────────────────────────────────────────────
|
||||
var existsInS3 = await ObjectExistsAsync(s3Key, ct);
|
||||
|
||||
// ── 3. Cache miss: fetch from Telegram and upload to S3 ───────────
|
||||
if (!existsInS3)
|
||||
{
|
||||
_logger.LogInformation("Cache miss for fileId {FileId}, fetching from Telegram.", telegramFileId);
|
||||
await FetchAndCacheAsync(telegramFileId, s3Key, ct);
|
||||
}
|
||||
|
||||
// ── 4. Generate presigned URL ─────────────────────────────────────
|
||||
return await _storage.GetDownloadUrlAsync(s3Key, urlExpiry, ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// ── 5. Release lock (only if we acquired it) ──────────────────────
|
||||
if (lockAcquired)
|
||||
await db.KeyDeleteAsync(lockKey);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Private helpers ───────────────────────────────────────────────────────
|
||||
|
||||
private static string ComputeHash(string fileId)
|
||||
{
|
||||
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(fileId));
|
||||
return Convert.ToHexString(bytes).ToLowerInvariant();
|
||||
}
|
||||
|
||||
private async Task<bool> ObjectExistsAsync(string key, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _s3.GetObjectMetadataAsync(_s3Opts.BucketName, key, ct);
|
||||
return true;
|
||||
}
|
||||
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task FetchAndCacheAsync(string telegramFileId, string s3Key, CancellationToken ct)
|
||||
{
|
||||
// Resolve file_path and file_size via Bot API
|
||||
var file = await _botClient.GetFile(telegramFileId, ct);
|
||||
var filePath = file.FilePath ?? throw new InvalidOperationException("Telegram returned null file_path.");
|
||||
var contentType = InferContentType(filePath);
|
||||
|
||||
// Stream from Telegram to S3 via a pipe — no full buffering
|
||||
var pipe = new Pipe();
|
||||
|
||||
// Download runs on a thread-pool thread, writing into the pipe writer
|
||||
var downloadTask = Task.Run(async () =>
|
||||
{
|
||||
try { await _botClient.DownloadFile(filePath, pipe.Writer.AsStream(), ct); }
|
||||
finally { pipe.Writer.Complete(); }
|
||||
}, CancellationToken.None);
|
||||
|
||||
var putRequest = new PutObjectRequest
|
||||
{
|
||||
BucketName = _s3Opts.BucketName,
|
||||
Key = s3Key,
|
||||
InputStream = pipe.Reader.AsStream(),
|
||||
ContentType = contentType,
|
||||
};
|
||||
// Provide ContentLength when available so the AWS SDK doesn't buffer internally
|
||||
if (file.FileSize.HasValue)
|
||||
putRequest.Headers.ContentLength = file.FileSize.Value;
|
||||
|
||||
await Task.WhenAll(_s3.PutObjectAsync(putRequest, ct), downloadTask);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Cached Telegram fileId {FileId} → S3 key {Key} ({Bytes} bytes).",
|
||||
telegramFileId, s3Key, file.FileSize);
|
||||
}
|
||||
|
||||
private static string InferContentType(string filePath)
|
||||
{
|
||||
var ext = Path.GetExtension(filePath).ToLowerInvariant();
|
||||
return ext switch
|
||||
{
|
||||
".jpg" or ".jpeg" => "image/jpeg",
|
||||
".png" => "image/png",
|
||||
".gif" => "image/gif",
|
||||
".webp" => "image/webp",
|
||||
".mp4" => "video/mp4",
|
||||
".webm" => "video/webm",
|
||||
".tgs" => "application/x-tgsticker",
|
||||
".ogg" => "audio/ogg",
|
||||
_ => "application/octet-stream",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using MemeVault.Application.Common;
|
||||
using MemeVault.Domain.Aggregates.MediaItem;
|
||||
using MemeVault.Domain.Enums;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types.InlineQueryResults;
|
||||
|
||||
namespace MemeVault.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Вызывает Telegram Bot API answerWebAppQuery, чтобы отправить медиа в чат.
|
||||
/// Формирует нужный InlineQueryResult в зависимости от типа медиа.
|
||||
/// </summary>
|
||||
public sealed class TelegramQueryAnswererService : ITelegramQueryAnswerer
|
||||
{
|
||||
private readonly ITelegramBotClient _botClient;
|
||||
private readonly ILogger<TelegramQueryAnswererService> _logger;
|
||||
|
||||
public TelegramQueryAnswererService(
|
||||
ITelegramBotClient botClient,
|
||||
ILogger<TelegramQueryAnswererService> logger)
|
||||
{
|
||||
_botClient = botClient;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task AnswerAsync(string queryId, MediaItem item, CancellationToken ct = default)
|
||||
{
|
||||
var result = BuildResult(item);
|
||||
await _botClient.AnswerWebAppQuery(queryId, result, ct);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Sent item {ItemId} (type={Type}) to chat via queryId {QueryId}",
|
||||
item.Id, item.Type, queryId);
|
||||
}
|
||||
|
||||
// ── Строим нужный тип InlineQueryResult ──────────────────────────────────
|
||||
|
||||
private static InlineQueryResult BuildResult(MediaItem item)
|
||||
{
|
||||
var id = item.Id.ToString();
|
||||
var fileId = item.Source?.Reference;
|
||||
var caption = item.Caption;
|
||||
|
||||
return item.Type switch
|
||||
{
|
||||
MediaType.Photo => new InlineQueryResultCachedPhoto(id,
|
||||
fileId ?? throw new InvalidOperationException("Photo has no file_id"))
|
||||
{
|
||||
Caption = caption,
|
||||
},
|
||||
|
||||
MediaType.Video => new InlineQueryResultCachedVideo(id,
|
||||
fileId ?? throw new InvalidOperationException("Video has no file_id"),
|
||||
title: caption?[..Math.Min(60, caption.Length)] ?? "Video")
|
||||
{
|
||||
Caption = caption,
|
||||
},
|
||||
|
||||
MediaType.Sticker => new InlineQueryResultCachedSticker(id,
|
||||
fileId ?? throw new InvalidOperationException("Sticker has no file_id")),
|
||||
|
||||
MediaType.Animation => new InlineQueryResultCachedMpeg4Gif(id,
|
||||
fileId ?? throw new InvalidOperationException("Animation has no file_id"))
|
||||
{
|
||||
Caption = caption,
|
||||
},
|
||||
|
||||
MediaType.Text => new InlineQueryResultArticle(id,
|
||||
title: caption?[..Math.Min(60, caption?.Length ?? 0)] ?? "Текст",
|
||||
inputMessageContent: new InputTextMessageContent(caption ?? string.Empty))
|
||||
{
|
||||
Description = caption,
|
||||
},
|
||||
|
||||
_ => throw new NotSupportedException($"MediaType {item.Type} is not supported for chat sending."),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -81,12 +81,12 @@ public sealed class GetCollectionItemsQueryHandlerTests
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(2, result.Count);
|
||||
|
||||
var dto1 = result.Single(d => d.Type == MediaType.Photo);
|
||||
var dto1 = result.Single(d => d.MediaType == MediaType.Photo);
|
||||
Assert.Equal("file1", dto1.Reference);
|
||||
Assert.Equal("funny cat", dto1.Caption);
|
||||
Assert.Equal("cats", Assert.Single(dto1.Tags));
|
||||
|
||||
var dto2 = result.Single(d => d.Type == MediaType.Text);
|
||||
var dto2 = result.Single(d => d.MediaType == MediaType.Text);
|
||||
Assert.Null(dto2.Reference);
|
||||
Assert.Equal("hello world", dto2.Caption);
|
||||
Assert.Empty(dto2.Tags);
|
||||
|
||||
Reference in New Issue
Block a user