Files
TelegramMemeVault/src/MemeVault.Domain/Aggregates/Collection/Collection.cs
T
2026-09-28 09:32:22 +04:00

159 lines
6.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using MemeVault.Domain.Enums;
using MemeVault.Domain.Events;
using MemeVault.Domain.Exceptions;
namespace MemeVault.Domain.Aggregates.Collection;
/// <summary>
/// Aggregate Root: коллекция медиа-элементов с ACL-моделью доступа.
/// Каждый пользователь имеет ровно одну системную коллекцию Inbox (IsInbox = true).
/// </summary>
public sealed class Collection
{
private readonly List<CollectionMember> _members = [];
private readonly List<IDomainEvent> _domainEvents = [];
public Guid Id { 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; }
/// <summary>Системная коллекция входящих. Нельзя удалить или переименовать.</summary>
public bool IsInbox { get; private set; }
/// <summary>Токен для доступа по ссылке (для Visibility = LinkOnly и Public).</summary>
public string? ShareToken { get; private set; }
public IReadOnlyList<CollectionMember> Members => _members.AsReadOnly();
public DateTimeOffset CreatedAt { get; private set; }
public DateTimeOffset? UpdatedAt { get; private set; }
public IReadOnlyList<IDomainEvent> DomainEvents => _domainEvents.AsReadOnly();
// EF Core constructor
private Collection() { }
private Collection(Guid id, long ownerTelegramId, string name, string? description, bool isInbox)
{
Id = id;
Name = name;
Description = description;
IsInbox = isInbox;
Visibility = CollectionVisibility.Private;
CreatedAt = DateTimeOffset.UtcNow;
// Владелец автоматически становится членом с ролью Owner
_members.Add(new CollectionMember(id, ownerTelegramId, CollectionRole.Owner));
}
public static Collection Create(long ownerTelegramId, string name, string? description = null)
{
if (string.IsNullOrWhiteSpace(name))
throw new DomainException("Collection name cannot be empty.");
if (name.Length > 100)
throw new DomainException("Collection name must be 100 characters or less.");
return new Collection(Guid.NewGuid(), ownerTelegramId, name, description, isInbox: false);
}
/// <summary>Создаёт системную коллекцию входящих для нового пользователя.</summary>
public static Collection CreateInbox(long ownerTelegramId) =>
new(Guid.NewGuid(), ownerTelegramId, "Inbox", description: null, isInbox: true);
// ── Управление участниками ─────────────────────────────────────────────────
public void AddMember(long telegramId, CollectionRole role, long requestingTelegramId)
{
EnsureRole(requestingTelegramId, CollectionRole.Owner);
if (role == CollectionRole.Owner)
throw new DomainException("Cannot assign Owner role. Transfer ownership instead.");
var existing = _members.FirstOrDefault(m => m.TelegramId == telegramId);
if (existing is not null)
{
existing.ChangeRole(role);
}
else
{
_members.Add(new CollectionMember(Id, telegramId, role));
}
UpdatedAt = DateTimeOffset.UtcNow;
}
public void RemoveMember(long telegramId, long requestingTelegramId)
{
EnsureRole(requestingTelegramId, CollectionRole.Owner);
if (telegramId == OwnerTelegramId)
throw new DomainException("Cannot remove the owner from the collection.");
var member = _members.FirstOrDefault(m => m.TelegramId == telegramId)
?? throw new DomainException("Member not found.");
_members.Remove(member);
UpdatedAt = DateTimeOffset.UtcNow;
}
// ── Видимость и шаринг ────────────────────────────────────────────────────
public void SetVisibility(CollectionVisibility visibility, long requestingTelegramId)
{
EnsureRole(requestingTelegramId, CollectionRole.Owner);
Visibility = visibility;
if (visibility is CollectionVisibility.LinkOnly or CollectionVisibility.Public)
{
ShareToken ??= GenerateToken();
}
UpdatedAt = DateTimeOffset.UtcNow;
}
public void Rename(string newName, long requestingTelegramId)
{
if (IsInbox)
throw new DomainException("Cannot rename the Inbox collection.");
EnsureRole(requestingTelegramId, CollectionRole.Manager);
if (string.IsNullOrWhiteSpace(newName))
throw new DomainException("Collection name cannot be empty.");
Name = newName.Trim();
UpdatedAt = DateTimeOffset.UtcNow;
}
// ── Доступ ────────────────────────────────────────────────────────────────
public bool CanView(long telegramId)
{
if (Visibility == CollectionVisibility.Public) return true;
return _members.Any(m => m.TelegramId == telegramId);
}
public CollectionRole? GetRole(long telegramId) =>
_members.FirstOrDefault(m => m.TelegramId == telegramId)?.Role;
private void EnsureRole(long telegramId, CollectionRole minimumRole)
{
var role = GetRole(telegramId);
if (role is null || role < minimumRole)
throw new DomainException($"Action requires at least {minimumRole} role.");
}
private static string GenerateToken() =>
Convert.ToBase64String(Guid.NewGuid().ToByteArray())
.Replace("/", "_").Replace("+", "-").TrimEnd('=');
public void ClearDomainEvents() => _domainEvents.Clear();
}