feat: invites

This commit is contained in:
2026-09-28 09:32:22 +04:00
parent 3055381788
commit 7e1e036bf1
24 changed files with 936 additions and 29 deletions
@@ -1,9 +1,12 @@
using MediatR;
using MemeVault.Api.Auth;
using MemeVault.Application.Commands.CreateCollection;
using MemeVault.Application.Commands.CreateCollectionInvite;
using MemeVault.Application.Commands.DeleteCollection;
using MemeVault.Application.Commands.RevokeCollectionInvite;
using MemeVault.Application.Commands.ShareCollection;
using MemeVault.Application.Commands.UpdateCollection;
using MemeVault.Application.Queries.GetCollectionInvites;
using MemeVault.Application.Queries.GetCollectionItems;
using MemeVault.Application.Queries.GetUserCollections;
using MemeVault.Domain.Enums;
@@ -72,6 +75,40 @@ public sealed class CollectionsController(IMediator mediator, CurrentUser curren
return result is null ? NotFound() : Ok(result);
}
// GET /api/collections/{id}/invites
[HttpGet("{id:guid}/invites")]
[ProducesResponseType(typeof(IReadOnlyList<CollectionInviteDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetInvites(Guid id, CancellationToken ct)
{
var result = await mediator.Send(
new GetCollectionInvitesQuery(id, currentUser.TelegramId), ct);
return result is null ? NotFound() : Ok(result);
}
// POST /api/collections/{id}/invites
[HttpPost("{id:guid}/invites")]
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> CreateInvite(
Guid id,
[FromBody] CreateInviteRequest request,
CancellationToken ct)
{
var token = await mediator.Send(
new CreateCollectionInviteCommand(id, currentUser.TelegramId, request.Role), ct);
return token is null ? NotFound() : Ok(new { token });
}
// DELETE /api/collections/{id}/invites/{inviteId}
[HttpDelete("{id:guid}/invites/{inviteId:guid}")]
public async Task<IActionResult> RevokeInvite(Guid id, Guid inviteId, CancellationToken ct)
{
var ok = await mediator.Send(
new RevokeCollectionInviteCommand(inviteId, currentUser.TelegramId), ct);
return ok ? NoContent() : NotFound();
}
// PUT /api/collections/{id}/visibility
[HttpPut("{id:guid}/visibility")]
public async Task<IActionResult> SetVisibility(
@@ -90,3 +127,4 @@ 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 SetVisibilityRequest(CollectionVisibility Visibility);
public sealed record CreateInviteRequest(CollectionRole Role);
@@ -0,0 +1,30 @@
using MediatR;
using MemeVault.Api.Auth;
using MemeVault.Application.Commands.AcceptCollectionInvite;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace MemeVault.Api.Controllers;
[ApiController]
[Authorize]
[Route("api/[controller]")]
public sealed class InvitesController(IMediator mediator, CurrentUser currentUser) : ControllerBase
{
/// <summary>
/// Принять инвайт. Вызывается API при обработке /start inv_TOKEN в боте.
/// </summary>
// POST /api/invites/{token}/accept
[HttpPost("{token}/accept")]
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Accept(string token, CancellationToken ct)
{
var collectionId = await mediator.Send(
new AcceptCollectionInviteCommand(token, currentUser.TelegramId), ct);
return collectionId is null
? NotFound()
: Ok(new { collectionId });
}
}
@@ -0,0 +1,11 @@
using MediatR;
namespace MemeVault.Application.Commands.AcceptCollectionInvite;
/// <param name="Token">Токен из deep link (t.me/Bot?start=inv_TOKEN).</param>
/// <param name="AcceptingTelegramId">Telegram ID принимающего приглашение.</param>
/// <returns>ID коллекции при успехе, null если инвайт не найден/отозван.</returns>
public sealed record AcceptCollectionInviteCommand(
string Token,
long AcceptingTelegramId
) : IRequest<Guid?>;
@@ -0,0 +1,52 @@
using MediatR;
using MemeVault.Application.Common;
using MemeVault.Domain.Enums;
using MemeVault.Domain.Exceptions;
using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Commands.AcceptCollectionInvite;
public sealed class AcceptCollectionInviteCommandHandler
: IRequestHandler<AcceptCollectionInviteCommand, Guid?>
{
private readonly ICollectionInviteRepository _invites;
private readonly ICollectionRepository _collections;
private readonly IUnitOfWork _uow;
public AcceptCollectionInviteCommandHandler(
ICollectionInviteRepository invites,
ICollectionRepository collections,
IUnitOfWork uow)
{
_invites = invites;
_collections = collections;
_uow = uow;
}
public async Task<Guid?> Handle(
AcceptCollectionInviteCommand request, CancellationToken cancellationToken)
{
var invite = await _invites.GetByTokenAsync(request.Token, cancellationToken);
if (invite is null || invite.IsRevoked)
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);
return collection.Id;
}
}
@@ -0,0 +1,14 @@
using MediatR;
using MemeVault.Domain.Enums;
namespace MemeVault.Application.Commands.CreateCollectionInvite;
/// <param name="CollectionId">Коллекция, для которой создаётся инвайт.</param>
/// <param name="RequestingTelegramId">Telegram ID запрашивающего (должен быть Owner).</param>
/// <param name="Role">Роль, которую получит принявший (Viewer или Manager).</param>
/// <returns>Токен инвайта, или null если коллекция не найдена / нет прав.</returns>
public sealed record CreateCollectionInviteCommand(
Guid CollectionId,
long RequestingTelegramId,
CollectionRole Role
) : IRequest<string?>;
@@ -0,0 +1,47 @@
using MediatR;
using MemeVault.Application.Common;
using MemeVault.Domain.Aggregates.CollectionInvite;
using MemeVault.Domain.Enums;
using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Commands.CreateCollectionInvite;
public sealed class CreateCollectionInviteCommandHandler
: IRequestHandler<CreateCollectionInviteCommand, string?>
{
private readonly ICollectionRepository _collections;
private readonly ICollectionInviteRepository _invites;
private readonly IUnitOfWork _uow;
public CreateCollectionInviteCommandHandler(
ICollectionRepository collections,
ICollectionInviteRepository invites,
IUnitOfWork uow)
{
_collections = collections;
_invites = invites;
_uow = uow;
}
public async Task<string?> Handle(
CreateCollectionInviteCommand request, CancellationToken cancellationToken)
{
var collection = await _collections.GetByIdAsync(request.CollectionId, cancellationToken);
if (collection is null)
return null;
// Только Owner может создавать инвайты
if (collection.GetRole(request.RequestingTelegramId) != CollectionRole.Owner)
return null;
var invite = CollectionInvite.Create(
collection.Id,
request.RequestingTelegramId,
request.Role);
await _invites.AddAsync(invite, cancellationToken);
await _uow.SaveChangesAsync(cancellationToken);
return invite.Token;
}
}
@@ -0,0 +1,9 @@
using MediatR;
namespace MemeVault.Application.Commands.RevokeCollectionInvite;
/// <returns>true если отозван, false если не найден или нет прав.</returns>
public sealed record RevokeCollectionInviteCommand(
Guid InviteId,
long RequestingTelegramId
) : IRequest<bool>;
@@ -0,0 +1,47 @@
using MediatR;
using MemeVault.Application.Common;
using MemeVault.Domain.Enums;
using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Commands.RevokeCollectionInvite;
public sealed class RevokeCollectionInviteCommandHandler
: IRequestHandler<RevokeCollectionInviteCommand, bool>
{
private readonly ICollectionInviteRepository _invites;
private readonly ICollectionRepository _collections;
private readonly IUnitOfWork _uow;
public RevokeCollectionInviteCommandHandler(
ICollectionInviteRepository invites,
ICollectionRepository collections,
IUnitOfWork uow)
{
_invites = invites;
_collections = collections;
_uow = uow;
}
public async Task<bool> Handle(
RevokeCollectionInviteCommand request, CancellationToken cancellationToken)
{
var invite = await _invites.GetByIdAsync(request.InviteId, cancellationToken);
if (invite is null)
return false;
var collection = await _collections.GetByIdAsync(invite.CollectionId, cancellationToken);
if (collection is null)
return false;
// Только Owner коллекции может отзывать инвайты
if (collection.GetRole(request.RequestingTelegramId) != CollectionRole.Owner)
return false;
invite.Revoke();
await _invites.UpdateAsync(invite, cancellationToken);
await _uow.SaveChangesAsync(cancellationToken);
return true;
}
}
@@ -0,0 +1,19 @@
using MediatR;
using MemeVault.Domain.Enums;
namespace MemeVault.Application.Queries.GetCollectionInvites;
/// <returns>Список инвайтов, или null если коллекция не найдена / нет прав.</returns>
public sealed record GetCollectionInvitesQuery(
Guid CollectionId,
long RequestingTelegramId
) : IRequest<IReadOnlyList<CollectionInviteDto>?>;
public sealed record CollectionInviteDto(
Guid Id,
string Token,
CollectionRole Role,
bool IsRevoked,
DateTimeOffset CreatedAt,
DateTimeOffset? RevokedAt
);
@@ -0,0 +1,39 @@
using MediatR;
using MemeVault.Domain.Enums;
using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Queries.GetCollectionInvites;
public sealed class GetCollectionInvitesQueryHandler
: IRequestHandler<GetCollectionInvitesQuery, IReadOnlyList<CollectionInviteDto>?>
{
private readonly ICollectionRepository _collections;
private readonly ICollectionInviteRepository _invites;
public GetCollectionInvitesQueryHandler(
ICollectionRepository collections,
ICollectionInviteRepository invites)
{
_collections = collections;
_invites = invites;
}
public async Task<IReadOnlyList<CollectionInviteDto>?> Handle(
GetCollectionInvitesQuery request, CancellationToken cancellationToken)
{
var collection = await _collections.GetByIdAsync(request.CollectionId, cancellationToken);
if (collection is null)
return null;
// Только Owner видит список инвайтов
if (collection.GetRole(request.RequestingTelegramId) != CollectionRole.Owner)
return null;
var invites = await _invites.GetByCollectionAsync(request.CollectionId, cancellationToken);
return invites
.Select(i => new CollectionInviteDto(
i.Id, i.Token, i.Role, i.IsRevoked, i.CreatedAt, i.RevokedAt))
.ToList();
}
}
@@ -1,4 +1,5 @@
using MediatR;
using MemeVault.Application.Commands.AcceptCollectionInvite;
using MemeVault.Application.Commands.EnsureUser;
using MemeVault.Application.Commands.SaveMedia;
using MemeVault.Domain.Enums;
@@ -25,6 +26,9 @@ public sealed class MessageHandler
// Сколько ждать, пока все части альбома придут от Telegram
private static readonly TimeSpan MediaGroupBuffer = TimeSpan.FromSeconds(2);
// Префикс токена в параметре /start
private const string InvitePrefix = "/start inv_";
public MessageHandler(
IMediator mediator,
ITelegramBotClient bot,
@@ -193,7 +197,17 @@ public sealed class MessageHandler
private async Task HandleCommandAsync(Message message, CancellationToken ct)
{
var reply = message.Text switch
var text = message.Text ?? "";
// /start inv_<TOKEN> — принять приглашение в коллекцию
if (text.StartsWith(InvitePrefix, StringComparison.OrdinalIgnoreCase))
{
var token = text[InvitePrefix.Length..].Trim();
await HandleInviteAsync(message, token, ct);
return;
}
var reply = text switch
{
"/start" => "👋 Привет! Отправь мне картинку, видео, стикер или текст — я сохраню.\n" +
"Теги прямо в подписи: #мем #кот\n" +
@@ -206,6 +220,21 @@ public sealed class MessageHandler
await _bot.SendMessage(message.Chat.Id, reply, cancellationToken: ct);
}
private async Task HandleInviteAsync(Message message, string token, CancellationToken ct)
{
_logger.LogInformation("User {UserId} accepting invite token {Token}",
message.From!.Id, token);
var collectionId = await _mediator.Send(
new AcceptCollectionInviteCommand(token, message.From!.Id), ct);
var reply = collectionId is not null
? "✅ Ты добавлен в коллекцию! Открой мини-апп, чтобы увидеть её."
: "❌ Ссылка недействительна или была отозвана.";
await _bot.SendMessage(message.Chat.Id, reply, cancellationToken: ct);
}
// ── Вспомогательные ───────────────────────────────────────────────────────
private static (MediaSource? source, MediaType type) ExtractMedia(Message message) =>
@@ -14,7 +14,11 @@ public sealed class Collection
private readonly List<IDomainEvent> _domainEvents = [];
public Guid Id { get; private set; }
public long OwnerTelegramId { get; private set; }
/// <summary>Вычисляется из CollectionMember с ролью Owner.</summary>
public long OwnerTelegramId =>
_members.FirstOrDefault(m => m.Role == CollectionRole.Owner)?.TelegramId ?? 0L;
public string Name { get; private set; } = string.Empty;
public string? Description { get; private set; }
public CollectionVisibility Visibility { get; private set; }
@@ -37,7 +41,6 @@ public sealed class Collection
private Collection(Guid id, long ownerTelegramId, string name, string? description, bool isInbox)
{
Id = id;
OwnerTelegramId = ownerTelegramId;
Name = name;
Description = description;
IsInbox = isInbox;
@@ -0,0 +1,61 @@
using MemeVault.Domain.Enums;
using MemeVault.Domain.Exceptions;
namespace MemeVault.Domain.Aggregates.CollectionInvite;
/// <summary>
/// Инвайт-ссылка для доступа к коллекции.
/// Активна до явного отзыва владельцем.
/// Token используется как часть Telegram deep link: t.me/Bot?start=inv_TOKEN
/// </summary>
public sealed class CollectionInvite
{
public Guid Id { get; private set; }
public Guid CollectionId { get; private set; }
public long CreatedByTelegramId { get; private set; }
/// <summary>Роль, которая будет назначена принявшему инвайт (Viewer или Manager).</summary>
public CollectionRole Role { get; private set; }
/// <summary>Уникальный токен для deep link.</summary>
public string Token { get; private set; } = string.Empty;
public DateTimeOffset CreatedAt { get; private set; }
public bool IsRevoked { get; private set; }
public DateTimeOffset? RevokedAt { get; private set; }
// EF Core constructor
private CollectionInvite() { }
private CollectionInvite(Guid collectionId, long createdBy, CollectionRole role)
{
Id = Guid.NewGuid();
CollectionId = collectionId;
CreatedByTelegramId = createdBy;
Role = role;
Token = GenerateToken();
CreatedAt = DateTimeOffset.UtcNow;
IsRevoked = false;
}
public static CollectionInvite Create(Guid collectionId, long createdBy, CollectionRole role)
{
if (role == CollectionRole.Owner)
throw new DomainException("Cannot create an invite with Owner role.");
return new CollectionInvite(collectionId, createdBy, role);
}
public void Revoke()
{
if (IsRevoked)
throw new DomainException("Invite is already revoked.");
IsRevoked = true;
RevokedAt = DateTimeOffset.UtcNow;
}
private static string GenerateToken() =>
Convert.ToBase64String(Guid.NewGuid().ToByteArray())
.Replace("/", "_").Replace("+", "-").TrimEnd('=');
}
@@ -0,0 +1,12 @@
using MemeVault.Domain.Aggregates.CollectionInvite;
namespace MemeVault.Domain.Repositories;
public interface ICollectionInviteRepository
{
Task<CollectionInvite?> GetByIdAsync(Guid id, CancellationToken ct = default);
Task<CollectionInvite?> GetByTokenAsync(string token, CancellationToken ct = default);
Task<IReadOnlyList<CollectionInvite>> GetByCollectionAsync(Guid collectionId, CancellationToken ct = default);
Task AddAsync(CollectionInvite invite, CancellationToken ct = default);
Task UpdateAsync(CollectionInvite invite, CancellationToken ct = default);
}
@@ -2,6 +2,7 @@ using MemeVault.Application.Common;
using MemeVault.Domain.Repositories;
using MemeVault.Infrastructure.Persistence;
using MemeVault.Infrastructure.Persistence.Repositories;
using MemeVault.Infrastructure.Persistence.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@@ -21,6 +22,7 @@ public static class InfrastructureServiceExtensions
services.AddScoped<IMediaItemRepository, MediaItemRepository>();
services.AddScoped<IBotUserRepository, BotUserRepository>();
services.AddScoped<ICollectionRepository, CollectionRepository>();
services.AddScoped<ICollectionInviteRepository, CollectionInviteRepository>();
var redisConn = config.GetConnectionString("Redis") ?? "localhost:6379";
services.AddStackExchangeRedisCache(opts => opts.Configuration = redisConn);
@@ -0,0 +1,296 @@
// <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("20260928051822_AddCollectionInvites")]
partial class AddCollectionInvites
{
/// <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<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,82 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace MemeVault.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AddCollectionInvites : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "ix_collections_inbox_unique",
table: "collections");
migrationBuilder.DropIndex(
name: "ix_collections_owner",
table: "collections");
migrationBuilder.DropColumn(
name: "owner_telegram_id",
table: "collections");
migrationBuilder.CreateTable(
name: "collection_invites",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false),
collection_id = table.Column<Guid>(type: "uuid", nullable: false),
created_by_telegram_id = table.Column<long>(type: "bigint", nullable: false),
role = table.Column<string>(type: "text", nullable: false),
token = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
is_revoked = table.Column<bool>(type: "boolean", nullable: false),
revoked_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_collection_invites", x => x.id);
});
migrationBuilder.CreateIndex(
name: "ix_collection_invites_collection_id",
table: "collection_invites",
column: "collection_id");
migrationBuilder.CreateIndex(
name: "ix_collection_invites_token",
table: "collection_invites",
column: "token",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "collection_invites");
migrationBuilder.AddColumn<long>(
name: "owner_telegram_id",
table: "collections",
type: "bigint",
nullable: false,
defaultValue: 0L);
migrationBuilder.CreateIndex(
name: "ix_collections_inbox_unique",
table: "collections",
columns: new[] { "owner_telegram_id", "is_inbox" },
unique: true,
filter: "is_inbox = true");
migrationBuilder.CreateIndex(
name: "ix_collections_owner",
table: "collections",
column: "owner_telegram_id");
}
}
}
@@ -87,10 +87,6 @@ namespace MemeVault.Infrastructure.Migrations
.HasColumnType("character varying(100)")
.HasColumnName("name");
b.Property<long>("OwnerTelegramId")
.HasColumnType("bigint")
.HasColumnName("owner_telegram_id");
b.Property<string>("ShareToken")
.HasMaxLength(64)
.HasColumnType("character varying(64)")
@@ -107,22 +103,64 @@ namespace MemeVault.Infrastructure.Migrations
b.HasKey("Id");
b.HasIndex("OwnerTelegramId")
.HasDatabaseName("ix_collections_owner");
b.HasIndex("ShareToken")
.IsUnique()
.HasDatabaseName("ix_collections_share_token")
.HasFilter("share_token IS NOT NULL");
b.HasIndex("OwnerTelegramId", "IsInbox")
.IsUnique()
.HasDatabaseName("ix_collections_inbox_unique")
.HasFilter("is_inbox = true");
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")
@@ -1,6 +1,7 @@
using MemeVault.Application.Common;
using MemeVault.Domain.Aggregates.BotUser;
using MemeVault.Domain.Aggregates.Collection;
using MemeVault.Domain.Aggregates.CollectionInvite;
using MemeVault.Domain.Aggregates.MediaItem;
using MemeVault.Infrastructure.Persistence.Configurations;
using Microsoft.EntityFrameworkCore;
@@ -14,11 +15,13 @@ public sealed class AppDbContext : DbContext, IUnitOfWork
public DbSet<MediaItem> MediaItems => Set<MediaItem>();
public DbSet<BotUser> BotUsers => Set<BotUser>();
public DbSet<Collection> Collections => Set<Collection>();
public DbSet<CollectionInvite> CollectionInvites => Set<CollectionInvite>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new MediaItemConfiguration());
modelBuilder.ApplyConfiguration(new BotUserConfiguration());
modelBuilder.ApplyConfiguration(new CollectionConfiguration());
modelBuilder.ApplyConfiguration(new CollectionInviteConfiguration());
}
}
@@ -13,9 +13,8 @@ public sealed class CollectionConfiguration : IEntityTypeConfiguration<Collectio
builder.HasKey(x => x.Id);
builder.Property(x => x.Id).HasColumnName("id");
builder.Property(x => x.OwnerTelegramId)
.HasColumnName("owner_telegram_id")
.IsRequired();
// OwnerTelegramId вычисляется из Members, не хранится как отдельная колонка
builder.Ignore(x => x.OwnerTelegramId);
builder.Property(x => x.Name)
.HasColumnName("name")
@@ -44,15 +43,6 @@ public sealed class CollectionConfiguration : IEntityTypeConfiguration<Collectio
.HasFilter("share_token IS NOT NULL")
.HasDatabaseName("ix_collections_share_token");
builder.HasIndex(x => x.OwnerTelegramId)
.HasDatabaseName("ix_collections_owner");
// Уникальность Inbox на пользователя
builder.HasIndex(x => new { x.OwnerTelegramId, x.IsInbox })
.HasFilter("is_inbox = true")
.IsUnique()
.HasDatabaseName("ix_collections_inbox_unique");
// Участники — owned entity
builder.OwnsMany(x => x.Members, m =>
{
@@ -0,0 +1,45 @@
using MemeVault.Domain.Aggregates.CollectionInvite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace MemeVault.Infrastructure.Persistence.Configurations;
public sealed class CollectionInviteConfiguration : IEntityTypeConfiguration<CollectionInvite>
{
public void Configure(EntityTypeBuilder<CollectionInvite> builder)
{
builder.ToTable("collection_invites");
builder.HasKey(x => x.Id);
builder.Property(x => x.Id).HasColumnName("id");
builder.Property(x => x.CollectionId)
.HasColumnName("collection_id")
.IsRequired();
builder.Property(x => x.CreatedByTelegramId)
.HasColumnName("created_by_telegram_id")
.IsRequired();
builder.Property(x => x.Role)
.HasColumnName("role")
.HasConversion<string>()
.IsRequired();
builder.Property(x => x.Token)
.HasColumnName("token")
.HasMaxLength(32)
.IsRequired();
builder.HasIndex(x => x.Token)
.IsUnique()
.HasDatabaseName("ix_collection_invites_token");
builder.HasIndex(x => x.CollectionId)
.HasDatabaseName("ix_collection_invites_collection_id");
builder.Property(x => x.CreatedAt).HasColumnName("created_at");
builder.Property(x => x.IsRevoked).HasColumnName("is_revoked");
builder.Property(x => x.RevokedAt).HasColumnName("revoked_at");
}
}
@@ -0,0 +1,33 @@
using MemeVault.Domain.Aggregates.CollectionInvite;
using MemeVault.Domain.Repositories;
using Microsoft.EntityFrameworkCore;
namespace MemeVault.Infrastructure.Persistence.Repositories;
public sealed class CollectionInviteRepository : ICollectionInviteRepository
{
private readonly AppDbContext _db;
public CollectionInviteRepository(AppDbContext db) => _db = db;
public Task<CollectionInvite?> GetByIdAsync(Guid id, CancellationToken ct) =>
_db.CollectionInvites.FirstOrDefaultAsync(x => x.Id == id, ct);
public Task<CollectionInvite?> GetByTokenAsync(string token, CancellationToken ct) =>
_db.CollectionInvites.FirstOrDefaultAsync(x => x.Token == token, ct);
public async Task<IReadOnlyList<CollectionInvite>> GetByCollectionAsync(Guid collectionId, CancellationToken ct) =>
await _db.CollectionInvites
.Where(x => x.CollectionId == collectionId)
.OrderByDescending(x => x.CreatedAt)
.ToListAsync(ct);
public async Task AddAsync(CollectionInvite invite, CancellationToken ct) =>
await _db.CollectionInvites.AddAsync(invite, ct);
public Task UpdateAsync(CollectionInvite invite, CancellationToken ct)
{
_db.CollectionInvites.Update(invite);
return Task.CompletedTask;
}
}
@@ -1,4 +1,5 @@
using MemeVault.Domain.Aggregates.Collection;
using MemeVault.Domain.Enums;
using MemeVault.Domain.Repositories;
using Microsoft.EntityFrameworkCore;
@@ -24,7 +25,8 @@ public sealed class CollectionRepository : ICollectionRepository
{
return await _db.Collections
.Include(c => c.Members)
.Where(x => x.OwnerTelegramId == ownerTelegramId)
.Where(c => c.Members.Any(m =>
m.TelegramId == ownerTelegramId && m.Role == CollectionRole.Owner))
.OrderBy(x => x.IsInbox ? 0 : 1) // Inbox всегда первым
.ThenBy(x => x.Name)
.ToListAsync(ct);
@@ -32,7 +34,11 @@ public sealed class CollectionRepository : ICollectionRepository
public Task<Collection?> GetInboxAsync(long ownerTelegramId, CancellationToken ct) =>
_db.Collections
.FirstOrDefaultAsync(x => x.OwnerTelegramId == ownerTelegramId && x.IsInbox, ct);
.Include(c => c.Members)
.FirstOrDefaultAsync(c =>
c.IsInbox &&
c.Members.Any(m => m.TelegramId == ownerTelegramId && m.Role == CollectionRole.Owner),
ct);
public async Task AddAsync(Collection collection, CancellationToken ct) =>
await _db.Collections.AddAsync(collection, ct);