Compare commits
54
Commits
9df7d7aaf1
...
bugfix_web
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4f61071ed | ||
|
|
e8c9a55fe9 | ||
|
|
bccbf12a11 | ||
|
|
c8b0384392 | ||
|
|
5245e8b7ae | ||
|
|
b346372555 | ||
|
|
d2e6eb578a | ||
|
|
ae710c3d43 | ||
|
|
600e43eec5 | ||
|
|
7b251686b2 | ||
|
|
00682b2977 | ||
|
|
e05572fc3f | ||
|
|
c264b7df27 | ||
|
|
56f75ae32b | ||
|
|
ca9cf27716 | ||
|
|
7225e3272e | ||
|
|
86ae06beb6 | ||
|
|
454f70f716 | ||
|
|
e700609d30 | ||
|
|
88f39aa51f | ||
|
|
c3dbbaa7b8 | ||
|
|
2eb4f48ca0 | ||
|
|
0c1adaab6c | ||
|
|
a52726d0e6 | ||
|
|
d812a7a40c | ||
|
|
c8b4fed25a | ||
|
|
8399d32490 | ||
|
|
3905094ff4 | ||
|
|
9e8625aea1 | ||
|
|
5b905c94da | ||
|
|
0eecc01374 | ||
|
|
c37e1723d4 | ||
|
|
02043d4d97 | ||
|
|
852efa090e | ||
|
|
c45f4db61c | ||
|
|
02a85fc587 | ||
|
|
e09860700c | ||
|
|
32c9bc43cf | ||
|
|
d96e4ec7d4 | ||
|
|
1558b20470 | ||
|
|
fa185afc73 | ||
|
|
90096ce2bc | ||
|
|
65d5f5fee9 | ||
|
|
e11240f78f | ||
|
|
53f193970c | ||
|
|
f41ad0bcf8 | ||
|
|
b49ff47762 | ||
|
|
182bbe2ad8 | ||
|
|
a04f04a448 | ||
|
|
2ab5b295e8 | ||
|
|
1b8abbc995 | ||
|
|
943699139b | ||
|
|
757142eda7 | ||
|
|
a42007df2d |
@@ -1,13 +1,13 @@
|
|||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using Knot.Modules.Profiles.Application.Profiles.UpdateProfile;
|
using Knot.Modules.Profiles.Application.Profiles.UpdateProfile;
|
||||||
using Knot.Modules.Profiles.Domain;
|
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using NSubstitute;
|
using NSubstitute;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
using System;
|
using System;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Modules.Profiles.Application.Abstractions;
|
using Knot.Contracts.Profiles.Domain;
|
||||||
|
using Knot.Contracts.Profiles.Application.DTOs;
|
||||||
|
|
||||||
namespace Knot.Modules.Profiles.UnitTests;
|
namespace Knot.Modules.Profiles.UnitTests;
|
||||||
|
|
||||||
@@ -25,14 +25,11 @@ public class UpdateProfileCommandHandlerTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public async Task Handle_ShouldReturnError_WhenProfileNotFound()
|
public async Task Handle_ShouldReturnError_WhenProfileNotFound()
|
||||||
{
|
{
|
||||||
// Arrange
|
var command = new UpdateProfileCommand(Guid.NewGuid(), "FirstName", "Bio", null, null);
|
||||||
var command = new UpdateProfileCommand(Guid.NewGuid(), "FirstName", "Bio", null);
|
_profileRepository.GetAsync(command.UserId, Arg.Any<CancellationToken>()).Returns((UserProfileDto?)null);
|
||||||
_profileRepository.GetByIdAsync(command.UserId, Arg.Any<CancellationToken>()).Returns((ProfileDocument?)null);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = await _handler.Handle(command, CancellationToken.None);
|
var result = await _handler.Handle(command, CancellationToken.None);
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.IsFailure.Should().BeTrue();
|
result.IsFailure.Should().BeTrue();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,4 +8,7 @@ public static class AuthErrors
|
|||||||
public static Error IdentityRegistrationDisabled => new("Auth.RegistrationDisabled", "Registration is disabled");
|
public static Error IdentityRegistrationDisabled => new("Auth.RegistrationDisabled", "Registration is disabled");
|
||||||
public static Error IdentityUsernameNotUnique => new("Auth.UsernameNotUnique", "Username is already taken");
|
public static Error IdentityUsernameNotUnique => new("Auth.UsernameNotUnique", "Username is already taken");
|
||||||
public static Error UserNotFound => new("Auth.UserNotFound", "User not found");
|
public static Error UserNotFound => new("Auth.UserNotFound", "User not found");
|
||||||
|
public static Error PasswordConfirmationMismatch => new("Auth.PasswordConfirmationMismatch", "Passwords do not match");
|
||||||
|
public static Error PasswordTooShort => new("Auth.PasswordTooShort", "Password must be at least 8 characters");
|
||||||
|
public static Error OldPasswordInvalid => new("Auth.OldPasswordInvalid", "Current password is incorrect");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
namespace Knot.Contracts.Auth.Application.Auth.DTOs;
|
namespace Knot.Contracts.Auth.Application.Auth.DTOs;
|
||||||
|
|
||||||
public class AuthResponseDto
|
public class AuthResponseDto
|
||||||
{
|
{
|
||||||
@@ -7,6 +7,7 @@ public class AuthResponseDto
|
|||||||
public Guid UserId { get; set; }
|
public Guid UserId { get; set; }
|
||||||
public string Username { get; set; } = string.Empty;
|
public string Username { get; set; } = string.Empty;
|
||||||
public string? DisplayName { get; set; }
|
public string? DisplayName { get; set; }
|
||||||
|
public string? Avatar { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public class ResetPasswordDto
|
public class ResetPasswordDto
|
||||||
|
|||||||
@@ -36,17 +36,21 @@ public sealed class Chat : AggregateRoot<Guid>
|
|||||||
public string? Avatar { get; private set; }
|
public string? Avatar { get; private set; }
|
||||||
public DateTime CreatedAt { get; private set; }
|
public DateTime CreatedAt { get; private set; }
|
||||||
public long LastMessageSequenceId { get; private set; }
|
public long LastMessageSequenceId { get; private set; }
|
||||||
|
public bool IsImporting { get; private set; }
|
||||||
|
public Guid? ImportJobId { get; private set; }
|
||||||
|
|
||||||
private readonly List<ChatMember> _members = new();
|
private readonly List<ChatMember> _members = new();
|
||||||
public IReadOnlyCollection<ChatMember> Members => _members.AsReadOnly();
|
public IReadOnlyCollection<ChatMember> Members => _members.AsReadOnly();
|
||||||
|
|
||||||
private Chat(Guid id, ChatType type, string? name, string? avatar, string? description = null) : base(id)
|
private Chat(Guid id, ChatType type, string? name, string? avatar, string? description = null, bool isImporting = false, Guid? importJobId = null) : base(id)
|
||||||
{
|
{
|
||||||
Type = type;
|
Type = type;
|
||||||
Name = name;
|
Name = name;
|
||||||
Avatar = avatar;
|
Avatar = avatar;
|
||||||
Description = description;
|
Description = description;
|
||||||
CreatedAt = DateTime.UtcNow;
|
CreatedAt = DateTime.UtcNow;
|
||||||
|
IsImporting = isImporting;
|
||||||
|
ImportJobId = importJobId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Chat CreatePersonal()
|
public static Chat CreatePersonal()
|
||||||
@@ -63,13 +67,18 @@ public sealed class Chat : AggregateRoot<Guid>
|
|||||||
return chat;
|
return chat;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Chat Create(string? name, ChatType type, string? avatar = null, string? description = null)
|
public static Chat Create(string? name, ChatType type, string? avatar = null, string? description = null, bool isImporting = false, Guid? importJobId = null)
|
||||||
{
|
{
|
||||||
var chat = new Chat(Guid.NewGuid(), type, name, avatar, description);
|
var chat = new Chat(Guid.NewGuid(), type, name, avatar, description, isImporting, importJobId);
|
||||||
chat.RaiseDomainEvent(new ChatCreatedDomainEvent(chat));
|
chat.RaiseDomainEvent(new ChatCreatedDomainEvent(chat));
|
||||||
return chat;
|
return chat;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void CompleteImport()
|
||||||
|
{
|
||||||
|
IsImporting = false;
|
||||||
|
}
|
||||||
|
|
||||||
public void AddMember(Guid userId, string role = "member")
|
public void AddMember(Guid userId, string role = "member")
|
||||||
{
|
{
|
||||||
if (_members.Any(m => m.UserId == userId))
|
if (_members.Any(m => m.UserId == userId))
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace Knot.Contracts.Conversations.Domain;
|
||||||
|
|
||||||
|
public static class ChatConstants
|
||||||
|
{
|
||||||
|
public const int DefaultMessageQueryLimit = 50;
|
||||||
|
public const int MaxSharedMediaQueryLimit = 1000;
|
||||||
|
public const int MaxGroupNameLength = 100;
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
using Knot.Shared.Kernel;
|
||||||
|
|
||||||
|
namespace Knot.Contracts.Conversations.Domain;
|
||||||
|
|
||||||
|
public static class ChatErrors
|
||||||
|
{
|
||||||
|
public static readonly Error ChatNotFound = new Error("Chat.NotFound", "Чат не найден");
|
||||||
|
public static readonly Error OnlyOwnerCanUpdate = new Error("Chat.OnlyOwnerCanUpdate", "Только владелец может редактировать чат");
|
||||||
|
public static readonly Error Unauthorized = new Error("Chat.Unauthorized", "Нет доступа к этому чату");
|
||||||
|
public static readonly Error FoldersDisabled = new Error("Chat.FoldersDisabled", "Папки отключены");
|
||||||
|
public static readonly Error FileEmpty = new Error("Chat.FileEmpty", "Файл пуст");
|
||||||
|
public static Error FileTooLarge(long maxMb) => new Error("Chat.FileTooLarge", $"Файл слишком большой (максимум {maxMb} МБ)");
|
||||||
|
public static readonly Error ChatsNotFound = new Error("Chat.NotFound", "Чат не найден");
|
||||||
|
public static readonly Error ChatsForbidden = new Error("Chat.Forbidden", "Доступ запрещен");
|
||||||
|
public static readonly Error MediaDisabled = new Error("Chat.MediaDisabled", "Медиафайлы отключены");
|
||||||
|
public static readonly Error PollsDisabled = new Error("Chat.PollsDisabled", "Опросы отключены");
|
||||||
|
public static readonly Error NotFound = new Error("Chat.NotFound", "Не найдено");
|
||||||
|
public static readonly Error NotMember = new Error("Chat.NotMember", "Вы не являетесь участником чата");
|
||||||
|
}
|
||||||
@@ -3,4 +3,5 @@ namespace Knot.Contracts.Messaging.Application.Abstractions;
|
|||||||
public interface IMessageNotifier
|
public interface IMessageNotifier
|
||||||
{
|
{
|
||||||
Task NotifyNewMessageAsync(Guid chatId, object messagePayload, CancellationToken cancellationToken);
|
Task NotifyNewMessageAsync(Guid chatId, object messagePayload, CancellationToken cancellationToken);
|
||||||
|
Task NotifyMessageUpdateAsync(Guid chatId, string updateType, object updatePayload, CancellationToken cancellationToken);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,9 +8,11 @@ public interface IMessageRepository
|
|||||||
Task<Message?> GetByIdAsync(Guid id, CancellationToken cancellationToken);
|
Task<Message?> GetByIdAsync(Guid id, CancellationToken cancellationToken);
|
||||||
Task<List<Message>> GetChatMessagesAsync(Guid chatId, int limit, int offset, CancellationToken cancellationToken);
|
Task<List<Message>> GetChatMessagesAsync(Guid chatId, int limit, int offset, CancellationToken cancellationToken);
|
||||||
Task<Message?> GetLatestChatMessageAsync(Guid chatId, CancellationToken cancellationToken);
|
Task<Message?> GetLatestChatMessageAsync(Guid chatId, CancellationToken cancellationToken);
|
||||||
|
Task<List<Message>> GetPinnedMessagesAsync(Guid chatId, CancellationToken cancellationToken);
|
||||||
Task<List<Message>> SearchMessagesAsync(string query, Guid? chatId, Guid requestingUserId, CancellationToken cancellationToken);
|
Task<List<Message>> SearchMessagesAsync(string query, Guid? chatId, Guid requestingUserId, CancellationToken cancellationToken);
|
||||||
|
|
||||||
Task<List<Message>> GetChatMessagesCursorAsync(Guid chatId, DateTime? cursor, int limit, CancellationToken cancellationToken);
|
Task<List<Message>> GetChatMessagesCursorAsync(Guid chatId, DateTime? cursor, long? sequenceId, int limit, CancellationToken cancellationToken);
|
||||||
|
Task<List<Message>> GetChatMessagesAroundAsync(Guid chatId, long sequenceId, int limit, CancellationToken cancellationToken);
|
||||||
Task<Message?> GetLastStoryMessageAsync(Guid chatId, Guid storyId, CancellationToken cancellationToken);
|
Task<Message?> GetLastStoryMessageAsync(Guid chatId, Guid storyId, CancellationToken cancellationToken);
|
||||||
|
|
||||||
Task UpdateAsync(Message message, CancellationToken cancellationToken);
|
Task UpdateAsync(Message message, CancellationToken cancellationToken);
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace Knot.Contracts.Messaging.Domain;
|
||||||
|
|
||||||
|
public class CallMessage : Message
|
||||||
|
{
|
||||||
|
public override string Type => "call";
|
||||||
|
public override string? Content { get; protected set; }
|
||||||
|
public string CallType { get; protected set; }
|
||||||
|
public string CallStatus { get; protected set; }
|
||||||
|
public int? Duration { get; protected set; }
|
||||||
|
|
||||||
|
public CallMessage() : base() { }
|
||||||
|
|
||||||
|
public CallMessage(
|
||||||
|
Guid id,
|
||||||
|
Guid chatId,
|
||||||
|
Guid senderId,
|
||||||
|
string callType,
|
||||||
|
string callStatus,
|
||||||
|
int? duration,
|
||||||
|
Guid? replyToId,
|
||||||
|
Guid? forwardedFromId,
|
||||||
|
DateTime createdAt,
|
||||||
|
bool isImported = false)
|
||||||
|
: base(id, chatId, senderId, replyToId, forwardedFromId, createdAt, isImported)
|
||||||
|
{
|
||||||
|
CallType = callType;
|
||||||
|
CallStatus = callStatus;
|
||||||
|
Duration = duration;
|
||||||
|
Content = $"Call {callStatus}";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace Knot.Contracts.Messaging.Domain;
|
||||||
|
|
||||||
|
public class Media
|
||||||
|
{
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
public string Type { get; set; } = string.Empty;
|
||||||
|
public string? Url { get; set; }
|
||||||
|
public string? ThumbnailUrl { get; set; }
|
||||||
|
public long? Size { get; set; }
|
||||||
|
public int Width { get; set; }
|
||||||
|
public int Height { get; set; }
|
||||||
|
public string? FileId { get; set; }
|
||||||
|
public string? Filename { get; set; }
|
||||||
|
public string? Duration { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace Knot.Contracts.Messaging.Domain;
|
||||||
|
|
||||||
|
public class MediaMessage : Message
|
||||||
|
{
|
||||||
|
public override string Type => MediaType.ToString().ToLower();
|
||||||
|
public override string? Content { get; protected set; }
|
||||||
|
public string? Caption { get => Content; private set => Content = value; }
|
||||||
|
public MediaType MediaType { get; private set; }
|
||||||
|
|
||||||
|
private List<Media> _media = new();
|
||||||
|
public IReadOnlyCollection<Media> Media => _media.AsReadOnly();
|
||||||
|
|
||||||
|
private MediaMessage() : base() { MediaType = MediaType.File; }
|
||||||
|
|
||||||
|
public MediaMessage(Guid id, Guid chatId, Guid senderId, MediaType mediaType, string? caption, Guid? replyToId, Guid? forwardedFromId, DateTime createdAt, bool isImported)
|
||||||
|
: base(id, chatId, senderId, replyToId, forwardedFromId, createdAt, isImported) { MediaType = mediaType; Caption = caption; }
|
||||||
|
|
||||||
|
public MediaMessage(Guid id, Guid chatId, Guid senderId, string mediaType, string? caption, Guid? replyToId, Guid? forwardedFromId, DateTime createdAt, bool isImported)
|
||||||
|
: this(id, chatId, senderId, Enum.TryParse<MediaType>(mediaType, true, out var mt) ? mt : MediaType.File, caption, replyToId, forwardedFromId, createdAt, isImported) { }
|
||||||
|
|
||||||
|
public void AddMedia(string type, string url, string? filename, long? size, string? duration = null) => _media.Add(new Media { Type = type, Url = url, Filename = filename, FileId = filename, Size = size, Duration = duration });
|
||||||
|
|
||||||
|
public override void Edit(string newCaption) => base.Edit(newCaption);
|
||||||
|
|
||||||
|
public override void Delete() { Caption = null; base.Delete(); }
|
||||||
|
}
|
||||||
@@ -16,18 +16,17 @@ public abstract class Message : AggregateRoot<Guid>
|
|||||||
public MessageState State { get; protected set; }
|
public MessageState State { get; protected set; }
|
||||||
public abstract string Type { get; }
|
public abstract string Type { get; }
|
||||||
public abstract string? Content { get; protected set; }
|
public abstract string? Content { get; protected set; }
|
||||||
public virtual string? Quote { get; protected set; } = null;
|
|
||||||
public virtual Guid? StoryId => null;
|
|
||||||
public virtual string? StoryMediaUrl => null;
|
|
||||||
public virtual string? StoryMediaType => null;
|
|
||||||
public virtual IReadOnlyCollection<Media> Media => Array.Empty<Media>();
|
|
||||||
public bool IsEdited => HasState(MessageState.IsEdited);
|
public bool IsEdited => HasState(MessageState.IsEdited);
|
||||||
public bool IsDeleted => HasState(MessageState.IsDeleted);
|
public bool IsDeleted => HasState(MessageState.IsDeleted);
|
||||||
public bool IsDeletedForUser(Guid userId) => _deletedFor.Exists(d => d.UserId == userId);
|
|
||||||
protected List<DeletedMessage> _deletedFor = new();
|
protected List<DeletedMessage> _deletedFor = new();
|
||||||
public IReadOnlyCollection<DeletedMessage> DeletedFor => _deletedFor.AsReadOnly();
|
public IReadOnlyCollection<DeletedMessage> DeletedFor => _deletedFor.AsReadOnly();
|
||||||
|
|
||||||
protected Message() : base(Guid.Empty) { }
|
protected Message() : base(Guid.Empty) { }
|
||||||
protected Message(Guid id, Guid chatId, Guid senderId, Guid? replyToId, Guid? forwardedFromId, DateTime createdAt, bool isImported) : base(id)
|
|
||||||
|
protected Message(Guid id, Guid chatId, Guid senderId, Guid? replyToId, Guid? forwardedFromId, DateTime createdAt, bool isImported)
|
||||||
|
: base(id)
|
||||||
{
|
{
|
||||||
ChatId = chatId;
|
ChatId = chatId;
|
||||||
SenderId = senderId;
|
SenderId = senderId;
|
||||||
@@ -36,91 +35,22 @@ public abstract class Message : AggregateRoot<Guid>
|
|||||||
CreatedAt = createdAt;
|
CreatedAt = createdAt;
|
||||||
if (isImported) AddState(MessageState.IsImported);
|
if (isImported) AddState(MessageState.IsImported);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void AddState(MessageState state) => State |= state;
|
public void AddState(MessageState state) => State |= state;
|
||||||
public void RemoveState(MessageState state) => State &= ~state;
|
public void RemoveState(MessageState state) => State &= ~state;
|
||||||
public bool HasState(MessageState state) => (State & state) == state;
|
public bool HasState(MessageState state) => (State & state) == state;
|
||||||
|
public bool IsDeletedForUser(Guid userId) => _deletedFor.Exists(d => d.UserId == userId);
|
||||||
|
|
||||||
public virtual void Delete() => AddState(MessageState.IsDeleted);
|
public virtual void Delete() => AddState(MessageState.IsDeleted);
|
||||||
public virtual void Edit(string newContent) { Content = newContent; AddState(MessageState.IsEdited); }
|
public virtual void Edit(string newContent)
|
||||||
public void DeleteForUser(Guid userId) { if (!_deletedFor.Exists(x => x.UserId == userId)) _deletedFor.Add(new DeletedMessage(Id, userId)); }
|
{
|
||||||
|
Content = newContent;
|
||||||
|
AddState(MessageState.IsEdited);
|
||||||
}
|
}
|
||||||
|
|
||||||
public class Media
|
public void DeleteForUser(Guid userId)
|
||||||
{
|
{
|
||||||
public Guid Id { get; set; }
|
if (!_deletedFor.Exists(x => x.UserId == userId))
|
||||||
public string Type { get; set; } = string.Empty;
|
_deletedFor.Add(new DeletedMessage(Id, userId));
|
||||||
public string? Url { get; set; }
|
|
||||||
public string? ThumbnailUrl { get; set; }
|
|
||||||
public long? Size { get; set; }
|
|
||||||
public int Width { get; set; }
|
|
||||||
public int Height { get; set; }
|
|
||||||
public string? FileId { get; set; }
|
|
||||||
public string? Filename { get; set; }
|
|
||||||
public string? Duration { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class TextMessage : Message
|
|
||||||
{
|
|
||||||
public override string Type => "text";
|
|
||||||
public override string? Content { get; protected set; }
|
|
||||||
public TextMessage() : base() { }
|
|
||||||
public TextMessage(Guid id, Guid chatId, Guid senderId, string content, Guid? replyToId, Guid? forwardedFromId, DateTime createdAt, bool isImported = false)
|
|
||||||
: base(id, chatId, senderId, replyToId, forwardedFromId, createdAt, isImported) => Content = content;
|
|
||||||
public TextMessage(Guid id, Guid chatId, Guid senderId, string content, Guid? replyToId, string? quote, Guid? forwardedFromId, DateTime createdAt, bool isImported = false)
|
|
||||||
: this(id, chatId, senderId, content, replyToId, forwardedFromId, createdAt, isImported) => Quote = quote;
|
|
||||||
}
|
|
||||||
|
|
||||||
public class MediaMessage : Message
|
|
||||||
{
|
|
||||||
public override string Type => MediaType.ToString().ToLower();
|
|
||||||
public override string? Content { get; protected set; }
|
|
||||||
public string? Caption { get => Content; private set => Content = value; }
|
|
||||||
public MediaType MediaType { get; private set; }
|
|
||||||
private List<Media> _media = new();
|
|
||||||
public override IReadOnlyCollection<Media> Media => _media.AsReadOnly();
|
|
||||||
private MediaMessage() : base() { MediaType = MediaType.File; }
|
|
||||||
public MediaMessage(Guid id, Guid chatId, Guid senderId, MediaType mediaType, string? caption, Guid? replyToId, Guid? forwardedFromId, DateTime createdAt, bool isImported)
|
|
||||||
: base(id, chatId, senderId, replyToId, forwardedFromId, createdAt, isImported) { MediaType = mediaType; Caption = caption; }
|
|
||||||
public MediaMessage(Guid id, Guid chatId, Guid senderId, string mediaType, string? caption, Guid? replyToId, Guid? forwardedFromId, DateTime createdAt, bool isImported)
|
|
||||||
: this(id, chatId, senderId, Enum.TryParse<MediaType>(mediaType, true, out var mt) ? mt : MediaType.File, caption, replyToId, forwardedFromId, createdAt, isImported) { }
|
|
||||||
public void AddMedia(string type, string url, string? filename, long? size) => _media.Add(new Media { Type = type, Url = url, FileId = filename, Size = size });
|
|
||||||
public override void Edit(string newCaption) => base.Edit(newCaption);
|
|
||||||
public override void Delete() { Caption = null; base.Delete(); }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class StoryMessage : Message
|
|
||||||
{
|
|
||||||
public override string Type => "story";
|
|
||||||
public override string? Content { get; protected set; }
|
|
||||||
public override Guid? StoryId { get; }
|
|
||||||
public string? InternalStoryMediaUrl { get; private set; }
|
|
||||||
public override string? StoryMediaUrl => InternalStoryMediaUrl;
|
|
||||||
public override string? StoryMediaType { get; }
|
|
||||||
public StoryMessage() : base() { }
|
|
||||||
public StoryMessage(Guid id, Guid chatId, Guid senderId, Guid storyId, string? storyMediaUrl, string? storyMediaType, DateTime createdAt)
|
|
||||||
: base(id, chatId, senderId, null, null, createdAt, false) { StoryId = storyId; InternalStoryMediaUrl = storyMediaUrl; StoryMediaType = storyMediaType; }
|
|
||||||
public StoryMessage(Guid id, Guid chatId, Guid senderId, Guid storyId, string? storyMediaUrl, string? storyMediaType, string? content, Guid? replyToId, Guid? forwardedFromId, DateTime createdAt, bool isImported)
|
|
||||||
: this(id, chatId, senderId, storyId, storyMediaUrl, storyMediaType, createdAt) { Content = content; ReplyToId = replyToId; ForwardedFromId = forwardedFromId; if (isImported) AddState(MessageState.IsImported); }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class PollMessage : Message
|
|
||||||
{
|
|
||||||
public override string Type => "poll";
|
|
||||||
public override string? Content { get; protected set; }
|
|
||||||
public List<PollOption> Options { get; } = new();
|
|
||||||
public List<PollVote> Votes { get; } = new();
|
|
||||||
public bool IsMultipleChoice { get; set; }
|
|
||||||
public DateTime? ExpiresAt { get; set; }
|
|
||||||
public bool IsClosed { get; set; }
|
|
||||||
public PollMessage() : base() { }
|
|
||||||
public PollMessage(Guid id, Guid chatId, Guid senderId, string? question, List<string>? options, bool isAnonymous, bool isMultiple, DateTime? expiresAt, Guid? replyToId, Guid? forwardedFromId, DateTime createdAt, bool isImported)
|
|
||||||
: base(id, chatId, senderId, replyToId, forwardedFromId, createdAt, isImported)
|
|
||||||
{
|
|
||||||
Content = question ?? "Poll";
|
|
||||||
if (options != null) foreach (var opt in options) Options.Add(new PollOption { Text = opt });
|
|
||||||
IsMultipleChoice = isMultiple;
|
|
||||||
ExpiresAt = expiresAt;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class PollOption { public string Text { get; set; } = string.Empty; public int VoteCount { get; set; } }
|
|
||||||
public class PollVote { public Guid OptionIndex { get; set; } public Guid UserId { get; set; } public DateTime VotedAt { get; set; } }
|
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace Knot.Contracts.Messaging.Domain;
|
||||||
|
|
||||||
|
public class PollMessage : Message
|
||||||
|
{
|
||||||
|
public override string Type => "poll";
|
||||||
|
public override string? Content { get; protected set; }
|
||||||
|
public List<PollOption> Options { get; set; } = new();
|
||||||
|
public List<PollVote> Votes { get; set; } = new();
|
||||||
|
public bool IsMultipleChoice { get; set; }
|
||||||
|
public bool IsAnonymous { get; set; }
|
||||||
|
public DateTime? ExpiresAt { get; set; }
|
||||||
|
public bool IsClosed { get; set; }
|
||||||
|
|
||||||
|
public PollMessage() : base() { }
|
||||||
|
|
||||||
|
public PollMessage(Guid id, Guid chatId, Guid senderId, string? question, List<PollOption>? options, bool isAnonymous, bool isMultiple, DateTime? expiresAt, Guid? replyToId, Guid? forwardedFromId, DateTime createdAt, bool isImported)
|
||||||
|
: base(id, chatId, senderId, replyToId, forwardedFromId, createdAt, isImported)
|
||||||
|
{
|
||||||
|
Content = question ?? "Poll";
|
||||||
|
Options = options ?? new List<PollOption>();
|
||||||
|
IsAnonymous = isAnonymous;
|
||||||
|
IsMultipleChoice = isMultiple;
|
||||||
|
ExpiresAt = expiresAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static PollMessage Create(Guid id, Guid chatId, Guid senderId, string? question, List<string> options, bool isAnonymous, bool isMultiple, DateTime? expiresAt, Guid? replyToId, Guid? forwardedFromId)
|
||||||
|
{
|
||||||
|
var poll = new PollMessage(id, chatId, senderId, question, null, isAnonymous, isMultiple, expiresAt, replyToId, forwardedFromId, DateTime.UtcNow, false);
|
||||||
|
foreach (var opt in options)
|
||||||
|
{
|
||||||
|
poll.Options.Add(new PollOption { Text = opt });
|
||||||
|
}
|
||||||
|
return poll;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace Knot.Contracts.Messaging.Domain;
|
||||||
|
|
||||||
|
public class PollOption
|
||||||
|
{
|
||||||
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
|
public string Text { get; set; } = string.Empty;
|
||||||
|
public int VoteCount { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace Knot.Contracts.Messaging.Domain;
|
||||||
|
|
||||||
|
public class PollVote
|
||||||
|
{
|
||||||
|
public Guid OptionId { get; set; }
|
||||||
|
public Guid UserId { get; set; }
|
||||||
|
public DateTime VotedAt { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace Knot.Contracts.Messaging.Domain;
|
||||||
|
|
||||||
|
public class StoryMessage : Message
|
||||||
|
{
|
||||||
|
public override string Type => "story";
|
||||||
|
public override string? Content { get; protected set; }
|
||||||
|
public Guid? StoryId { get; private set; }
|
||||||
|
public string? StoryMediaUrl { get; private set; }
|
||||||
|
public string? StoryMediaType { get; private set; }
|
||||||
|
|
||||||
|
public StoryMessage() : base() { }
|
||||||
|
|
||||||
|
public StoryMessage(Guid id, Guid chatId, Guid senderId, Guid storyId, string? storyMediaUrl, string? storyMediaType, DateTime createdAt)
|
||||||
|
: base(id, chatId, senderId, null, null, createdAt, false)
|
||||||
|
{
|
||||||
|
StoryId = storyId;
|
||||||
|
StoryMediaUrl = storyMediaUrl;
|
||||||
|
StoryMediaType = storyMediaType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public StoryMessage(Guid id, Guid chatId, Guid senderId, Guid storyId, string? storyMediaUrl, string? storyMediaType, string? content, Guid? replyToId, Guid? forwardedFromId, DateTime createdAt, bool isImported)
|
||||||
|
: this(id, chatId, senderId, storyId, storyMediaUrl, storyMediaType, createdAt)
|
||||||
|
{
|
||||||
|
Content = content;
|
||||||
|
ReplyToId = replyToId;
|
||||||
|
ForwardedFromId = forwardedFromId;
|
||||||
|
if (isImported) AddState(MessageState.IsImported);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace Knot.Contracts.Messaging.Domain;
|
||||||
|
|
||||||
|
public class TextMessage : Message
|
||||||
|
{
|
||||||
|
public override string Type => "text";
|
||||||
|
public override string? Content { get; protected set; }
|
||||||
|
public string? Quote { get; protected set; }
|
||||||
|
|
||||||
|
public TextMessage() : base() { }
|
||||||
|
|
||||||
|
public TextMessage(Guid id, Guid chatId, Guid senderId, string content, Guid? replyToId, Guid? forwardedFromId, DateTime createdAt, bool isImported = false)
|
||||||
|
: base(id, chatId, senderId, replyToId, forwardedFromId, createdAt, isImported) => Content = content;
|
||||||
|
|
||||||
|
public TextMessage(Guid id, Guid chatId, Guid senderId, string content, Guid? replyToId, string? quote, Guid? forwardedFromId, DateTime createdAt, bool isImported = false)
|
||||||
|
: this(id, chatId, senderId, content, replyToId, forwardedFromId, createdAt, isImported) => Quote = quote;
|
||||||
|
}
|
||||||
@@ -9,4 +9,8 @@ public static class ProfilesErrors
|
|||||||
public static Error AvatarNotFound => new("Profiles.AvatarNotFound", "Avatar not found");
|
public static Error AvatarNotFound => new("Profiles.AvatarNotFound", "Avatar not found");
|
||||||
public static Error InvalidAvatarFormat => new("Profiles.InvalidAvatarFormat", "Invalid avatar format");
|
public static Error InvalidAvatarFormat => new("Profiles.InvalidAvatarFormat", "Invalid avatar format");
|
||||||
public static Error AvatarUploadFailed => new("Profiles.AvatarUploadFailed", "Avatar upload failed");
|
public static Error AvatarUploadFailed => new("Profiles.AvatarUploadFailed", "Avatar upload failed");
|
||||||
|
public static Error BioTooLong => new("Profiles.BioTooLong", "Bio must be 200 characters or less");
|
||||||
|
public static Error StatusTextTooLong => new("Profiles.StatusTextTooLong", "Status text must be 50 characters or less");
|
||||||
|
public static Error StatusEmpty => new("Statuses.Empty", "Status emoji or text is required");
|
||||||
|
public static Error InvalidPreset => new("Statuses.InvalidPreset", "Unknown status preset");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace Knot.Contracts.Profiles.Application.DTOs;
|
||||||
|
|
||||||
|
public sealed class StatusPresetDto
|
||||||
|
{
|
||||||
|
public string Id { get; set; } = "";
|
||||||
|
public string Emoji { get; set; } = "";
|
||||||
|
public string TextRu { get; set; } = "";
|
||||||
|
public string TextEn { get; set; } = "";
|
||||||
|
}
|
||||||
@@ -10,6 +10,15 @@ public class UserProfileDto
|
|||||||
public string? Avatar { get; set; }
|
public string? Avatar { get; set; }
|
||||||
public bool IsBot { get; set; }
|
public bool IsBot { get; set; }
|
||||||
public DateTime? LastSeen { get; set; }
|
public DateTime? LastSeen { get; set; }
|
||||||
|
public DateTime? Birthday { get; set; }
|
||||||
public bool IsPremium { get; set; }
|
public bool IsPremium { get; set; }
|
||||||
|
public UserStatusDto? Status { get; set; }
|
||||||
|
|
||||||
|
public Guid? CurrentStatusId { get; set; }
|
||||||
|
|
||||||
|
public string? StatusText { get; set; }
|
||||||
|
public string? StatusEmoji { get; set; }
|
||||||
|
public DateTime? StatusExpiresAt { get; set; }
|
||||||
|
public bool IsInvisible { get; set; }
|
||||||
public DateTime CreatedAt { get; set; }
|
public DateTime CreatedAt { get; set; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
namespace Knot.Contracts.Profiles.Application.DTOs;
|
||||||
|
|
||||||
|
public sealed class UserStatusDto
|
||||||
|
{
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
public string Type { get; set; } = "Custom";
|
||||||
|
public string Emoji { get; set; } = "";
|
||||||
|
public string Text { get; set; } = "";
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
public DateTime? ExpiresAt { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
using Knot.Contracts.Profiles.Application.DTOs;
|
||||||
|
using Knot.Shared.Kernel;
|
||||||
|
|
||||||
|
namespace Knot.Contracts.Profiles.Domain;
|
||||||
|
|
||||||
|
public interface IProfileStatusWriter
|
||||||
|
{
|
||||||
|
Task<Result<UserProfileDto>> SetCustomAsync(Guid userId, string emoji, string text, DateTime? expiresAt, string? presetKey, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
Task<Result<UserProfileDto>> ClearAsync(Guid userId, CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using Knot.Contracts.Profiles.Application.DTOs;
|
||||||
|
|
||||||
|
namespace Knot.Contracts.Profiles.Domain;
|
||||||
|
|
||||||
|
public interface IUserStatusRepository
|
||||||
|
{
|
||||||
|
Task<UserStatusDto?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
Task<IReadOnlyDictionary<Guid, UserStatusDto>> GetByIdsAsync(IEnumerable<Guid> ids, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
Task InsertAsync(UserStatusDto dto, Guid userId, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
Task DeleteAsync(Guid id, CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
|
||||||
namespace Knot.Contracts.Settings.Application.DTOs;
|
namespace Knot.Contracts.Settings.Application.DTOs;
|
||||||
|
|
||||||
@@ -53,6 +53,7 @@ public class MessagesConfig
|
|||||||
public class WebRtcConfig
|
public class WebRtcConfig
|
||||||
{
|
{
|
||||||
public bool Enabled { get; set; } = false;
|
public bool Enabled { get; set; } = false;
|
||||||
|
public bool EnableVoiceCalls { get; set; } = true;
|
||||||
public bool EnableVideoCalls { get; set; } = true;
|
public bool EnableVideoCalls { get; set; } = true;
|
||||||
public bool EnableScreenSharing { get; set; } = true;
|
public bool EnableScreenSharing { get; set; } = true;
|
||||||
public string TurnHost { get; set; } = string.Empty;
|
public string TurnHost { get; set; } = string.Empty;
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ using MediatR;
|
|||||||
|
|
||||||
|
|
||||||
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
|
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
|
||||||
|
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
@@ -48,7 +49,7 @@ var builder = WebApplication.CreateBuilder(args);
|
|||||||
// Маппинг стандартных переменных окружения в иерархию .NET
|
// Маппинг стандартных переменных окружения в иерархию .NET
|
||||||
var envMappings = new Dictionary<string, string?>
|
var envMappings = new Dictionary<string, string?>
|
||||||
{
|
{
|
||||||
["ConnectionStrings:DefaultConnection"] = builder.Configuration["DATABASE_URL"] ?? "Host=localhost;Database=knot;Username=postgres;Password=postgres",
|
["ConnectionStrings:DefaultConnection"] = builder.Configuration["DATABASE_URL"] ?? builder.Configuration.GetConnectionString("DefaultConnection") ?? "Host=localhost;Database=knot;Username=postgres;Password=postgres",
|
||||||
["ConnectionStrings:MongoConnection"] = builder.Configuration["MONGO_CONNECTION"],
|
["ConnectionStrings:MongoConnection"] = builder.Configuration["MONGO_CONNECTION"],
|
||||||
["Jwt:Secret"] = builder.Configuration["JWT_SECRET"],
|
["Jwt:Secret"] = builder.Configuration["JWT_SECRET"],
|
||||||
["Jwt:Issuer"] = builder.Configuration["JWT_ISSUER"],
|
["Jwt:Issuer"] = builder.Configuration["JWT_ISSUER"],
|
||||||
@@ -80,6 +81,8 @@ builder.Services.AddStorageModule(builder.Configuration);
|
|||||||
builder.Services.AddStoriesModule(builder.Configuration);
|
builder.Services.AddStoriesModule(builder.Configuration);
|
||||||
builder.Services.AddKlipyModule();
|
builder.Services.AddKlipyModule();
|
||||||
builder.Services.AddAdminModule();
|
builder.Services.AddAdminModule();
|
||||||
|
builder.Services.AddWebRtcModule();
|
||||||
|
builder.Services.AddTelegramImportModule();
|
||||||
builder.Services.AddSharedInfrastructure(builder.Configuration);
|
builder.Services.AddSharedInfrastructure(builder.Configuration);
|
||||||
|
|
||||||
// CQRS / MediatR для команд в Host (например, AdminController)
|
// CQRS / MediatR для команд в Host (например, AdminController)
|
||||||
@@ -91,7 +94,11 @@ builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(
|
|||||||
typeof(Knot.Modules.Conversations.DependencyInjection).Assembly,
|
typeof(Knot.Modules.Conversations.DependencyInjection).Assembly,
|
||||||
typeof(Knot.Modules.Stories.DependencyInjection).Assembly,
|
typeof(Knot.Modules.Stories.DependencyInjection).Assembly,
|
||||||
typeof(Knot.Modules.Klipy.DependencyInjection).Assembly,
|
typeof(Knot.Modules.Klipy.DependencyInjection).Assembly,
|
||||||
typeof(Knot.Modules.Relations.DependencyInjection).Assembly
|
typeof(Knot.Modules.Relations.DependencyInjection).Assembly,
|
||||||
|
typeof(Knot.Modules.WebRtc.DependencyInjection).Assembly,
|
||||||
|
typeof(Knot.Modules.TelegramImport.DependencyInjection).Assembly,
|
||||||
|
typeof(Knot.Modules.Auth.Infrastructure.Persistence.AuthDbContext).Assembly,
|
||||||
|
typeof(Knot.Modules.Profiles.DependencyInjection).Assembly
|
||||||
));
|
));
|
||||||
|
|
||||||
// Настройка CORS
|
// Настройка CORS
|
||||||
@@ -243,6 +250,7 @@ app.MapStoriesEndpoints();
|
|||||||
app.MapContactsEndpoints();
|
app.MapContactsEndpoints();
|
||||||
app.MapSettingsEndpoints();
|
app.MapSettingsEndpoints();
|
||||||
app.MapProfilesEndpoints();
|
app.MapProfilesEndpoints();
|
||||||
|
app.MapStatusesEndpoints();
|
||||||
app.MapFederationEndpoints();
|
app.MapFederationEndpoints();
|
||||||
app.MapKlipyEndpoints();
|
app.MapKlipyEndpoints();
|
||||||
app.MapChatsEndpoints();
|
app.MapChatsEndpoints();
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ using Knot.Contracts.Auth.Infrastructure.Persistence;
|
|||||||
using Knot.Contracts.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Contracts.Conversations.Infrastructure.Persistence;
|
using Knot.Contracts.Conversations.Infrastructure.Persistence;
|
||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
using Knot.Contracts.Storage.Abstractions;
|
using Knot.Shared.Kernel.Storage;
|
||||||
using Knot.Contracts.Stories.Infrastructure.Persistence;
|
using Knot.Contracts.Stories.Infrastructure.Persistence;
|
||||||
using Knot.Modules.Admin.Application.Admin.DTOs;
|
using Knot.Modules.Admin.Application.Admin.DTOs;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
@@ -51,7 +51,7 @@ internal sealed class CleanRunCommandHandler : ICommandHandler<CleanRunCommand,
|
|||||||
var orphanMessages = await _messageQueryService.GetOrphanedMessagesAsync(activeChatIds, cancellationToken);
|
var orphanMessages = await _messageQueryService.GetOrphanedMessagesAsync(activeChatIds, cancellationToken);
|
||||||
|
|
||||||
var keptMessages = allMessages
|
var keptMessages = allMessages
|
||||||
.Where(m => !orphanMessages.Any(om => om.Id == m.Id))
|
.Where(m => !orphanMessages.Any(om => om.Id == m.Id) && !m.IsDeleted)
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
var allMinioFiles = (await _fileStorage.ListFilesAsync()).ToList();
|
var allMinioFiles = (await _fileStorage.ListFilesAsync()).ToList();
|
||||||
|
|||||||
+35
-14
@@ -1,4 +1,4 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
@@ -8,6 +8,7 @@ using Knot.Contracts.Auth.Infrastructure.Persistence;
|
|||||||
using Knot.Contracts.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Contracts.Conversations.Infrastructure.Persistence;
|
using Knot.Contracts.Conversations.Infrastructure.Persistence;
|
||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
|
using Knot.Shared.Kernel.Storage;
|
||||||
using Knot.Contracts.Stories.Infrastructure.Persistence;
|
using Knot.Contracts.Stories.Infrastructure.Persistence;
|
||||||
using Knot.Modules.Admin.Application.Admin.DTOs;
|
using Knot.Modules.Admin.Application.Admin.DTOs;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
@@ -23,17 +24,20 @@ internal sealed class CleanDryRunQueryHandler : IQueryHandler<CleanDryRunQuery,
|
|||||||
private readonly IAuthDbContext _authDbContext;
|
private readonly IAuthDbContext _authDbContext;
|
||||||
private readonly IChatsDbContext _chatsDbContext;
|
private readonly IChatsDbContext _chatsDbContext;
|
||||||
private readonly IStoryCollection _storyCollection;
|
private readonly IStoryCollection _storyCollection;
|
||||||
|
private readonly IFileStorageService _fileStorage;
|
||||||
|
|
||||||
public CleanDryRunQueryHandler(
|
public CleanDryRunQueryHandler(
|
||||||
Knot.Contracts.Messaging.Application.Abstractions.IMessageQueryService messageService,
|
Knot.Contracts.Messaging.Application.Abstractions.IMessageQueryService messageService,
|
||||||
IAuthDbContext authDbContext,
|
IAuthDbContext authDbContext,
|
||||||
IChatsDbContext chatsDbContext,
|
IChatsDbContext chatsDbContext,
|
||||||
IStoryCollection storyCollection)
|
IStoryCollection storyCollection,
|
||||||
|
IFileStorageService fileStorage)
|
||||||
{
|
{
|
||||||
_messageService = messageService;
|
_messageService = messageService;
|
||||||
_authDbContext = authDbContext;
|
_authDbContext = authDbContext;
|
||||||
_chatsDbContext = chatsDbContext;
|
_chatsDbContext = chatsDbContext;
|
||||||
_storyCollection = storyCollection;
|
_storyCollection = storyCollection;
|
||||||
|
_fileStorage = fileStorage;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Result<CleanDryRunResult>> Handle(CleanDryRunQuery request, CancellationToken ct)
|
public async Task<Result<CleanDryRunResult>> Handle(CleanDryRunQuery request, CancellationToken ct)
|
||||||
@@ -46,25 +50,42 @@ internal sealed class CleanDryRunQueryHandler : IQueryHandler<CleanDryRunQuery,
|
|||||||
var orphanedMediaCount = orphanedMessages.Count(m => m.MediaUrl != null);
|
var orphanedMediaCount = orphanedMessages.Count(m => m.MediaUrl != null);
|
||||||
var orphanedMessageCount = orphanedMessages.Count;
|
var orphanedMessageCount = orphanedMessages.Count;
|
||||||
|
|
||||||
var validIds = new HashSet<string>();
|
var allMessages = await _messageService.GetAllMessagesAsync(ct);
|
||||||
foreach (var msg in orphanedMessages.Where(m => m.MediaUrl != null))
|
var keptMessages = allMessages
|
||||||
{
|
.Where(m => !orphanedMessages.Any(om => om.Id == m.Id) && !m.IsDeleted)
|
||||||
var parts = msg.MediaUrl.Split('/');
|
.ToList();
|
||||||
var fileId = parts.LastOrDefault();
|
var allUsers = await _authDbContext.Users.ToListAsync(ct);
|
||||||
if (!string.IsNullOrEmpty(fileId))
|
|
||||||
{
|
|
||||||
validIds.Add(fileId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var stories = await _storyCollection.GetAllAsync(ct);
|
var stories = await _storyCollection.GetAllAsync(ct);
|
||||||
|
|
||||||
|
var validUrls = new HashSet<string>();
|
||||||
|
|
||||||
|
var activeMessageUrls = keptMessages.Where(m => m.Media != null).SelectMany(m => m.Media!).Select(x => x.Url).Where(u => !string.IsNullOrEmpty(u));
|
||||||
|
var activeChatUrls = _chatsDbContext.Chats.Select(c => c.Avatar).Where(u => !string.IsNullOrEmpty(u));
|
||||||
|
var activeUserUrls = allUsers.Select(u => u.Avatar).Where(u => !string.IsNullOrEmpty(u));
|
||||||
|
var activeStoryUrls = stories.Select(s => s.MediaUrl).Where(u => !string.IsNullOrEmpty(u));
|
||||||
|
|
||||||
|
foreach (var u in activeMessageUrls) validUrls.Add(u!);
|
||||||
|
foreach (var u in activeChatUrls) validUrls.Add(u!);
|
||||||
|
foreach (var u in activeUserUrls) validUrls.Add(u!);
|
||||||
|
foreach (var u in activeStoryUrls) validUrls.Add(u!);
|
||||||
|
|
||||||
|
var validFileIds = validUrls
|
||||||
|
.Where(u => u.Contains("/api/files/"))
|
||||||
|
.Select(u => u.Split('/').Last())
|
||||||
|
.ToHashSet();
|
||||||
|
|
||||||
|
var allMinioFiles = await _fileStorage.ListFilesAsync();
|
||||||
|
long orphanedFileSize = allMinioFiles
|
||||||
|
.Where(f => !validFileIds.Contains(f.FileId))
|
||||||
|
.Sum(f => f.Size);
|
||||||
|
|
||||||
var expiredStoriesCount = stories.Count(s => s.ExpiresAt.HasValue && s.ExpiresAt.Value < DateTime.UtcNow);
|
var expiredStoriesCount = stories.Count(s => s.ExpiresAt.HasValue && s.ExpiresAt.Value < DateTime.UtcNow);
|
||||||
var expiredStoriesSize = stories.Where(s => s.ExpiresAt.HasValue && s.ExpiresAt.Value < DateTime.UtcNow).Sum(s => s.MediaUrl?.Length ?? 0);
|
var expiredStoriesSize = stories.Where(s => s.ExpiresAt.HasValue && s.ExpiresAt.Value < DateTime.UtcNow).Sum(s => s.MediaUrl?.Length ?? 0);
|
||||||
|
|
||||||
return Result.Success(new CleanDryRunResult(
|
return Result.Success(new CleanDryRunResult(
|
||||||
orphanedMessageCount,
|
orphanedMessageCount,
|
||||||
orphanedMediaCount,
|
orphanedMediaCount,
|
||||||
0,
|
orphanedFileSize,
|
||||||
expiredStoriesCount,
|
expiredStoriesCount,
|
||||||
expiredStoriesSize
|
expiredStoriesSize
|
||||||
));
|
));
|
||||||
|
|||||||
@@ -131,6 +131,17 @@ public static class AdminEndpoints
|
|||||||
return Results.Ok(result.Value);
|
return Results.Ok(result.Value);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
group.MapPost("clean/run", async (ISender sender, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var result = await sender.Send(new CleanRunCommand(), ct);
|
||||||
|
if (!result.IsSuccess)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"[Admin] Cleanup Run Error: {result.Error.Description}");
|
||||||
|
return Results.BadRequest(new { error = result.Error.Description });
|
||||||
|
}
|
||||||
|
return Results.Ok(result.Value);
|
||||||
|
});
|
||||||
|
|
||||||
group.MapGet("timezones", () =>
|
group.MapGet("timezones", () =>
|
||||||
{
|
{
|
||||||
// Получаем все системные часовые пояса и формируем удобный для фронтенда формат
|
// Получаем все системные часовые пояса и формируем удобный для фронтенда формат
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
using BCrypt.Net;
|
||||||
|
using Knot.Contracts.Auth.Application.Abstractions;
|
||||||
|
using Knot.Contracts.Auth.Application.Auth.DTOs;
|
||||||
|
using Knot.Modules.Auth.Domain;
|
||||||
|
using Knot.Shared.Kernel;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Knot.Modules.Auth.Application.Users.ChangePassword;
|
||||||
|
|
||||||
|
public sealed record ChangePasswordCommand(
|
||||||
|
Guid UserId,
|
||||||
|
string OldPassword,
|
||||||
|
string NewPassword,
|
||||||
|
string ConfirmPassword) : ICommand;
|
||||||
|
|
||||||
|
internal sealed class ChangePasswordCommandHandler : ICommandHandler<ChangePasswordCommand>
|
||||||
|
{
|
||||||
|
private readonly IAuthDbContext _dbContext;
|
||||||
|
|
||||||
|
public ChangePasswordCommandHandler(IAuthDbContext dbContext)
|
||||||
|
{
|
||||||
|
_dbContext = dbContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Result> Handle(ChangePasswordCommand request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (request.NewPassword != request.ConfirmPassword)
|
||||||
|
return Result.Failure(AuthErrors.PasswordConfirmationMismatch);
|
||||||
|
|
||||||
|
if (request.NewPassword.Length < 8)
|
||||||
|
return Result.Failure(AuthErrors.PasswordTooShort);
|
||||||
|
|
||||||
|
var user = await _dbContext.Set<User>()
|
||||||
|
.FirstOrDefaultAsync(u => u.Id == request.UserId, cancellationToken);
|
||||||
|
|
||||||
|
if (user is null)
|
||||||
|
return Result.Failure(AuthErrors.UserNotFound);
|
||||||
|
|
||||||
|
if (!BCrypt.Net.BCrypt.Verify(request.OldPassword, user.PasswordHash))
|
||||||
|
return Result.Failure(AuthErrors.OldPasswordInvalid);
|
||||||
|
|
||||||
|
user.ChangePassword(BCrypt.Net.BCrypt.HashPassword(request.NewPassword));
|
||||||
|
user.SetRefreshToken(null);
|
||||||
|
|
||||||
|
await _dbContext.SaveChangesAsync(cancellationToken);
|
||||||
|
return Result.Success();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,7 +29,8 @@ internal sealed class GetMeQueryHandler : IQueryHandler<GetMeQuery, AuthResponse
|
|||||||
RefreshToken = string.Empty,
|
RefreshToken = string.Empty,
|
||||||
UserId = user.Id,
|
UserId = user.Id,
|
||||||
Username = user.Username,
|
Username = user.Username,
|
||||||
DisplayName = user.DisplayName
|
DisplayName = user.DisplayName,
|
||||||
|
Avatar = user.Avatar
|
||||||
};
|
};
|
||||||
|
|
||||||
return Result.Success(response);
|
return Result.Success(response);
|
||||||
|
|||||||
@@ -72,6 +72,9 @@ public sealed class User : AggregateRoot<Guid>
|
|||||||
Username = contract.Username;
|
Username = contract.Username;
|
||||||
DisplayName = contract.DisplayName;
|
DisplayName = contract.DisplayName;
|
||||||
PhoneNumber = contract.PhoneNumber;
|
PhoneNumber = contract.PhoneNumber;
|
||||||
|
Bio = contract.Bio;
|
||||||
|
Avatar = contract.Avatar;
|
||||||
|
Birthday = contract.Birthday;
|
||||||
IsBanned = contract.IsBanned;
|
IsBanned = contract.IsBanned;
|
||||||
BannedUntil = contract.BannedUntil;
|
BannedUntil = contract.BannedUntil;
|
||||||
SetOnline(contract.IsOnline, contract.LastSeen);
|
SetOnline(contract.IsOnline, contract.LastSeen);
|
||||||
|
|||||||
@@ -65,6 +65,7 @@ internal sealed class UserRepository : IUserRepository
|
|||||||
{
|
{
|
||||||
domainUser.UpdateFromContract(user);
|
domainUser.UpdateFromContract(user);
|
||||||
_context.Users.Update(domainUser);
|
_context.Users.Update(domainUser);
|
||||||
|
await _context.SaveChangesAsync(cancellationToken);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+106
@@ -0,0 +1,106 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using Knot.Modules.Auth.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 Knot.Modules.Auth.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(AuthDbContext))]
|
||||||
|
[Migration("20260407181656_AddUserInfoFields")]
|
||||||
|
partial class AddUserInfoFields
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder
|
||||||
|
.HasDefaultSchema("identity")
|
||||||
|
.HasAnnotation("ProductVersion", "10.0.4")
|
||||||
|
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||||
|
|
||||||
|
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||||
|
|
||||||
|
modelBuilder.Entity("Knot.Modules.Auth.Domain.User", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<string>("Avatar")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<DateTime?>("BannedUntil")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Bio")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<DateTime?>("Birthday")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<DateTime>("CreatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("DisplayName")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("Domain")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("Email")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<bool>("HideStatus")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<bool>("HideStoryViews")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<bool>("IsBanned")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<bool>("IsExternal")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<bool>("IsOnline")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<DateTime?>("LastSeen")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("PasswordHash")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("PhoneNumber")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("RefreshToken")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("UserDomain")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("Username")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(50)
|
||||||
|
.HasColumnType("character varying(50)");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("Username")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.ToTable("Users", "identity");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Knot.Modules.Auth.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddUserInfoFields : Migration
|
||||||
|
{
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.Sql(@"
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='identity' AND table_name='Users' AND column_name='BannedUntil') THEN
|
||||||
|
ALTER TABLE identity.""Users"" ADD ""BannedUntil"" timestamp with time zone;
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='identity' AND table_name='Users' AND column_name='PhoneNumber') THEN
|
||||||
|
ALTER TABLE identity.""Users"" ADD ""PhoneNumber"" text;
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='identity' AND table_name='Users' AND column_name='RefreshToken') THEN
|
||||||
|
ALTER TABLE identity.""Users"" ADD ""RefreshToken"" text;
|
||||||
|
END IF;
|
||||||
|
END $$;");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(name: "BannedUntil", schema: "identity", table: "Users");
|
||||||
|
migrationBuilder.DropColumn(name: "PhoneNumber", schema: "identity", table: "Users");
|
||||||
|
migrationBuilder.DropColumn(name: "RefreshToken", schema: "identity", table: "Users");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
// <auto-generated />
|
// <auto-generated />
|
||||||
using System;
|
using System;
|
||||||
using Knot.Modules.Auth.Infrastructure.Persistence;
|
using Knot.Modules.Auth.Infrastructure.Persistence;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
@@ -23,7 +23,7 @@ namespace Knot.Modules.Auth.Migrations
|
|||||||
|
|
||||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||||
|
|
||||||
modelBuilder.Entity("Knot.Contracts.Auth.Domain.User", b =>
|
modelBuilder.Entity("Knot.Modules.Auth.Domain.User", b =>
|
||||||
{
|
{
|
||||||
b.Property<Guid>("Id")
|
b.Property<Guid>("Id")
|
||||||
.ValueGeneratedOnAdd()
|
.ValueGeneratedOnAdd()
|
||||||
@@ -32,6 +32,9 @@ namespace Knot.Modules.Auth.Migrations
|
|||||||
b.Property<string>("Avatar")
|
b.Property<string>("Avatar")
|
||||||
.HasColumnType("text");
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<DateTime?>("BannedUntil")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
b.Property<string>("Bio")
|
b.Property<string>("Bio")
|
||||||
.HasColumnType("text");
|
.HasColumnType("text");
|
||||||
|
|
||||||
@@ -57,10 +60,10 @@ namespace Knot.Modules.Auth.Migrations
|
|||||||
b.Property<bool>("HideStoryViews")
|
b.Property<bool>("HideStoryViews")
|
||||||
.HasColumnType("boolean");
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
b.Property<bool>("IsExternal")
|
b.Property<bool>("IsBanned")
|
||||||
.HasColumnType("boolean");
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
b.Property<bool>("IsBanned")
|
b.Property<bool>("IsExternal")
|
||||||
.HasColumnType("boolean");
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
b.Property<bool>("IsOnline")
|
b.Property<bool>("IsOnline")
|
||||||
@@ -73,6 +76,15 @@ namespace Knot.Modules.Auth.Migrations
|
|||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnType("text");
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("PhoneNumber")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("RefreshToken")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("UserDomain")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
b.Property<string>("Username")
|
b.Property<string>("Username")
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasMaxLength(50)
|
.HasMaxLength(50)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ using Knot.Shared.Kernel;
|
|||||||
using Knot.Modules.Auth.Application.Users.Login;
|
using Knot.Modules.Auth.Application.Users.Login;
|
||||||
using Knot.Modules.Auth.Application.Users.Register;
|
using Knot.Modules.Auth.Application.Users.Register;
|
||||||
using Knot.Modules.Auth.Application.Users.GetMe;
|
using Knot.Modules.Auth.Application.Users.GetMe;
|
||||||
|
using Knot.Modules.Auth.Application.Users.ChangePassword;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
@@ -12,6 +13,8 @@ namespace Knot.Modules.Auth.Presentation.Endpoints;
|
|||||||
|
|
||||||
public static class AuthEndpoints
|
public static class AuthEndpoints
|
||||||
{
|
{
|
||||||
|
public sealed record ChangePasswordRequest(string OldPassword, string NewPassword, string ConfirmPassword);
|
||||||
|
|
||||||
public static void MapAuthEndpoints(this WebApplication app)
|
public static void MapAuthEndpoints(this WebApplication app)
|
||||||
{
|
{
|
||||||
var group = app.MapGroup("api/auth");
|
var group = app.MapGroup("api/auth");
|
||||||
@@ -33,5 +36,19 @@ public static class AuthEndpoints
|
|||||||
var result = await sender.Send(new GetMeQuery(userContext.UserId), ct);
|
var result = await sender.Send(new GetMeQuery(userContext.UserId), ct);
|
||||||
return result.IsSuccess ? Results.Ok(result.Value) : Results.NotFound();
|
return result.IsSuccess ? Results.Ok(result.Value) : Results.NotFound();
|
||||||
}).RequireAuthorization();
|
}).RequireAuthorization();
|
||||||
|
|
||||||
|
group.MapPost("change-password", async ([FromBody] ChangePasswordRequest request, ISender sender, IUserContext userContext, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var result = await sender.Send(
|
||||||
|
new ChangePasswordCommand(userContext.UserId, request.OldPassword, request.NewPassword, request.ConfirmPassword),
|
||||||
|
ct);
|
||||||
|
|
||||||
|
if (result.IsSuccess) return Results.Ok();
|
||||||
|
|
||||||
|
if (result.Error.Code == "Auth.OldPasswordInvalid")
|
||||||
|
return Results.StatusCode(StatusCodes.Status403Forbidden);
|
||||||
|
|
||||||
|
return Results.BadRequest(new { error = result.Error.Code ?? result.Error.Description });
|
||||||
|
}).RequireAuthorization();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
using Knot.Shared.Kernel;
|
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Application.Abstractions;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Unit of Work специфичный для модуля Chats.
|
|
||||||
/// </summary>
|
|
||||||
public interface IChatsUnitOfWork : IUnitOfWork
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Threading;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using Knot.Shared.Kernel;
|
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Application.Abstractions;
|
|
||||||
|
|
||||||
public interface IUserDeleterService
|
|
||||||
{
|
|
||||||
Task<Result> DeleteUserAsync(Guid userId, CancellationToken cancellationToken);
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
using System;
|
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Application.Abstractions;
|
|
||||||
|
|
||||||
public interface IUserStatusService
|
|
||||||
{
|
|
||||||
bool IsUserOnline(string userId);
|
|
||||||
}
|
|
||||||
@@ -4,8 +4,8 @@ using System.Threading;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using Knot.Shared.Kernel.Storage;
|
using Knot.Shared.Kernel.Storage;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using SixLabors.ImageSharp;
|
using SixLabors.ImageSharp;
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ using System;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
|
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Application.Chats.Create;
|
namespace Knot.Modules.Conversations.Application.Chats.Create;
|
||||||
|
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ using System.Threading;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
using Knot.Contracts.Messaging.Domain;
|
using Knot.Contracts.Messaging.Domain;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using Knot.Modules.Conversations.Application.DTOs;
|
using Knot.Modules.Conversations.Application.DTOs;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
|
|
||||||
@@ -63,6 +63,9 @@ internal sealed class GetChatByIdQueryHandler : IQueryHandler<GetChatByIdQuery,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var pinnedMessages = await _messageRepository.GetPinnedMessagesAsync(chat.Id, cancellationToken);
|
||||||
|
foreach (var pm in pinnedMessages) userIdsToFetch.Add(pm.SenderId);
|
||||||
|
|
||||||
var usersInfo = await _userProvider.GetUsersInfoAsync(userIdsToFetch, cancellationToken);
|
var usersInfo = await _userProvider.GetUsersInfoAsync(userIdsToFetch, cancellationToken);
|
||||||
|
|
||||||
var members = new List<ChatMemberDto>();
|
var members = new List<ChatMemberDto>();
|
||||||
@@ -88,51 +91,19 @@ internal sealed class GetChatByIdQueryHandler : IQueryHandler<GetChatByIdQuery,
|
|||||||
var messagesList = new List<ChatMessageDto>();
|
var messagesList = new List<ChatMessageDto>();
|
||||||
if (latestMessage != null)
|
if (latestMessage != null)
|
||||||
{
|
{
|
||||||
usersInfo.TryGetValue(latestMessage.SenderId, out var senderObj);
|
messagesList.Add(MessageMapper.MapToDto(
|
||||||
|
latestMessage,
|
||||||
var reactionsWithUser = new List<ReactionDto>();
|
usersInfo,
|
||||||
foreach (var reaction in latestReactions)
|
latestReactions,
|
||||||
{
|
chat.Members.Where(m => m.LastReadSequenceId >= latestMessage.SequenceId && m.UserId != latestMessage.SenderId).Select(m => m.UserId)));
|
||||||
usersInfo.TryGetValue(reaction.UserId, out var reactionUser);
|
|
||||||
reactionsWithUser.Add(new ReactionDto(
|
|
||||||
reaction.Id,
|
|
||||||
reaction.Emoji,
|
|
||||||
reaction.UserId,
|
|
||||||
reactionUser != null
|
|
||||||
? new MessageSenderDto(reactionUser.Id, reactionUser.Username, reactionUser.DisplayName, reactionUser.Avatar)
|
|
||||||
: new MessageSenderDto(reaction.UserId, "unknown", "Unknown", null)
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var readByList = chat.Members
|
var pinnedDtoList = new List<PinnedMessageDto>();
|
||||||
.Where(m => m.LastReadSequenceId >= latestMessage.SequenceId && m.UserId != latestMessage.SenderId)
|
foreach (var pm in pinnedMessages)
|
||||||
.Select(m => new ReadByDto(m.UserId))
|
{
|
||||||
.ToList();
|
pinnedDtoList.Add(new PinnedMessageDto(
|
||||||
|
pm.Id,
|
||||||
messagesList.Add(new ChatMessageDto(
|
MessageMapper.MapToDto(pm, usersInfo, new List<MessageReaction>(), new List<Guid>())
|
||||||
latestMessage.Id,
|
|
||||||
latestMessage.ChatId,
|
|
||||||
latestMessage.SenderId,
|
|
||||||
latestMessage.Content,
|
|
||||||
latestMessage.Type,
|
|
||||||
latestMessage.ReplyToId,
|
|
||||||
latestMessage.Quote,
|
|
||||||
latestMessage.StoryId,
|
|
||||||
latestMessage.StoryMediaUrl,
|
|
||||||
latestMessage.StoryMediaType,
|
|
||||||
latestMessage.IsEdited,
|
|
||||||
latestMessage.IsDeleted,
|
|
||||||
latestMessage.CreatedAt,
|
|
||||||
latestMessage.SequenceId,
|
|
||||||
latestMessage.Media.Select(media => new MediaDto(media.Id, media.Type, media.Url, media.Filename, media.Size)).ToList(),
|
|
||||||
senderObj != null ? new MessageSenderDto(
|
|
||||||
senderObj.Id,
|
|
||||||
senderObj.Username,
|
|
||||||
senderObj.DisplayName,
|
|
||||||
senderObj.Avatar
|
|
||||||
) : new MessageSenderDto(latestMessage.SenderId, "unknown", "Unknown", null),
|
|
||||||
reactionsWithUser,
|
|
||||||
readByList
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,6 +119,7 @@ internal sealed class GetChatByIdQueryHandler : IQueryHandler<GetChatByIdQuery,
|
|||||||
chat.CreatedAt,
|
chat.CreatedAt,
|
||||||
members,
|
members,
|
||||||
messagesList,
|
messagesList,
|
||||||
|
pinnedDtoList,
|
||||||
unreadCount
|
unreadCount
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ using System.Threading;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
using Knot.Contracts.Messaging.Domain;
|
using Knot.Contracts.Messaging.Domain;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using Knot.Modules.Conversations.Application.DTOs;
|
using Knot.Modules.Conversations.Application.DTOs;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
|
|
||||||
@@ -59,6 +59,9 @@ internal sealed class GetChatsQueryHandler : IQueryHandler<GetChatsQuery, List<C
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var pinnedMessages = await _messageRepository.GetPinnedMessagesAsync(chat.Id, cancellationToken);
|
||||||
|
foreach (var pm in pinnedMessages) userIdsToFetch.Add(pm.SenderId);
|
||||||
|
|
||||||
var usersInfo = await _userProvider.GetUsersInfoAsync(userIdsToFetch, cancellationToken);
|
var usersInfo = await _userProvider.GetUsersInfoAsync(userIdsToFetch, cancellationToken);
|
||||||
|
|
||||||
var members = new List<ChatMemberDto>();
|
var members = new List<ChatMemberDto>();
|
||||||
@@ -85,46 +88,19 @@ internal sealed class GetChatsQueryHandler : IQueryHandler<GetChatsQuery, List<C
|
|||||||
|
|
||||||
if (latestMessage != null)
|
if (latestMessage != null)
|
||||||
{
|
{
|
||||||
usersInfo.TryGetValue(latestMessage.SenderId, out var senderObj);
|
messagesList.Add(MessageMapper.MapToDto(
|
||||||
|
latestMessage,
|
||||||
var reactionsWithUser = new List<ReactionDto>();
|
usersInfo,
|
||||||
foreach (var reaction in latestReactions)
|
latestReactions,
|
||||||
{
|
chat.Members.Where(m => m.LastReadSequenceId >= latestMessage.SequenceId && m.UserId != latestMessage.SenderId).Select(m => m.UserId)));
|
||||||
usersInfo.TryGetValue(reaction.UserId, out var reactionUser);
|
|
||||||
reactionsWithUser.Add(new ReactionDto(
|
|
||||||
reaction.Id,
|
|
||||||
reaction.Emoji,
|
|
||||||
reaction.UserId,
|
|
||||||
reactionUser != null
|
|
||||||
? new MessageSenderDto(reactionUser.Id, reactionUser.Username, reactionUser.DisplayName, reactionUser.Avatar)
|
|
||||||
: new MessageSenderDto(reaction.UserId, "unknown", "Unknown", null)
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
messagesList.Add(new ChatMessageDto(
|
var pinnedDtoList = new List<PinnedMessageDto>();
|
||||||
latestMessage.Id,
|
foreach (var pm in pinnedMessages)
|
||||||
latestMessage.ChatId,
|
{
|
||||||
latestMessage.SenderId,
|
pinnedDtoList.Add(new PinnedMessageDto(
|
||||||
latestMessage.Content,
|
pm.Id,
|
||||||
latestMessage.Type,
|
MessageMapper.MapToDto(pm, usersInfo, new List<MessageReaction>(), new List<Guid>())
|
||||||
latestMessage.ReplyToId,
|
|
||||||
latestMessage.Quote,
|
|
||||||
latestMessage.StoryId,
|
|
||||||
latestMessage.StoryMediaUrl,
|
|
||||||
latestMessage.StoryMediaType,
|
|
||||||
latestMessage.IsEdited,
|
|
||||||
latestMessage.IsDeleted,
|
|
||||||
latestMessage.CreatedAt,
|
|
||||||
latestMessage.SequenceId,
|
|
||||||
latestMessage.Media.Select(media => new MediaDto(media.Id, media.Type, media.Url, media.Filename, media.Size)).ToList(),
|
|
||||||
senderObj != null ? new MessageSenderDto(
|
|
||||||
senderObj.Id,
|
|
||||||
senderObj.Username,
|
|
||||||
senderObj.DisplayName,
|
|
||||||
senderObj.Avatar
|
|
||||||
) : new MessageSenderDto(latestMessage.SenderId, "unknown", "Unknown", null),
|
|
||||||
reactionsWithUser,
|
|
||||||
chat.Members.Where(m => m.LastReadSequenceId >= latestMessage.SequenceId && m.UserId != latestMessage.SenderId).Select(m => new ReadByDto(m.UserId)).ToList()
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,7 +116,10 @@ internal sealed class GetChatsQueryHandler : IQueryHandler<GetChatsQuery, List<C
|
|||||||
chat.CreatedAt,
|
chat.CreatedAt,
|
||||||
members,
|
members,
|
||||||
messagesList,
|
messagesList,
|
||||||
unreadCount
|
pinnedDtoList,
|
||||||
|
unreadCount,
|
||||||
|
chat.IsImporting,
|
||||||
|
chat.ImportJobId
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Application.Chats.GetOrCreateFavorites;
|
namespace Knot.Modules.Conversations.Application.Chats.GetOrCreateFavorites;
|
||||||
|
|
||||||
|
|||||||
+59
-5
@@ -1,12 +1,13 @@
|
|||||||
|
|
||||||
using System;
|
using System;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
|
using Knot.Shared.Kernel.Storage;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Application.Chats.LeaveOrDelete;
|
namespace Knot.Modules.Conversations.Application.Chats.LeaveOrDelete;
|
||||||
|
|
||||||
@@ -15,11 +16,19 @@ public record LeaveOrDeleteChatCommand(Guid ChatId, Guid UserId) : ICommand<Succ
|
|||||||
internal sealed class LeaveOrDeleteChatCommandHandler : ICommandHandler<LeaveOrDeleteChatCommand, SuccessResponse>
|
internal sealed class LeaveOrDeleteChatCommandHandler : ICommandHandler<LeaveOrDeleteChatCommand, SuccessResponse>
|
||||||
{
|
{
|
||||||
private readonly IChatRepository _chatRepository;
|
private readonly IChatRepository _chatRepository;
|
||||||
|
private readonly IMessageRepository _messageRepository;
|
||||||
|
private readonly IFileStorageService _fileStorage;
|
||||||
private readonly IChatsUnitOfWork _uow;
|
private readonly IChatsUnitOfWork _uow;
|
||||||
|
|
||||||
public LeaveOrDeleteChatCommandHandler(IChatRepository chatRepository, IChatsUnitOfWork uow)
|
public LeaveOrDeleteChatCommandHandler(
|
||||||
|
IChatRepository chatRepository,
|
||||||
|
IMessageRepository messageRepository,
|
||||||
|
IFileStorageService fileStorage,
|
||||||
|
IChatsUnitOfWork uow)
|
||||||
{
|
{
|
||||||
_chatRepository = chatRepository;
|
_chatRepository = chatRepository;
|
||||||
|
_messageRepository = messageRepository;
|
||||||
|
_fileStorage = fileStorage;
|
||||||
_uow = uow;
|
_uow = uow;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,13 +45,18 @@ internal sealed class LeaveOrDeleteChatCommandHandler : ICommandHandler<LeaveOrD
|
|||||||
return Result.Failure<SuccessResponse>(ChatErrors.Unauthorized);
|
return Result.Failure<SuccessResponse>(ChatErrors.Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (chat.Type == ChatType.Group)
|
// If it's a private chat or the last member leaving a group, delete everything
|
||||||
|
bool shouldDeleteEverything = chat.Type != ChatType.Group || chat.Members.Count <= 1;
|
||||||
|
|
||||||
|
if (chat.Type == ChatType.Group && !shouldDeleteEverything)
|
||||||
{
|
{
|
||||||
chat.RemoveMember(request.UserId);
|
chat.RemoveMember(request.UserId);
|
||||||
_chatRepository.Update(chat);
|
_chatRepository.Update(chat);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
// DELETE ALL MESSAGES AND FILES FIRST
|
||||||
|
await DeleteChatMediaAndMessagesAsync(chat.Id, cancellationToken);
|
||||||
_chatRepository.Remove(chat);
|
_chatRepository.Remove(chat);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,5 +64,45 @@ internal sealed class LeaveOrDeleteChatCommandHandler : ICommandHandler<LeaveOrD
|
|||||||
|
|
||||||
return Result.Success(new SuccessResponse(true));
|
return Result.Success(new SuccessResponse(true));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async Task DeleteChatMediaAndMessagesAsync(Guid chatId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Get all messages directly from Mongo (not paged)
|
||||||
|
var messages = await _messageRepository.GetChatMessagesAsync(chatId, int.MaxValue, 0, ct);
|
||||||
|
foreach (var msg in messages)
|
||||||
|
{
|
||||||
|
if (msg is Knot.Contracts.Messaging.Domain.MediaMessage mediaMsg)
|
||||||
|
{
|
||||||
|
foreach (var media in mediaMsg.Media)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrEmpty(media.Url))
|
||||||
|
{
|
||||||
|
var fileId = ExtractFileId(media.Url);
|
||||||
|
if (!string.IsNullOrEmpty(fileId))
|
||||||
|
{
|
||||||
|
await _fileStorage.DeleteFileAsync(fileId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await _messageRepository.DeleteChatMessagesAsync(chatId, ct);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// Log if possible, but don't fail chat deletion
|
||||||
|
Console.WriteLine($"[Cleanup] Error deleting chat media: {ex.Message}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private string? ExtractFileId(string url)
|
||||||
|
{
|
||||||
|
var lastSlash = url.LastIndexOf('/');
|
||||||
|
if (lastSlash == -1) return null;
|
||||||
|
var id = url[(lastSlash + 1)..];
|
||||||
|
if (id.Contains('?')) id = id[..id.IndexOf('?')];
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ using System.Collections.Generic;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ using System;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using Knot.Modules.Conversations.Application.DTOs;
|
using Knot.Modules.Conversations.Application.DTOs;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ using System;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,9 @@ public record ChatDto(
|
|||||||
DateTime CreatedAt,
|
DateTime CreatedAt,
|
||||||
List<ChatMemberDto> Members,
|
List<ChatMemberDto> Members,
|
||||||
List<ChatMessageDto> Messages,
|
List<ChatMessageDto> Messages,
|
||||||
int UnreadCount
|
List<PinnedMessageDto> PinnedMessages,
|
||||||
|
int UnreadCount,
|
||||||
|
bool IsImporting = false,
|
||||||
|
Guid? ImportJobId = null
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using System;
|
using System;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Application.DTOs;
|
namespace Knot.Modules.Conversations.Application.DTOs;
|
||||||
|
|||||||
@@ -21,6 +21,17 @@ public record ChatMessageDto(
|
|||||||
List<MediaDto> Media,
|
List<MediaDto> Media,
|
||||||
MessageSenderDto Sender,
|
MessageSenderDto Sender,
|
||||||
List<ReactionDto> Reactions,
|
List<ReactionDto> Reactions,
|
||||||
List<ReadByDto> ReadBy
|
List<ReadByDto> ReadBy,
|
||||||
|
string? CallType = null,
|
||||||
|
string? CallStatus = null,
|
||||||
|
int? Duration = null,
|
||||||
|
List<PollOptionDto>? PollOptions = null,
|
||||||
|
bool? PollIsMultipleChoice = null,
|
||||||
|
bool? PollIsAnonymous = null,
|
||||||
|
bool? PollIsClosed = null,
|
||||||
|
List<Guid>? UserVotedOptionIds = null
|
||||||
);
|
);
|
||||||
|
|
||||||
|
public record PollOptionDto(Guid Id, string Text, int VoteCount, List<MessageSenderDto>? Voters = null, List<Guid>? VoterIds = null);
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Application.DTOs;
|
namespace Knot.Modules.Conversations.Application.DTOs;
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,6 @@ public record MediaDto(
|
|||||||
string Type,
|
string Type,
|
||||||
string? Url,
|
string? Url,
|
||||||
string? Filename,
|
string? Filename,
|
||||||
long? Size
|
long? Size,
|
||||||
|
string? Duration = null
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,15 @@ public record MessageDetailDto(
|
|||||||
List<MediaDto> Media,
|
List<MediaDto> Media,
|
||||||
MessageSenderDto? Sender,
|
MessageSenderDto? Sender,
|
||||||
List<ReadByDto> ReadBy,
|
List<ReadByDto> ReadBy,
|
||||||
List<MessageReactionDto> Reactions
|
List<MessageReactionDto> Reactions,
|
||||||
|
string? CallType = null,
|
||||||
|
string? CallStatus = null,
|
||||||
|
int? Duration = null,
|
||||||
|
List<PollOptionDto>? PollOptions = null,
|
||||||
|
bool? PollIsMultipleChoice = null,
|
||||||
|
bool? PollIsAnonymous = null,
|
||||||
|
bool? PollIsClosed = null,
|
||||||
|
List<Guid>? UserVotedOptionIds = null
|
||||||
);
|
);
|
||||||
|
|
||||||
public record ReplyToMessageDto(
|
public record ReplyToMessageDto(
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
using Knot.Shared.Kernel;
|
||||||
|
using Knot.Contracts.Messaging.Domain;
|
||||||
|
using Knot.Modules.Conversations.Application.DTOs;
|
||||||
|
|
||||||
|
namespace Knot.Modules.Conversations.Application.DTOs;
|
||||||
|
|
||||||
|
public static class MessageMapper
|
||||||
|
{
|
||||||
|
public static ChatMessageDto MapToDto(
|
||||||
|
Message message,
|
||||||
|
IReadOnlyDictionary<Guid, UserInfo> usersInfo,
|
||||||
|
IEnumerable<MessageReaction> reactions,
|
||||||
|
IEnumerable<Guid> readByUsers,
|
||||||
|
Guid? currentUserId = null)
|
||||||
|
{
|
||||||
|
usersInfo.TryGetValue(message.SenderId, out var senderObj);
|
||||||
|
|
||||||
|
var reactionsWithUser = new List<ReactionDto>();
|
||||||
|
foreach (var reaction in reactions)
|
||||||
|
{
|
||||||
|
usersInfo.TryGetValue(reaction.UserId, out var reactionUser);
|
||||||
|
reactionsWithUser.Add(new ReactionDto(
|
||||||
|
reaction.Id,
|
||||||
|
reaction.Emoji,
|
||||||
|
reaction.UserId,
|
||||||
|
reactionUser != null
|
||||||
|
? new MessageSenderDto(reactionUser.Id, reactionUser.Username, reactionUser.DisplayName, reactionUser.Avatar)
|
||||||
|
: new MessageSenderDto(reaction.UserId, "unknown", "Unknown", null)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
var textMessage = message as TextMessage;
|
||||||
|
var mediaMessage = message as MediaMessage;
|
||||||
|
var storyMessage = message as StoryMessage;
|
||||||
|
var callMessage = message as CallMessage;
|
||||||
|
|
||||||
|
return new ChatMessageDto(
|
||||||
|
message.Id,
|
||||||
|
message.ChatId,
|
||||||
|
message.SenderId,
|
||||||
|
message.Content,
|
||||||
|
message.Type,
|
||||||
|
message.ReplyToId,
|
||||||
|
textMessage?.Quote,
|
||||||
|
storyMessage?.StoryId,
|
||||||
|
storyMessage?.StoryMediaUrl,
|
||||||
|
storyMessage?.StoryMediaType,
|
||||||
|
message.IsEdited,
|
||||||
|
message.IsDeleted,
|
||||||
|
message.CreatedAt,
|
||||||
|
message.SequenceId,
|
||||||
|
mediaMessage?.Media.Select(media => new MediaDto(media.Id, media.Type, media.Url, media.Filename, media.Size, media.Duration)).ToList() ?? new List<MediaDto>(),
|
||||||
|
senderObj != null ? new MessageSenderDto(
|
||||||
|
senderObj.Id,
|
||||||
|
senderObj.Username,
|
||||||
|
senderObj.DisplayName,
|
||||||
|
senderObj.Avatar
|
||||||
|
) : new MessageSenderDto(message.SenderId, "unknown", "Unknown", null),
|
||||||
|
reactionsWithUser,
|
||||||
|
readByUsers.Select(id => new ReadByDto(id)).ToList(),
|
||||||
|
callMessage?.CallType,
|
||||||
|
callMessage?.CallStatus,
|
||||||
|
callMessage?.Duration,
|
||||||
|
message is PollMessage pm ? pm.Options.Select(o => {
|
||||||
|
var voters = pm.IsAnonymous == false
|
||||||
|
? pm.Votes
|
||||||
|
.Where(v => v.OptionId == o.Id)
|
||||||
|
.Select(v => {
|
||||||
|
usersInfo.TryGetValue(v.UserId, out var vu);
|
||||||
|
return vu != null
|
||||||
|
? new MessageSenderDto(vu.Id, vu.Username, vu.DisplayName, vu.Avatar)
|
||||||
|
: new MessageSenderDto(v.UserId, "unknown", "Unknown", null);
|
||||||
|
})
|
||||||
|
.ToList()
|
||||||
|
: null;
|
||||||
|
return new PollOptionDto(o.Id, o.Text, o.VoteCount, voters, pm.IsAnonymous == false ? pm.Votes.Where(v => v.OptionId == o.Id).Select(v => v.UserId).ToList() : null);
|
||||||
|
}).ToList() : null,
|
||||||
|
(message as PollMessage)?.IsMultipleChoice,
|
||||||
|
(message as PollMessage)?.IsAnonymous,
|
||||||
|
(message as PollMessage)?.IsClosed,
|
||||||
|
(message is PollMessage poll && currentUserId.HasValue) ? poll.Votes.Where(v => v.UserId == currentUserId.Value).Select(v => v.OptionId).ToList() : null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace Knot.Modules.Conversations.Application.DTOs;
|
||||||
|
|
||||||
|
public record PinnedMessageDto(
|
||||||
|
Guid Id,
|
||||||
|
ChatMessageDto Message
|
||||||
|
);
|
||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using Knot.Contracts.Settings.Application.Abstractions;
|
using Knot.Contracts.Settings.Application.Abstractions;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
|
|||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
using global::Knot.Modules.Conversations.Application.Abstractions;
|
using global::Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using global::Knot.Modules.Conversations.Domain;
|
using global::Knot.Contracts.Conversations.Domain;
|
||||||
using global::Knot.Modules.Conversations.Infrastructure.SignalR;
|
using global::Knot.Modules.Conversations.Infrastructure.SignalR;
|
||||||
using global::Knot.Shared.Kernel;
|
using global::Knot.Shared.Kernel;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
|
using Knot.Contracts.Messaging.Domain;
|
||||||
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
|
using Knot.Contracts.Conversations.Domain;
|
||||||
|
using Knot.Modules.Conversations.Infrastructure.SignalR;
|
||||||
|
using Knot.Shared.Kernel;
|
||||||
|
using MediatR;
|
||||||
|
using Microsoft.AspNetCore.SignalR;
|
||||||
|
|
||||||
|
namespace Knot.Modules.Conversations.Application.Messages.Edit;
|
||||||
|
|
||||||
|
public sealed record EditMessageCommand(
|
||||||
|
Guid MessageId,
|
||||||
|
Guid ChatId,
|
||||||
|
Guid UserId,
|
||||||
|
string Content) : ICommand;
|
||||||
|
|
||||||
|
public sealed class EditMessageCommandHandler : ICommandHandler<EditMessageCommand>
|
||||||
|
{
|
||||||
|
private readonly IMessageRepository _messageRepository;
|
||||||
|
private readonly IChatsUnitOfWork _unitOfWork;
|
||||||
|
private readonly IHubContext<ChatHub> _hubContext;
|
||||||
|
|
||||||
|
public EditMessageCommandHandler(
|
||||||
|
IMessageRepository messageRepository,
|
||||||
|
IChatsUnitOfWork unitOfWork,
|
||||||
|
IHubContext<ChatHub> hubContext)
|
||||||
|
{
|
||||||
|
_messageRepository = messageRepository;
|
||||||
|
_unitOfWork = unitOfWork;
|
||||||
|
_hubContext = hubContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Result> Handle(EditMessageCommand request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var message = await _messageRepository.GetByIdAsync(request.MessageId, cancellationToken);
|
||||||
|
|
||||||
|
if (message is null)
|
||||||
|
{
|
||||||
|
return Result.Failure(new Error("Message.NotFound", "Message not found."));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message.SenderId != request.UserId)
|
||||||
|
{
|
||||||
|
return Result.Failure(new Error("Message.Forbidden", "You can only edit your own messages."));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message.ChatId != request.ChatId)
|
||||||
|
{
|
||||||
|
return Result.Failure(new Error("Message.InvalidChat", "Message does not belong to this chat."));
|
||||||
|
}
|
||||||
|
|
||||||
|
message.Edit(request.Content);
|
||||||
|
|
||||||
|
await _messageRepository.UpdateAsync(message, cancellationToken);
|
||||||
|
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
|
// Notify clients
|
||||||
|
await _hubContext.Clients.Group(request.ChatId.ToString()).SendAsync("message_edited", new
|
||||||
|
{
|
||||||
|
messageId = message.Id,
|
||||||
|
chatId = message.ChatId,
|
||||||
|
content = message.Content,
|
||||||
|
isEdited = true
|
||||||
|
});
|
||||||
|
|
||||||
|
return Result.Success();
|
||||||
|
}
|
||||||
|
}
|
||||||
+84
-46
@@ -5,15 +5,15 @@ using System.Threading;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
using Knot.Contracts.Messaging.Domain;
|
using Knot.Contracts.Messaging.Domain;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using Knot.Modules.Conversations.Application.DTOs;
|
using Knot.Modules.Conversations.Application.DTOs;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Application.Messages.GetMessages;
|
namespace Knot.Modules.Conversations.Application.Messages.GetMessages;
|
||||||
|
|
||||||
public record GetMessagesQuery(Guid UserId, Guid ChatId, string? Cursor) : IQuery<List<MessageDetailDto>>;
|
public record GetMessagesQuery(Guid UserId, Guid ChatId, string? Cursor, long? Pivot = null, int? Limit = null) : IQuery<List<MessageDetailDto>>;
|
||||||
|
|
||||||
internal sealed class GetMessagesQueryHandler : IQueryHandler<GetMessagesQuery, List<MessageDetailDto>>
|
internal sealed class GetMessagesQueryHandler : IQueryHandler<GetMessagesQuery, List<MessageDetailDto>>
|
||||||
{
|
{
|
||||||
@@ -38,15 +38,34 @@ internal sealed class GetMessagesQueryHandler : IQueryHandler<GetMessagesQuery,
|
|||||||
return Result.Failure<List<MessageDetailDto>>(ChatErrors.ChatsForbidden);
|
return Result.Failure<List<MessageDetailDto>>(ChatErrors.ChatsForbidden);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
List<Message> messages;
|
||||||
|
int queryLimit = request.Limit ?? ChatConstants.DefaultMessageQueryLimit;
|
||||||
|
|
||||||
|
if (request.Pivot.HasValue)
|
||||||
|
{
|
||||||
|
messages = await _messageRepository.GetChatMessagesAroundAsync(request.ChatId, request.Pivot.Value, queryLimit, cancellationToken);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
DateTime? cursorDate = null;
|
DateTime? cursorDate = null;
|
||||||
if (!string.IsNullOrEmpty(request.Cursor) && DateTime.TryParse(request.Cursor, null, System.Globalization.DateTimeStyles.RoundtripKind, out var parsed))
|
long? cursorSequenceId = null;
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(request.Cursor))
|
||||||
|
{
|
||||||
|
if (long.TryParse(request.Cursor, out var seqId))
|
||||||
|
{
|
||||||
|
cursorSequenceId = seqId;
|
||||||
|
}
|
||||||
|
else if (DateTime.TryParse(request.Cursor, null, System.Globalization.DateTimeStyles.RoundtripKind, out var parsed))
|
||||||
{
|
{
|
||||||
cursorDate = parsed.ToUniversalTime();
|
cursorDate = parsed.ToUniversalTime();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
messages = await _messageRepository.GetChatMessagesCursorAsync(request.ChatId, cursorDate, cursorSequenceId, queryLimit, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
var messages = await _messageRepository.GetChatMessagesCursorAsync(request.ChatId, cursorDate, ChatConstants.DefaultMessageQueryLimit, cancellationToken);
|
|
||||||
var result = new List<MessageDetailDto>();
|
var result = new List<MessageDetailDto>();
|
||||||
|
|
||||||
var userIdsToFetch = new HashSet<Guid>();
|
var userIdsToFetch = new HashSet<Guid>();
|
||||||
var replyMessages = new Dictionary<Guid, Message>();
|
var replyMessages = new Dictionary<Guid, Message>();
|
||||||
|
|
||||||
@@ -57,6 +76,14 @@ internal sealed class GetMessagesQueryHandler : IQueryHandler<GetMessagesQuery,
|
|||||||
{
|
{
|
||||||
userIdsToFetch.Add(m.SenderId);
|
userIdsToFetch.Add(m.SenderId);
|
||||||
|
|
||||||
|
if (m is PollMessage poll && !poll.IsAnonymous)
|
||||||
|
{
|
||||||
|
foreach (var vote in poll.Votes)
|
||||||
|
{
|
||||||
|
userIdsToFetch.Add(vote.UserId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!m.ReplyToId.HasValue)
|
if (!m.ReplyToId.HasValue)
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
@@ -85,36 +112,19 @@ internal sealed class GetMessagesQueryHandler : IQueryHandler<GetMessagesQuery,
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
ReplyToMessageDto? replyToObj = null;
|
senders.TryGetValue(message.SenderId, out var sender);
|
||||||
if (message.ReplyToId.HasValue && replyMessages.TryGetValue(message.ReplyToId.Value, out var replyMsg))
|
reactionsByMessage.TryGetValue(message.Id, out var reactions);
|
||||||
{
|
|
||||||
var senderObj = senders.TryGetValue(replyMsg.SenderId, out var rs)
|
|
||||||
? new MessageSenderDto(rs.Id, rs.Username, rs.DisplayName, rs.Avatar)
|
|
||||||
: null;
|
|
||||||
|
|
||||||
replyToObj = new ReplyToMessageDto(
|
Message? replyMsg = null;
|
||||||
replyMsg.Id,
|
if (message.ReplyToId.HasValue)
|
||||||
replyMsg.Content,
|
{
|
||||||
replyMsg.IsDeleted,
|
replyMessages.TryGetValue(message.ReplyToId.Value, out replyMsg);
|
||||||
replyMsg.Media.Select(rm => new MediaDto(rm.Id, rm.Type, rm.Url, rm.Filename, rm.Size)).ToList(),
|
|
||||||
senderObj
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var reactionsWithUser = new List<MessageReactionDto>();
|
UserInfo? replySender = null;
|
||||||
var messageReactions = reactionsByMessage.TryGetValue(message.Id, out var mr) ? mr : new List<MessageReaction>();
|
if (replyMsg != null)
|
||||||
foreach (var reaction in messageReactions)
|
|
||||||
{
|
{
|
||||||
var userObj = senders.TryGetValue(reaction.UserId, out var reactionUser)
|
senders.TryGetValue(replyMsg.SenderId, out replySender);
|
||||||
? new MessageSenderDto(reactionUser.Id, reactionUser.Username, reactionUser.DisplayName, reactionUser.Avatar)
|
|
||||||
: new MessageSenderDto(reaction.UserId, "unknown", "Unknown", null);
|
|
||||||
|
|
||||||
reactionsWithUser.Add(new MessageReactionDto(
|
|
||||||
reaction.Id,
|
|
||||||
reaction.Emoji,
|
|
||||||
reaction.UserId,
|
|
||||||
userObj
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
result.Add(new MessageDetailDto(
|
result.Add(new MessageDetailDto(
|
||||||
@@ -122,29 +132,57 @@ internal sealed class GetMessagesQueryHandler : IQueryHandler<GetMessagesQuery,
|
|||||||
message.ChatId,
|
message.ChatId,
|
||||||
message.SenderId,
|
message.SenderId,
|
||||||
message.Content,
|
message.Content,
|
||||||
message.Type,
|
message.Type.ToLower(),
|
||||||
message.ReplyToId,
|
message.ReplyToId,
|
||||||
replyToObj,
|
replyMsg != null ? new ReplyToMessageDto(
|
||||||
message.Quote,
|
replyMsg.Id,
|
||||||
|
replyMsg.Content,
|
||||||
|
replyMsg.IsDeleted,
|
||||||
|
replyMsg is MediaMessage mm ? mm.Media.Select(m => new MediaDto(m.Id, m.Type, m.Url, m.Filename, m.Size, m.Duration)).ToList() : new List<MediaDto>(),
|
||||||
|
replySender != null ? new MessageSenderDto(replySender.Id, replySender.Username, replySender.DisplayName, replySender.Avatar) : null
|
||||||
|
) : null,
|
||||||
|
message is TextMessage tm ? tm.Quote : null,
|
||||||
message.IsEdited,
|
message.IsEdited,
|
||||||
message.IsDeleted,
|
message.IsDeleted,
|
||||||
message.CreatedAt,
|
message.CreatedAt,
|
||||||
message.SequenceId,
|
message.SequenceId,
|
||||||
message.ForwardedFromId,
|
message.ForwardedFromId,
|
||||||
message.ForwardedFromId.HasValue && senders.TryGetValue(message.ForwardedFromId.Value, out var fwdUser) ? new MessageSenderDto(fwdUser.Id, fwdUser.Username, fwdUser.DisplayName, fwdUser.Avatar) : null,
|
null, // ForwardedFrom details not implemented here yet
|
||||||
message.StoryId,
|
(message as StoryMessage)?.StoryId,
|
||||||
message.StoryMediaUrl,
|
(message as StoryMessage)?.StoryMediaUrl,
|
||||||
message.StoryMediaType,
|
(message as StoryMessage)?.StoryMediaType,
|
||||||
message.Media.Select(media => new MediaDto(media.Id, media.Type, media.Url, media.Filename, media.Size)).ToList(),
|
(message as MediaMessage)?.Media.Select(m => new MediaDto(m.Id, m.Type, m.Url, m.Filename, m.Size, m.Duration)).ToList() ?? new List<MediaDto>(),
|
||||||
senders.TryGetValue(message.SenderId, out var senderUser) ? new MessageSenderDto(senderUser.Id, senderUser.Username, senderUser.DisplayName, senderUser.Avatar) : null,
|
sender != null ? new MessageSenderDto(sender.Id, sender.Username, sender.DisplayName, sender.Avatar) : new MessageSenderDto(message.SenderId, "unknown", "Unknown", null),
|
||||||
chat.Members.Where(m => m.LastReadSequenceId >= message.SequenceId && m.UserId != message.SenderId).Select(m => new ReadByDto(m.UserId)).ToList(),
|
new List<ReadByDto>(), // ReadBy not implemented in this detailed view yet
|
||||||
reactionsWithUser
|
reactions?.Select(r => {
|
||||||
|
senders.TryGetValue(r.UserId, out var ru);
|
||||||
|
return new MessageReactionDto(r.Id, r.Emoji, r.UserId, ru != null ? new MessageSenderDto(ru.Id, ru.Username, ru.DisplayName, ru.Avatar) : null);
|
||||||
|
}).ToList() ?? new List<MessageReactionDto>(),
|
||||||
|
(message as CallMessage)?.CallType,
|
||||||
|
(message as CallMessage)?.CallStatus,
|
||||||
|
(message as CallMessage)?.Duration,
|
||||||
|
(message as PollMessage)?.Options.Select(o => {
|
||||||
|
var pm = (PollMessage)message;
|
||||||
|
var voters = pm.IsAnonymous == false
|
||||||
|
? pm.Votes
|
||||||
|
.Where(v => v.OptionId == o.Id)
|
||||||
|
.Select(v => {
|
||||||
|
senders.TryGetValue(v.UserId, out var vu);
|
||||||
|
return vu != null
|
||||||
|
? new MessageSenderDto(vu.Id, vu.Username, vu.DisplayName, vu.Avatar)
|
||||||
|
: new MessageSenderDto(v.UserId, "unknown", "Unknown", null);
|
||||||
|
})
|
||||||
|
.ToList()
|
||||||
|
: null;
|
||||||
|
return new PollOptionDto(o.Id, o.Text, o.VoteCount, voters, pm.IsAnonymous == false ? pm.Votes.Where(v => v.OptionId == o.Id).Select(v => v.UserId).ToList() : null);
|
||||||
|
}).ToList(),
|
||||||
|
(message as PollMessage)?.IsMultipleChoice,
|
||||||
|
(message as PollMessage)?.IsAnonymous,
|
||||||
|
(message as PollMessage)?.IsClosed,
|
||||||
|
(message as PollMessage)?.Votes.Where(v => v.UserId == request.UserId).Select(v => v.OptionId).ToList()
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
return Result.Success(result);
|
return Result.Success(result);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+27
-25
@@ -6,9 +6,9 @@ using System.Threading;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
using Knot.Contracts.Messaging.Domain;
|
using Knot.Contracts.Messaging.Domain;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using Knot.Modules.Conversations.Application.DTOs;
|
using Knot.Modules.Conversations.Application.DTOs;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
|
|
||||||
@@ -48,13 +48,20 @@ internal sealed class GetSharedMediaQueryHandler : IQueryHandler<GetSharedMediaQ
|
|||||||
|
|
||||||
foreach (var message in messages)
|
foreach (var message in messages)
|
||||||
{
|
{
|
||||||
|
var mediaMessage = message as MediaMessage;
|
||||||
|
var textMessage = message as TextMessage;
|
||||||
|
var storyMessage = message as StoryMessage;
|
||||||
|
|
||||||
if (filterType == "links")
|
if (filterType == "links")
|
||||||
{
|
{
|
||||||
var messageContent = message.Content;
|
var messageContent = message.Content;
|
||||||
var linkRegex = new Regex(@"https?://[^\s]+", RegexOptions.IgnoreCase);
|
var linkRegex = new Regex(@"https?://[^\s]+", RegexOptions.IgnoreCase);
|
||||||
var contentLinks = !string.IsNullOrEmpty(messageContent) ? linkRegex.Matches(messageContent).Select(match => match.Value).ToList() : new List<string>();
|
var contentLinks = !string.IsNullOrEmpty(messageContent) ? linkRegex.Matches(messageContent).Select(match => match.Value).ToList() : new List<string>();
|
||||||
var messageMediaColl = message.Media;
|
|
||||||
var mediaLinks = (messageMediaColl ?? Enumerable.Empty<Media>()).Where(media => media.Type?.ToString().ToLower() == "link").Select(media => media.Url).ToList();
|
var mediaLinks = (mediaMessage?.Media ?? Enumerable.Empty<Media>())
|
||||||
|
.Where(media => media.Type?.ToString().ToLower() == "link" && !string.IsNullOrEmpty(media.Url))
|
||||||
|
.Select(media => media.Url!)
|
||||||
|
.ToList();
|
||||||
var allLinks = contentLinks.Concat(mediaLinks).Distinct().ToList();
|
var allLinks = contentLinks.Concat(mediaLinks).Distinct().ToList();
|
||||||
|
|
||||||
if (allLinks.Any())
|
if (allLinks.Any())
|
||||||
@@ -72,7 +79,7 @@ internal sealed class GetSharedMediaQueryHandler : IQueryHandler<GetSharedMediaQ
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
var messageMedia = message.Media;
|
var messageMedia = mediaMessage?.Media;
|
||||||
if (messageMedia == null || !messageMedia.Any())
|
if (messageMedia == null || !messageMedia.Any())
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
@@ -80,23 +87,18 @@ internal sealed class GetSharedMediaQueryHandler : IQueryHandler<GetSharedMediaQ
|
|||||||
|
|
||||||
var filteredMedia = messageMedia.Where(media =>
|
var filteredMedia = messageMedia.Where(media =>
|
||||||
{
|
{
|
||||||
var mediaType = media.Type?.ToLower() ?? "file";
|
var mType = media.Type?.ToLower() ?? "file";
|
||||||
var isGif = mediaType == "image" && (media.Url.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase) || media.Url.EndsWith(".gif", StringComparison.OrdinalIgnoreCase));
|
var filename = media.Filename?.ToLower() ?? "";
|
||||||
|
var url = media.Url?.ToLower() ?? "";
|
||||||
|
|
||||||
if (filterType == "gifs")
|
var isGif = mType == "gif" ||
|
||||||
{
|
(mType == "image" && (filename.EndsWith(".mp4") || filename.EndsWith(".gif") || url.EndsWith(".gif") || filename.Contains("gif"))) ||
|
||||||
return isGif;
|
(mType == "video" && (filename.Contains("animation") || filename.Contains("gif")));
|
||||||
}
|
|
||||||
|
|
||||||
if (filterType == "files")
|
if (filterType == "gifs") return isGif;
|
||||||
{
|
if (filterType == "media") return (mType == "image" || mType == "video") && !isGif;
|
||||||
return mediaType != "image" && mediaType != "video" && mediaType != "link";
|
if (filterType == "files") return (mType == "file" || mType == "audio") && !isGif && mType != "image" && mType != "video";
|
||||||
}
|
if (filterType == "links") return mType == "link";
|
||||||
|
|
||||||
if (filterType == "media")
|
|
||||||
{
|
|
||||||
return (mediaType == "image" || mediaType == "video") && !isGif;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}).ToList();
|
}).ToList();
|
||||||
@@ -111,13 +113,13 @@ internal sealed class GetSharedMediaQueryHandler : IQueryHandler<GetSharedMediaQ
|
|||||||
null,
|
null,
|
||||||
sender != null ? new MessageSenderDto(sender.Id, sender.Username, sender.DisplayName, sender.Avatar) : null,
|
sender != null ? new MessageSenderDto(sender.Id, sender.Username, sender.DisplayName, sender.Avatar) : null,
|
||||||
message.ReplyToId,
|
message.ReplyToId,
|
||||||
message.Quote,
|
textMessage?.Quote,
|
||||||
message.StoryId,
|
storyMessage?.StoryId,
|
||||||
message.StoryMediaUrl,
|
storyMessage?.StoryMediaUrl,
|
||||||
message.StoryMediaType,
|
storyMessage?.StoryMediaType,
|
||||||
message.IsEdited,
|
message.IsEdited,
|
||||||
message.Type,
|
message.Type,
|
||||||
filteredMedia.Select(media => new MediaDto(media.Id, media.Type, media.Url, media.Filename, media.Size)).ToList()
|
filteredMedia.Select(media => new MediaDto(media.Id, media.Type, media.Url, media.Filename, media.Size, media.Duration)).ToList()
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+58
@@ -0,0 +1,58 @@
|
|||||||
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
|
using Knot.Contracts.Messaging.Domain;
|
||||||
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
|
using Knot.Contracts.Conversations.Domain;
|
||||||
|
using Knot.Shared.Kernel;
|
||||||
|
using MediatR;
|
||||||
|
|
||||||
|
namespace Knot.Modules.Conversations.Application.Messages.Pin;
|
||||||
|
|
||||||
|
public sealed record PinMessageCommand(Guid MessageId, Guid ChatId, Guid UserId) : ICommand<Guid>;
|
||||||
|
|
||||||
|
public sealed class PinMessageCommandHandler : ICommandHandler<PinMessageCommand, Guid>
|
||||||
|
{
|
||||||
|
private readonly IMessageRepository _messageRepository;
|
||||||
|
private readonly IChatRepository _chatRepository;
|
||||||
|
private readonly IChatsUnitOfWork _unitOfWork;
|
||||||
|
private readonly IMediator _mediator;
|
||||||
|
|
||||||
|
public PinMessageCommandHandler(
|
||||||
|
IMessageRepository messageRepository,
|
||||||
|
IChatRepository chatRepository,
|
||||||
|
IChatsUnitOfWork unitOfWork,
|
||||||
|
IMediator mediator)
|
||||||
|
{
|
||||||
|
_messageRepository = messageRepository;
|
||||||
|
_chatRepository = chatRepository;
|
||||||
|
_unitOfWork = unitOfWork;
|
||||||
|
_mediator = mediator;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Result<Guid>> Handle(PinMessageCommand request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var chat = await _chatRepository.GetByIdAsync(request.ChatId, cancellationToken);
|
||||||
|
if (chat is null) return Result.Failure<Guid>(ChatErrors.ChatsNotFound);
|
||||||
|
|
||||||
|
// Security check
|
||||||
|
if (!chat.Members.Any(m => m.UserId == request.UserId))
|
||||||
|
return Result.Failure<Guid>(ChatErrors.ChatsForbidden);
|
||||||
|
|
||||||
|
var message = await _messageRepository.GetByIdAsync(request.MessageId, cancellationToken);
|
||||||
|
if (message is null) return Result.Failure<Guid>(ChatErrors.NotFound);
|
||||||
|
|
||||||
|
if (message.ChatId != request.ChatId)
|
||||||
|
return Result.Failure<Guid>(ChatErrors.NotFound);
|
||||||
|
|
||||||
|
message.AddState(MessageState.IsPinned);
|
||||||
|
|
||||||
|
await _messageRepository.UpdateAsync(message, cancellationToken);
|
||||||
|
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
|
// Notify chat about pinned message change
|
||||||
|
await _mediator.Publish(new MessagePinnedDomainEvent(message.Id, message.ChatId, message.SenderId, message.Content), cancellationToken);
|
||||||
|
|
||||||
|
return Result.Success(message.Id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public record MessagePinnedDomainEvent(Guid MessageId, Guid ChatId, Guid SenderId, string? Content) : INotification;
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
using Knot.Contracts.Messaging.Domain;
|
using Knot.Contracts.Messaging.Domain;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Modules.Conversations.Infrastructure.SignalR;
|
using Knot.Modules.Conversations.Infrastructure.SignalR;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
|
|||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
using Knot.Contracts.Messaging.Domain;
|
using Knot.Contracts.Messaging.Domain;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Modules.Conversations.Infrastructure.SignalR;
|
using Knot.Modules.Conversations.Infrastructure.SignalR;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
|
|||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
using MediatR;
|
using MediatR;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Application.Messages.Read;
|
namespace Knot.Modules.Conversations.Application.Messages.Read;
|
||||||
|
|
||||||
|
|||||||
+14
-8
@@ -6,7 +6,7 @@ using System.Threading.Tasks;
|
|||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
using Knot.Contracts.Messaging.Domain;
|
using Knot.Contracts.Messaging.Domain;
|
||||||
using Knot.Modules.Conversations.Application.DTOs;
|
using Knot.Modules.Conversations.Application.DTOs;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
|
|
||||||
@@ -41,28 +41,34 @@ internal sealed class SearchMessagesQueryHandler : IQueryHandler<SearchMessagesQ
|
|||||||
var allReactions = await _reactionRepository.GetReactionsForMessagesAsync(messageIds, cancellationToken);
|
var allReactions = await _reactionRepository.GetReactionsForMessagesAsync(messageIds, cancellationToken);
|
||||||
var reactionsByMessage = allReactions.GroupBy(r => r.MessageId).ToDictionary(g => g.Key, g => g.ToList());
|
var reactionsByMessage = allReactions.GroupBy(r => r.MessageId).ToDictionary(g => g.Key, g => g.ToList());
|
||||||
|
|
||||||
var result = messages.Select(message => new SearchMessageDto(
|
var result = messages.Select(message => {
|
||||||
|
var textMessage = message as TextMessage;
|
||||||
|
var mediaMessage = message as MediaMessage;
|
||||||
|
var storyMessage = message as StoryMessage;
|
||||||
|
|
||||||
|
return new SearchMessageDto(
|
||||||
message.Id,
|
message.Id,
|
||||||
message.ChatId,
|
message.ChatId,
|
||||||
message.SenderId,
|
message.SenderId,
|
||||||
message.Content,
|
message.Content,
|
||||||
message.Type,
|
message.Type,
|
||||||
message.ReplyToId,
|
message.ReplyToId,
|
||||||
message.Quote,
|
textMessage?.Quote,
|
||||||
message.IsEdited,
|
message.IsEdited,
|
||||||
message.IsDeleted,
|
message.IsDeleted,
|
||||||
message.CreatedAt,
|
message.CreatedAt,
|
||||||
message.SequenceId,
|
message.SequenceId,
|
||||||
message.ForwardedFromId,
|
message.ForwardedFromId,
|
||||||
null,
|
null,
|
||||||
message.StoryId,
|
storyMessage?.StoryId,
|
||||||
message.StoryMediaUrl,
|
storyMessage?.StoryMediaUrl,
|
||||||
message.StoryMediaType,
|
storyMessage?.StoryMediaType,
|
||||||
message.Media.Select(media => new MediaDto(media.Id, media.Type, media.Url, media.Filename, media.Size)).ToList(),
|
mediaMessage?.Media.Select(media => new MediaDto(media.Id, media.Type, media.Url, media.Filename, media.Size)).ToList() ?? new List<MediaDto>(),
|
||||||
senders.TryGetValue(message.SenderId, out var senderUser) ? new MessageSenderDto(senderUser.Id, senderUser.Username, senderUser.DisplayName, senderUser.Avatar) : new MessageSenderDto(message.SenderId, "unknown", "Unknown", null),
|
senders.TryGetValue(message.SenderId, out var senderUser) ? new MessageSenderDto(senderUser.Id, senderUser.Username, senderUser.DisplayName, senderUser.Avatar) : new MessageSenderDto(message.SenderId, "unknown", "Unknown", null),
|
||||||
reactionsByMessage.TryGetValue(message.Id, out var mr) ? mr.Select(reaction => new SimpleReactionDto(reaction.UserId, reaction.Emoji)).ToList() : new List<SimpleReactionDto>(),
|
reactionsByMessage.TryGetValue(message.Id, out var mr) ? mr.Select(reaction => new SimpleReactionDto(reaction.UserId, reaction.Emoji)).ToList() : new List<SimpleReactionDto>(),
|
||||||
new List<ReadByDto>()
|
new List<ReadByDto>()
|
||||||
)).ToList();
|
);
|
||||||
|
}).ToList();
|
||||||
|
|
||||||
return Result.Success(result);
|
return Result.Success(result);
|
||||||
}
|
}
|
||||||
|
|||||||
+20
-4
@@ -1,8 +1,8 @@
|
|||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
using Knot.Contracts.Messaging.Domain;
|
using Knot.Contracts.Messaging.Domain;
|
||||||
using Knot.Contracts.Settings.Application.Abstractions;
|
using Knot.Contracts.Settings.Application.Abstractions;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Application.Messages.Send;
|
namespace Knot.Modules.Conversations.Application.Messages.Send;
|
||||||
@@ -27,7 +27,10 @@ public sealed record SendMessageCommand(
|
|||||||
List<string>? PollOptions = null,
|
List<string>? PollOptions = null,
|
||||||
bool? PollIsAnonymous = null,
|
bool? PollIsAnonymous = null,
|
||||||
bool? PollAllowMultipleAnswers = null,
|
bool? PollAllowMultipleAnswers = null,
|
||||||
DateTime? PollExpiresAt = null) : ICommand<Guid>;
|
DateTime? PollExpiresAt = null,
|
||||||
|
string? CallType = null,
|
||||||
|
string? CallStatus = null,
|
||||||
|
int? Duration = null) : ICommand<Guid>;
|
||||||
|
|
||||||
public sealed class SendMessageCommandHandler : ICommandHandler<SendMessageCommand, Guid>
|
public sealed class SendMessageCommandHandler : ICommandHandler<SendMessageCommand, Guid>
|
||||||
{
|
{
|
||||||
@@ -132,8 +135,9 @@ public sealed class SendMessageCommandHandler : ICommandHandler<SendMessageComma
|
|||||||
else if (request.Type == "poll")
|
else if (request.Type == "poll")
|
||||||
{
|
{
|
||||||
if (!_messagesSettings.Current.AllowPolls) return Result.Failure<Guid>(ChatErrors.PollsDisabled);
|
if (!_messagesSettings.Current.AllowPolls) return Result.Failure<Guid>(ChatErrors.PollsDisabled);
|
||||||
|
if (chat.Type != ChatType.Group) return Result.Failure<Guid>(new Error("Poll.InvalidChat", "Polls are only allowed in groups."));
|
||||||
|
|
||||||
message = new PollMessage(
|
message = PollMessage.Create(
|
||||||
Guid.NewGuid(),
|
Guid.NewGuid(),
|
||||||
request.ChatId,
|
request.ChatId,
|
||||||
request.SenderId,
|
request.SenderId,
|
||||||
@@ -143,6 +147,18 @@ public sealed class SendMessageCommandHandler : ICommandHandler<SendMessageComma
|
|||||||
request.PollAllowMultipleAnswers ?? false,
|
request.PollAllowMultipleAnswers ?? false,
|
||||||
request.PollExpiresAt,
|
request.PollExpiresAt,
|
||||||
request.ReplyToId,
|
request.ReplyToId,
|
||||||
|
request.ForwardedFromId);
|
||||||
|
}
|
||||||
|
else if (request.Type == "call")
|
||||||
|
{
|
||||||
|
message = new CallMessage(
|
||||||
|
Guid.NewGuid(),
|
||||||
|
request.ChatId,
|
||||||
|
request.SenderId,
|
||||||
|
request.CallType ?? "voice",
|
||||||
|
request.CallStatus ?? "completed",
|
||||||
|
request.Duration,
|
||||||
|
request.ReplyToId,
|
||||||
request.ForwardedFromId,
|
request.ForwardedFromId,
|
||||||
DateTime.UtcNow,
|
DateTime.UtcNow,
|
||||||
false);
|
false);
|
||||||
|
|||||||
+58
@@ -0,0 +1,58 @@
|
|||||||
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
|
using Knot.Contracts.Messaging.Domain;
|
||||||
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
|
using Knot.Contracts.Conversations.Domain;
|
||||||
|
using Knot.Shared.Kernel;
|
||||||
|
using MediatR;
|
||||||
|
|
||||||
|
namespace Knot.Modules.Conversations.Application.Messages.Unpin;
|
||||||
|
|
||||||
|
public sealed record UnpinMessageCommand(Guid MessageId, Guid ChatId, Guid UserId) : ICommand<Guid>;
|
||||||
|
|
||||||
|
public sealed class UnpinMessageCommandHandler : ICommandHandler<UnpinMessageCommand, Guid>
|
||||||
|
{
|
||||||
|
private readonly IMessageRepository _messageRepository;
|
||||||
|
private readonly IChatRepository _chatRepository;
|
||||||
|
private readonly IChatsUnitOfWork _unitOfWork;
|
||||||
|
private readonly IMediator _mediator;
|
||||||
|
|
||||||
|
public UnpinMessageCommandHandler(
|
||||||
|
IMessageRepository messageRepository,
|
||||||
|
IChatRepository chatRepository,
|
||||||
|
IChatsUnitOfWork unitOfWork,
|
||||||
|
IMediator mediator)
|
||||||
|
{
|
||||||
|
_messageRepository = messageRepository;
|
||||||
|
_chatRepository = chatRepository;
|
||||||
|
_unitOfWork = unitOfWork;
|
||||||
|
_mediator = mediator;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Result<Guid>> Handle(UnpinMessageCommand request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var chat = await _chatRepository.GetByIdAsync(request.ChatId, cancellationToken);
|
||||||
|
if (chat is null) return Result.Failure<Guid>(ChatErrors.ChatsNotFound);
|
||||||
|
|
||||||
|
// Security check
|
||||||
|
if (!chat.Members.Any(m => m.UserId == request.UserId))
|
||||||
|
return Result.Failure<Guid>(ChatErrors.ChatsForbidden);
|
||||||
|
|
||||||
|
var message = await _messageRepository.GetByIdAsync(request.MessageId, cancellationToken);
|
||||||
|
if (message is null) return Result.Failure<Guid>(ChatErrors.NotFound);
|
||||||
|
|
||||||
|
if (message.ChatId != request.ChatId)
|
||||||
|
return Result.Failure<Guid>(ChatErrors.NotFound);
|
||||||
|
|
||||||
|
message.RemoveState(MessageState.IsPinned);
|
||||||
|
|
||||||
|
await _messageRepository.UpdateAsync(message, cancellationToken);
|
||||||
|
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
|
// Notify chat about unpinned message change
|
||||||
|
await _mediator.Publish(new MessageUnpinnedDomainEvent(message.Id, message.ChatId), cancellationToken);
|
||||||
|
|
||||||
|
return Result.Success(message.Id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public record MessageUnpinnedDomainEvent(Guid MessageId, Guid ChatId) : INotification;
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
|
using Knot.Contracts.Conversations.Domain;
|
||||||
|
using Knot.Contracts.Messaging.Domain;
|
||||||
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
|
using Knot.Shared.Kernel;
|
||||||
|
using MediatR;
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace Knot.Modules.Conversations.Application.Messages.Vote;
|
||||||
|
|
||||||
|
public sealed record VotePollCommand(
|
||||||
|
Guid MessageId,
|
||||||
|
Guid ChatId,
|
||||||
|
Guid UserId,
|
||||||
|
Guid OptionId) : ICommand;
|
||||||
|
|
||||||
|
public sealed class VotePollCommandHandler : ICommandHandler<VotePollCommand>
|
||||||
|
{
|
||||||
|
private readonly IMessageRepository _messageRepository;
|
||||||
|
private readonly IChatRepository _chatRepository;
|
||||||
|
private readonly IChatsUnitOfWork _unitOfWork;
|
||||||
|
private readonly IMessageNotifier _notifier;
|
||||||
|
private readonly IUserDisplayNameProvider _userProvider;
|
||||||
|
|
||||||
|
public VotePollCommandHandler(
|
||||||
|
IMessageRepository messageRepository,
|
||||||
|
IChatRepository chatRepository,
|
||||||
|
IChatsUnitOfWork unitOfWork,
|
||||||
|
IMessageNotifier notifier,
|
||||||
|
IUserDisplayNameProvider userProvider)
|
||||||
|
{
|
||||||
|
_messageRepository = messageRepository;
|
||||||
|
_chatRepository = chatRepository;
|
||||||
|
_unitOfWork = unitOfWork;
|
||||||
|
_notifier = notifier;
|
||||||
|
_userProvider = userProvider;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Result> Handle(VotePollCommand request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var message = await _messageRepository.GetByIdAsync(request.MessageId, cancellationToken);
|
||||||
|
if (message is not PollMessage poll) return Result.Failure(new Error("Poll.NotFound", "Poll not found"));
|
||||||
|
|
||||||
|
if (poll.IsClosed) return Result.Failure(new Error("Poll.Closed", "This poll is closed."));
|
||||||
|
|
||||||
|
var chat = await _chatRepository.GetByIdAsync(request.ChatId, cancellationToken);
|
||||||
|
if (chat == null || !chat.Members.Any(m => m.UserId == request.UserId)) return Result.Failure(ChatErrors.ChatsForbidden);
|
||||||
|
|
||||||
|
var targetOption = poll.Options.FirstOrDefault(o => o.Id == request.OptionId);
|
||||||
|
if (targetOption == null) return Result.Failure(new Error("Poll.InvalidOption", "Invalid option ID."));
|
||||||
|
|
||||||
|
// Prevent duplicate or changed votes
|
||||||
|
var existingVote = poll.Votes.FirstOrDefault(v => v.UserId == request.UserId && v.OptionId == request.OptionId);
|
||||||
|
if (existingVote != null) return Result.Failure(new Error("Poll.AlreadyVoted", "You have already voted for this option."));
|
||||||
|
|
||||||
|
if (!poll.IsMultipleChoice)
|
||||||
|
{
|
||||||
|
var hasVotedInThisPoll = poll.Votes.Any(v => v.UserId == request.UserId);
|
||||||
|
if (hasVotedInThisPoll) return Result.Failure(new Error("Poll.AlreadyVoted", "You have already voted in this poll."));
|
||||||
|
}
|
||||||
|
|
||||||
|
poll.Votes.Add(new PollVote { UserId = request.UserId, OptionId = request.OptionId, VotedAt = DateTime.UtcNow });
|
||||||
|
targetOption.VoteCount++;
|
||||||
|
|
||||||
|
await _messageRepository.UpdateAsync(poll, cancellationToken);
|
||||||
|
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
|
// Notify updated poll
|
||||||
|
var voterIds = poll.Votes.Select(v => v.UserId).Distinct().ToList();
|
||||||
|
var votersInfo = poll.IsAnonymous == false
|
||||||
|
? await _userProvider.GetUsersInfoAsync(voterIds, cancellationToken)
|
||||||
|
: new Dictionary<Guid, UserInfo>();
|
||||||
|
|
||||||
|
await _notifier.NotifyMessageUpdateAsync(poll.ChatId, "poll_updated", new
|
||||||
|
{
|
||||||
|
id = poll.Id,
|
||||||
|
chatId = poll.ChatId,
|
||||||
|
senderId = poll.SenderId,
|
||||||
|
createdAt = poll.CreatedAt,
|
||||||
|
type = "poll",
|
||||||
|
content = poll.Content,
|
||||||
|
pollOptions = poll.Options.Select(o => new {
|
||||||
|
id = o.Id,
|
||||||
|
text = o.Text,
|
||||||
|
voteCount = o.VoteCount,
|
||||||
|
voters = poll.IsAnonymous == false
|
||||||
|
? poll.Votes.Where(v => v.OptionId == o.Id)
|
||||||
|
.Select(v => {
|
||||||
|
votersInfo.TryGetValue(v.UserId, out var vu);
|
||||||
|
return vu != null
|
||||||
|
? new { id = vu.Id, username = vu.Username, displayName = vu.DisplayName, avatar = vu.Avatar }
|
||||||
|
: new { id = v.UserId, username = "unknown", displayName = "Unknown", avatar = (string?)null };
|
||||||
|
}).ToList()
|
||||||
|
: null,
|
||||||
|
voterIds = poll.IsAnonymous == false
|
||||||
|
? poll.Votes.Where(v => v.OptionId == o.Id).Select(v => v.UserId).ToList()
|
||||||
|
: null
|
||||||
|
}).ToList(),
|
||||||
|
pollIsMultipleChoice = poll.IsMultipleChoice,
|
||||||
|
pollIsClosed = poll.IsClosed,
|
||||||
|
pollIsAnonymous = poll.IsAnonymous
|
||||||
|
}, cancellationToken);
|
||||||
|
|
||||||
|
return Result.Success();
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-3
@@ -2,8 +2,8 @@ using System.Text.RegularExpressions;
|
|||||||
using Knot.Contracts.Auth.Application.Abstractions;
|
using Knot.Contracts.Auth.Application.Abstractions;
|
||||||
using Knot.Contracts.Auth.Domain;
|
using Knot.Contracts.Auth.Domain;
|
||||||
using Knot.Contracts.Messaging.Domain;
|
using Knot.Contracts.Messaging.Domain;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using Knot.Shared.Kernel.Storage;
|
using Knot.Shared.Kernel.Storage;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
@@ -54,9 +54,11 @@ internal sealed class DeleteUserCommandHandler : ICommandHandler<DeleteUserComma
|
|||||||
if (msg is MediaMessage mediaMsg)
|
if (msg is MediaMessage mediaMsg)
|
||||||
{
|
{
|
||||||
foreach (var media in mediaMsg.Media)
|
foreach (var media in mediaMsg.Media)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrEmpty(media.Url))
|
||||||
{
|
{
|
||||||
bool isUsedElsewhere = allMessages.Any(m => m.Id != msg.Id &&
|
bool isUsedElsewhere = allMessages.Any(m => m.Id != msg.Id &&
|
||||||
m is MediaMessage mm && mm.Media.Any(ame => ame.Url == media.Url));
|
m is MediaMessage mm && mm.Media.Any(ame => !string.IsNullOrEmpty(ame.Url) && ame.Url == media.Url));
|
||||||
|
|
||||||
if (!isUsedElsewhere)
|
if (!isUsedElsewhere)
|
||||||
{
|
{
|
||||||
@@ -69,6 +71,7 @@ internal sealed class DeleteUserCommandHandler : ICommandHandler<DeleteUserComma
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
await _messageRepository.DeleteUserMessagesAsync(request.UserId, cancellationToken);
|
await _messageRepository.DeleteUserMessagesAsync(request.UserId, cancellationToken);
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,14 @@
|
|||||||
using Knot.Contracts.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using Knot.Contracts.Conversations.Infrastructure.Persistence;
|
using Knot.Contracts.Conversations.Infrastructure.Persistence;
|
||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Contracts.Messaging.Domain;
|
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
|
||||||
using Knot.Modules.Conversations.Domain;
|
|
||||||
using Knot.Modules.Conversations.Infrastructure.Persistence;
|
using Knot.Modules.Conversations.Infrastructure.Persistence;
|
||||||
using Knot.Modules.Conversations.Infrastructure.Persistence.Mongo;
|
using Knot.Modules.Conversations.Infrastructure.Persistence.Mongo;
|
||||||
|
using Knot.Modules.Conversations.Infrastructure.Services;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using ConversationsAbstractions = Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations;
|
namespace Knot.Modules.Conversations;
|
||||||
|
|
||||||
@@ -29,21 +27,22 @@ public static class DependencyInjection
|
|||||||
|
|
||||||
var mongoConnectionString = configuration.GetConnectionString("MongoConnection") ?? "mongodb://localhost:27017";
|
var mongoConnectionString = configuration.GetConnectionString("MongoConnection") ?? "mongodb://localhost:27017";
|
||||||
|
|
||||||
services.AddScoped<ConversationsAbstractions.IChatsUnitOfWork>(sp => sp.GetRequiredService<ChatsDbContext>());
|
services.AddScoped<IChatsUnitOfWork>(sp => sp.GetRequiredService<ChatsDbContext>());
|
||||||
services.AddScoped<Knot.Contracts.Conversations.Infrastructure.Persistence.IChatsDbContext>(sp => sp.GetRequiredService<ChatsDbContext>());
|
services.AddScoped<Knot.Contracts.Conversations.Infrastructure.Persistence.IChatsDbContext>(sp => sp.GetRequiredService<ChatsDbContext>());
|
||||||
services.AddScoped<IChatRepository, ChatRepository>();
|
services.AddScoped<IChatRepository, ChatRepository>();
|
||||||
services.AddScoped<IFolderRepository, FolderRepository>();
|
services.AddScoped<IFolderRepository, FolderRepository>();
|
||||||
services.AddScoped<IUserChatSettingsRepository, UserChatSettingsRepository>();
|
services.AddScoped<IUserChatSettingsRepository, UserChatSettingsRepository>();
|
||||||
services.AddScoped<IUserFolderSettingsRepository, UserFolderSettingsRepository>();
|
services.AddScoped<Knot.Contracts.Conversations.Domain.IUserFolderSettingsRepository, UserFolderSettingsRepository>();
|
||||||
|
|
||||||
services.AddMediatR(config =>
|
services.AddMediatR(config =>
|
||||||
config.RegisterServicesFromAssembly(typeof(DependencyInjection).Assembly));
|
config.RegisterServicesFromAssembly(typeof(DependencyInjection).Assembly));
|
||||||
|
|
||||||
services.AddScoped<Knot.Contracts.Messaging.Application.Abstractions.IChatAccessProvider, Knot.Modules.Conversations.Infrastructure.Services.ChatAccessProvider>();
|
services.AddScoped<Knot.Contracts.Messaging.Application.Abstractions.IChatAccessProvider, ChatAccessProvider>();
|
||||||
services.AddScoped<Knot.Contracts.Messaging.Application.Abstractions.IMessageNotifier, Knot.Modules.Conversations.Infrastructure.SignalR.MessageNotifier>();
|
services.AddScoped<Knot.Contracts.Messaging.Application.Abstractions.IMessageNotifier, Knot.Modules.Conversations.Infrastructure.SignalR.MessageNotifier>();
|
||||||
services.AddScoped<ConversationsAbstractions.IUserStatusService, Knot.Modules.Conversations.Infrastructure.Services.UserStatusService>();
|
services.AddScoped<Knot.Contracts.Conversations.Application.Abstractions.IUserStatusService, UserStatusService>();
|
||||||
services.AddScoped<Knot.Contracts.Conversations.Abstractions.IUserStatusService, Knot.Modules.Conversations.Infrastructure.Services.UserStatusService>();
|
services.AddScoped<Knot.Contracts.Conversations.Abstractions.IUserStatusService, UserStatusService>();
|
||||||
services.AddScoped<Knot.Contracts.Conversations.Abstractions.IUserDeleterService, Knot.Modules.Conversations.Infrastructure.Services.UserDeleterService>();
|
services.AddScoped<Knot.Contracts.Conversations.Abstractions.IUserDeleterService, UserDeleterService>();
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,157 +0,0 @@
|
|||||||
using Knot.Shared.Kernel;
|
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Domain;
|
|
||||||
|
|
||||||
public sealed record ChatCreatedDomainEvent(Chat Chat) : IDomainEvent;
|
|
||||||
public sealed record ChatMemberAddedDomainEvent(Guid ChatId, Guid UserId) : IDomainEvent;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Тип чата: личный или групповой.
|
|
||||||
/// </summary>
|
|
||||||
public enum ChatType
|
|
||||||
{
|
|
||||||
Personal,
|
|
||||||
Group,
|
|
||||||
Favorites
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Роль участника в чате.
|
|
||||||
/// </summary>
|
|
||||||
public static class ChatRole
|
|
||||||
{
|
|
||||||
public const string Owner = "owner";
|
|
||||||
public const string Admin = "admin";
|
|
||||||
public const string Member = "member";
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Сущность чата (Агрегат).
|
|
||||||
/// </summary>
|
|
||||||
public sealed class Chat : AggregateRoot<Guid>
|
|
||||||
{
|
|
||||||
public ChatType Type { get; private set; }
|
|
||||||
public string? Name { get; private set; }
|
|
||||||
public string? Description { get; private set; }
|
|
||||||
public string? Avatar { get; private set; }
|
|
||||||
public DateTime CreatedAt { get; private set; }
|
|
||||||
public long LastMessageSequenceId { get; private set; }
|
|
||||||
|
|
||||||
private readonly List<ChatMember> _members = new();
|
|
||||||
public IReadOnlyCollection<ChatMember> Members => _members.AsReadOnly();
|
|
||||||
|
|
||||||
private Chat(Guid id, ChatType type, string? name, string? avatar, string? description = null) : base(id)
|
|
||||||
{
|
|
||||||
Type = type;
|
|
||||||
Name = name;
|
|
||||||
Avatar = avatar;
|
|
||||||
Description = description;
|
|
||||||
CreatedAt = DateTime.UtcNow;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Создает личный чат между двумя пользователями.
|
|
||||||
/// </summary>
|
|
||||||
public static Chat CreatePersonal()
|
|
||||||
{
|
|
||||||
var chat = new Chat(Guid.NewGuid(), ChatType.Personal, null, null);
|
|
||||||
chat.RaiseDomainEvent(new ChatCreatedDomainEvent(chat));
|
|
||||||
return chat;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Создает групповой чат.
|
|
||||||
/// </summary>
|
|
||||||
public static Chat CreateGroup(string name, string? avatar = null)
|
|
||||||
{
|
|
||||||
var chat = new Chat(Guid.NewGuid(), ChatType.Group, name, avatar);
|
|
||||||
chat.RaiseDomainEvent(new ChatCreatedDomainEvent(chat));
|
|
||||||
return chat;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Фабричный метод для создания чата.
|
|
||||||
/// </summary>
|
|
||||||
public static Chat Create(string? name, ChatType type, string? avatar = null, string? description = null)
|
|
||||||
{
|
|
||||||
var chat = new Chat(Guid.NewGuid(), type, name, avatar, description);
|
|
||||||
chat.RaiseDomainEvent(new ChatCreatedDomainEvent(chat));
|
|
||||||
return chat;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void AddMember(Guid userId, string role = "member")
|
|
||||||
{
|
|
||||||
if (_members.Any(m => m.UserId == userId))
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
_members.Add(new ChatMember(Id, userId, role));
|
|
||||||
RaiseDomainEvent(new ChatMemberAddedDomainEvent(Id, userId));
|
|
||||||
}
|
|
||||||
|
|
||||||
public void RemoveMember(Guid userId)
|
|
||||||
{
|
|
||||||
var member = _members.FirstOrDefault(m => m.UserId == userId);
|
|
||||||
if (member != null)
|
|
||||||
{
|
|
||||||
_members.Remove(member);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void UpdateName(string name) => Name = name;
|
|
||||||
|
|
||||||
public void UpdateDescription(string? description) => Description = description;
|
|
||||||
|
|
||||||
public void UpdateAvatar(string? avatarUrl) => Avatar = avatarUrl;
|
|
||||||
|
|
||||||
public long IncrementSequenceId()
|
|
||||||
{
|
|
||||||
return ++LastMessageSequenceId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Участник чата.
|
|
||||||
/// </summary>
|
|
||||||
public sealed class ChatMember : Entity<Guid>
|
|
||||||
{
|
|
||||||
public Guid ChatId { get; private set; }
|
|
||||||
public Guid UserId { get; private set; }
|
|
||||||
public string Role { get; private set; }
|
|
||||||
public DateTime JoinedAt { get; private set; }
|
|
||||||
public bool IsPinned { get; private set; }
|
|
||||||
public bool IsMuted { get; private set; }
|
|
||||||
|
|
||||||
public Guid? LastReadMessageId { get; private set; }
|
|
||||||
public long LastReadSequenceId { get; private set; }
|
|
||||||
public Guid? LastDeliveredMessageId { get; private set; }
|
|
||||||
|
|
||||||
// For EF Core
|
|
||||||
private ChatMember() : base(Guid.Empty) { Role = "member"; }
|
|
||||||
|
|
||||||
internal ChatMember(Guid chatId, Guid userId, string role) : base(Guid.NewGuid())
|
|
||||||
{
|
|
||||||
ChatId = chatId;
|
|
||||||
UserId = userId;
|
|
||||||
Role = role;
|
|
||||||
JoinedAt = DateTime.UtcNow;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void TogglePin() => IsPinned = !IsPinned;
|
|
||||||
|
|
||||||
public void UpdateReadCursor(Guid messageId, long sequenceId)
|
|
||||||
{
|
|
||||||
if (sequenceId > LastReadSequenceId)
|
|
||||||
{
|
|
||||||
LastReadMessageId = messageId;
|
|
||||||
LastReadSequenceId = sequenceId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void UpdateDeliveredCursor(Guid messageId)
|
|
||||||
{
|
|
||||||
LastDeliveredMessageId = messageId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
namespace Knot.Modules.Conversations.Domain;
|
|
||||||
|
|
||||||
public static class ChatConstants
|
|
||||||
{
|
|
||||||
public const int DefaultMessageQueryLimit = 100;
|
|
||||||
public const int MaxSharedMediaQueryLimit = 300;
|
|
||||||
public const int SearchMessagesLimit = 50;
|
|
||||||
public const int MaxFileUploadSizeMb = 50;
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
using Knot.Shared.Kernel;
|
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Domain;
|
|
||||||
|
|
||||||
public static class ChatErrors
|
|
||||||
{
|
|
||||||
public static readonly Error FileEmpty = new Error("File.Empty", "No file uploaded");
|
|
||||||
public static readonly Error FileInvalidExtension = new Error("File.InvalidExtension", "Must be a ZIP archive");
|
|
||||||
public static readonly Error ImportExpired = new Error("Import.Expired", "Session not found or expired");
|
|
||||||
public static readonly Error ImportMissing = new Error("Import.Missing", "ZIP file lost");
|
|
||||||
public static readonly Error ChatNotFound = new Error("Chat.NotFound", "Chat not found or access denied");
|
|
||||||
public static readonly Error NotFound = new Error("Chat.NotFound", "Chat not found"); // Alias
|
|
||||||
public static readonly Error NotMember = new Error("Chat.NotMember", "You are not a member of this chat");
|
|
||||||
public static readonly Error ChatsForbidden = new Error("Chats.Forbidden", "Вы не являетесь участником этого чата.");
|
|
||||||
public static readonly Error MessagesNotFound = new Error("Messages.NotFound", "Message not found.");
|
|
||||||
public static readonly Error ChatsNotFound = new Error("Chats.NotFound", "Чат не найден.");
|
|
||||||
public static readonly Error Unauthorized = new Error("Chats.Unauthorized", "Access denied");
|
|
||||||
public static readonly Error FoldersDisabled = new Error("Folders.Disabled", "Folders feature is disabled by the administrator.");
|
|
||||||
public static readonly Error PollsDisabled = new Error("Polls.Disabled", "Polls are disabled by the administrator.");
|
|
||||||
public static readonly Error MediaDisabled = new Error("Media.Disabled", "Media messages are disabled by the administrator.");
|
|
||||||
|
|
||||||
public static Error ImportCreateChatFailed(string msg) => new Error("Import.CreateChatFailed", msg);
|
|
||||||
public static Error FileTooLarge(int maxMb) => new Error("File.TooLarge", $"File exceeds the maximum allowed size of {maxMb}MB.");
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using Knot.Shared.Kernel;
|
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Domain;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Сущность папки для группировки чатов.
|
|
||||||
/// </summary>
|
|
||||||
public sealed class Folder : AggregateRoot<Guid>
|
|
||||||
{
|
|
||||||
public string Name { get; private set; }
|
|
||||||
public string? Icon { get; private set; } // URL из хранилища
|
|
||||||
public bool IsDefault { get; private set; }
|
|
||||||
public FolderType Type { get; private set; }
|
|
||||||
|
|
||||||
public Folder(Guid id, string name, string? icon = null, bool isDefault = false, FolderType type = FolderType.Custom)
|
|
||||||
: base(id)
|
|
||||||
{
|
|
||||||
Name = name;
|
|
||||||
Icon = icon;
|
|
||||||
IsDefault = isDefault;
|
|
||||||
Type = type;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Update(string name, string? icon)
|
|
||||||
{
|
|
||||||
if (IsDefault) throw new InvalidOperationException("Cannot rename default folders.");
|
|
||||||
Name = name;
|
|
||||||
Icon = icon;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public enum FolderType
|
|
||||||
{
|
|
||||||
All, // Все чаты
|
|
||||||
New, // Новые (с непрочитанными)
|
|
||||||
Muted, // Без звука
|
|
||||||
Custom // Пользовательская
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Настройки конкретного чата для конкретного пользователя.
|
|
||||||
/// Хранятся в PostgreSQL (связь User <-> Chat).
|
|
||||||
/// </summary>
|
|
||||||
public sealed class UserChatSettings : Entity<Guid>
|
|
||||||
{
|
|
||||||
public Guid UserId { get; private set; }
|
|
||||||
public Guid ChatId { get; private set; }
|
|
||||||
|
|
||||||
// Список папок, в которые входит чат для этого пользователя
|
|
||||||
private readonly List<Guid> _folderIds = new();
|
|
||||||
public IReadOnlyCollection<Guid> FolderIds => _folderIds.AsReadOnly();
|
|
||||||
|
|
||||||
public bool IsMuted { get; private set; }
|
|
||||||
|
|
||||||
private UserChatSettings() : base(Guid.NewGuid()) { }
|
|
||||||
|
|
||||||
public UserChatSettings(Guid userId, Guid chatId) : base(Guid.NewGuid())
|
|
||||||
{
|
|
||||||
UserId = userId;
|
|
||||||
ChatId = chatId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static UserChatSettings Create(Guid userId, Guid chatId) => new(userId, chatId);
|
|
||||||
|
|
||||||
public void AddToFolder(Guid folderId)
|
|
||||||
{
|
|
||||||
if (!_folderIds.Contains(folderId)) _folderIds.Add(folderId);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void RemoveFromFolder(Guid folderId)
|
|
||||||
{
|
|
||||||
_folderIds.Remove(folderId);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void SetMute(bool isMuted) => IsMuted = isMuted;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Глобальные настройки папок пользователя (скрытие дефолтных и т.д.).
|
|
||||||
/// Будет храниться в MongoDB.
|
|
||||||
/// </summary>
|
|
||||||
public sealed class UserFolderSettings : AggregateRoot<Guid>
|
|
||||||
{
|
|
||||||
public Guid UserId { get; private set; }
|
|
||||||
|
|
||||||
// Список ID папок, которые пользователь скрыл (только для дефолтных)
|
|
||||||
public List<Guid> HiddenDefaultFolderIds { get; private set; } = new();
|
|
||||||
|
|
||||||
// Список пользовательских папок (Guid созданных Folder)
|
|
||||||
public List<Guid> CustomFolderIds { get; private set; } = new();
|
|
||||||
|
|
||||||
public UserFolderSettings(Guid userId) : base(Guid.NewGuid())
|
|
||||||
{
|
|
||||||
UserId = userId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void HideFolder(Guid folderId)
|
|
||||||
{
|
|
||||||
if (!HiddenDefaultFolderIds.Contains(folderId)) HiddenDefaultFolderIds.Add(folderId);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void ShowFolder(Guid folderId)
|
|
||||||
{
|
|
||||||
HiddenDefaultFolderIds.Remove(folderId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
using Knot.Modules.Conversations.Domain;
|
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Domain;
|
|
||||||
|
|
||||||
public interface IChatRepository
|
|
||||||
{
|
|
||||||
void Add(Chat chat);
|
|
||||||
void Update(Chat chat);
|
|
||||||
void Remove(Chat chat);
|
|
||||||
Task<Chat?> GetByIdAsync(Guid id, CancellationToken cancellationToken);
|
|
||||||
Task<Chat?> GetFavoritesAsync(Guid userId, CancellationToken cancellationToken);
|
|
||||||
Task<List<Chat>> GetUserChatsAsync(Guid userId, CancellationToken cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public interface IFolderRepository
|
|
||||||
{
|
|
||||||
void Add(Folder folder);
|
|
||||||
void Update(Folder folder);
|
|
||||||
void Remove(Folder folder);
|
|
||||||
Task<Folder?> GetByIdAsync(Guid id, CancellationToken cancellationToken);
|
|
||||||
Task<List<Folder>> GetUserFoldersAsync(Guid userId, CancellationToken cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public interface IUserChatSettingsRepository
|
|
||||||
{
|
|
||||||
void Add(UserChatSettings settings);
|
|
||||||
void Update(UserChatSettings settings);
|
|
||||||
void Remove(UserChatSettings settings);
|
|
||||||
void RemoveRange(IEnumerable<UserChatSettings> settings);
|
|
||||||
Task<UserChatSettings?> GetAsync(Guid userId, Guid chatId, CancellationToken cancellationToken);
|
|
||||||
Task<List<UserChatSettings>> GetByUserIdAsync(Guid userId, CancellationToken cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public interface IUserFolderSettingsRepository
|
|
||||||
{
|
|
||||||
Task<UserFolderSettings?> GetByUserIdAsync(Guid userId, CancellationToken cancellationToken);
|
|
||||||
Task UpdateAsync(UserFolderSettings settings, CancellationToken cancellationToken);
|
|
||||||
Task RemoveByUserIdAsync(Guid userId, CancellationToken cancellationToken);
|
|
||||||
}
|
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Modules.Conversations.Infrastructure.SignalR;
|
using Knot.Modules.Conversations.Infrastructure.SignalR;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
using Microsoft.AspNetCore.SignalR;
|
using Microsoft.AspNetCore.SignalR;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Knot.Modules.Conversations.Domain;
|
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Infrastructure.Persistence;
|
namespace Knot.Modules.Conversations.Infrastructure.Persistence;
|
||||||
|
|
||||||
|
|||||||
+5
-4
@@ -4,19 +4,18 @@ using System.Linq;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Contracts.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Contracts.Conversations.Infrastructure.Persistence;
|
using Knot.Contracts.Conversations.Infrastructure.Persistence;
|
||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
|
||||||
using Knot.Modules.Conversations.Domain;
|
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using Knot.Shared.Kernel.Security;
|
using Knot.Shared.Kernel.Security;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||||
using DomainChat = Knot.Modules.Conversations.Domain.Chat;
|
using DomainChat = Knot.Contracts.Conversations.Domain.Chat;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Infrastructure.Persistence;
|
namespace Knot.Modules.Conversations.Infrastructure.Persistence;
|
||||||
|
|
||||||
public sealed class ChatsDbContext : DbContext, Knot.Modules.Conversations.Application.Abstractions.IChatsUnitOfWork, Knot.Contracts.Conversations.Infrastructure.Persistence.IChatsDbContext
|
public sealed class ChatsDbContext : DbContext, Knot.Contracts.Conversations.Application.Abstractions.IChatsUnitOfWork, Knot.Contracts.Conversations.Infrastructure.Persistence.IChatsDbContext
|
||||||
{
|
{
|
||||||
private readonly IMediator? _mediator;
|
private readonly IMediator? _mediator;
|
||||||
private readonly IEncryptionService? _encryptionService;
|
private readonly IEncryptionService? _encryptionService;
|
||||||
@@ -54,6 +53,8 @@ public sealed class ChatsDbContext : DbContext, Knot.Modules.Conversations.Appli
|
|||||||
{
|
{
|
||||||
builder.ToTable("Chats");
|
builder.ToTable("Chats");
|
||||||
builder.HasKey(c => c.Id);
|
builder.HasKey(c => c.Id);
|
||||||
|
builder.Property(c => c.IsImporting);
|
||||||
|
builder.Property(c => c.ImportJobId);
|
||||||
builder.Property(c => c.Type).HasConversion<string>();
|
builder.Property(c => c.Type).HasConversion<string>();
|
||||||
|
|
||||||
builder.OwnsMany(c => c.Members, mb =>
|
builder.OwnsMany(c => c.Members, mb =>
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using MongoDB.Bson.Serialization;
|
using MongoDB.Bson.Serialization;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Infrastructure.Persistence.Mongo;
|
namespace Knot.Modules.Conversations.Infrastructure.Persistence.Mongo;
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using MongoDB.Driver;
|
using MongoDB.Driver;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Infrastructure.Persistence.Mongo;
|
namespace Knot.Modules.Conversations.Infrastructure.Persistence.Mongo;
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
using Knot.Modules.Conversations.Application.Abstractions;
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using Knot.Modules.Conversations.Infrastructure.SignalR;
|
using Knot.Modules.Conversations.Infrastructure.SignalR;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Infrastructure.Services;
|
namespace Knot.Modules.Conversations.Infrastructure.Services;
|
||||||
|
|
||||||
public sealed class UserStatusService : IUserStatusService, Knot.Contracts.Conversations.Abstractions.IUserStatusService
|
public sealed class UserStatusService :
|
||||||
|
Knot.Contracts.Conversations.Application.Abstractions.IUserStatusService,
|
||||||
|
Knot.Contracts.Conversations.Abstractions.IUserStatusService
|
||||||
{
|
{
|
||||||
public bool IsUserOnline(string userId)
|
public bool IsUserOnline(string userId)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -8,9 +8,20 @@ using Knot.Modules.Conversations.Application.Messages.Send;
|
|||||||
using Knot.Modules.Conversations.Application.Messages.Read;
|
using Knot.Modules.Conversations.Application.Messages.Read;
|
||||||
using Knot.Modules.Conversations.Application.Messages.Delete;
|
using Knot.Modules.Conversations.Application.Messages.Delete;
|
||||||
using Knot.Modules.Conversations.Application.Messages.React;
|
using Knot.Modules.Conversations.Application.Messages.React;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using Microsoft.Extensions.Caching.Memory;
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
|
using Knot.Contracts.Auth.Domain;
|
||||||
|
using Knot.Contracts.Auth.Application.Abstractions;
|
||||||
|
using Knot.Modules.Conversations.Application.Messages.Pin;
|
||||||
|
using Knot.Modules.Conversations.Application.Messages.Unpin;
|
||||||
|
using Knot.Modules.Conversations.Application.Messages.Vote;
|
||||||
|
using Knot.Modules.Conversations.Application.Messages.Edit;
|
||||||
|
using Knot.Modules.Conversations.Application.DTOs;
|
||||||
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
|
using Knot.Contracts.Messaging.Domain;
|
||||||
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
|
using Knot.Contracts.Profiles.Domain;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Infrastructure.SignalR;
|
namespace Knot.Modules.Conversations.Infrastructure.SignalR;
|
||||||
|
|
||||||
@@ -28,19 +39,41 @@ public sealed class ChatHub : Hub
|
|||||||
public static int OnlineUsersCount => _userConnections.Count;
|
public static int OnlineUsersCount => _userConnections.Count;
|
||||||
public static bool IsUserOnline(string userId) => _userConnections.ContainsKey(userId);
|
public static bool IsUserOnline(string userId) => _userConnections.ContainsKey(userId);
|
||||||
|
|
||||||
|
// userId → CallSession (one user can be in only one call at a time)
|
||||||
|
private static readonly ConcurrentDictionary<string, CallSession> _activeSessionsByUser = new();
|
||||||
|
// chatId → (startTime, callType)
|
||||||
|
private static readonly ConcurrentDictionary<string, (DateTime StartTime, string CallType)> _activeGroupCalls = new();
|
||||||
|
|
||||||
private readonly ISender _sender;
|
private readonly ISender _sender;
|
||||||
private readonly IUserContext _userContext;
|
private readonly IUserContext _userContext;
|
||||||
private readonly IChatRepository _chatRepository;
|
private readonly IChatRepository _chatRepository;
|
||||||
|
private readonly IUserRepository _userRepository;
|
||||||
|
private readonly IMessageRepository _messageRepository;
|
||||||
private readonly ILogger<ChatHub> _logger;
|
private readonly ILogger<ChatHub> _logger;
|
||||||
private readonly IMemoryCache _cache;
|
private readonly IMemoryCache _cache;
|
||||||
|
private readonly IUserDisplayNameProvider _userProvider;
|
||||||
|
private readonly IProfileRepository _profileRepository;
|
||||||
|
|
||||||
public ChatHub(ISender sender, IUserContext userContext, IChatRepository chatRepository, ILogger<ChatHub> logger, IMemoryCache cache)
|
public ChatHub(
|
||||||
|
ISender sender,
|
||||||
|
IUserContext userContext,
|
||||||
|
IChatRepository chatRepository,
|
||||||
|
IUserRepository userRepository,
|
||||||
|
IMessageRepository messageRepository,
|
||||||
|
ILogger<ChatHub> logger,
|
||||||
|
IMemoryCache cache,
|
||||||
|
IUserDisplayNameProvider userProvider,
|
||||||
|
IProfileRepository profileRepository)
|
||||||
{
|
{
|
||||||
_sender = sender;
|
_sender = sender;
|
||||||
_userContext = userContext;
|
_userContext = userContext;
|
||||||
_chatRepository = chatRepository;
|
_chatRepository = chatRepository;
|
||||||
|
_userRepository = userRepository;
|
||||||
|
_messageRepository = messageRepository;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_cache = cache;
|
_cache = cache;
|
||||||
|
_userProvider = userProvider;
|
||||||
|
_profileRepository = profileRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task OnConnectedAsync()
|
public override async Task OnConnectedAsync()
|
||||||
@@ -66,7 +99,15 @@ public sealed class ChatHub : Hub
|
|||||||
|
|
||||||
userId, Context.ConnectionId, userChats.Count);
|
userId, Context.ConnectionId, userChats.Count);
|
||||||
|
|
||||||
await Clients.Others.SendAsync("user_online", new { userId });
|
var isInvisible = await IsUserInvisibleAsync(_userContext.UserId, Context.ConnectionAborted);
|
||||||
|
if (!isInvisible)
|
||||||
|
{
|
||||||
|
await BroadcastPresenceToVisibleUsersAsync(
|
||||||
|
"user_online",
|
||||||
|
new { userId },
|
||||||
|
_userContext.UserId,
|
||||||
|
Context.ConnectionAborted);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
await base.OnConnectedAsync();
|
await base.OnConnectedAsync();
|
||||||
}
|
}
|
||||||
@@ -82,7 +123,22 @@ public sealed class ChatHub : Hub
|
|||||||
if (set.Count == 0)
|
if (set.Count == 0)
|
||||||
{
|
{
|
||||||
_userConnections.TryRemove(userId, out _);
|
_userConnections.TryRemove(userId, out _);
|
||||||
await Clients.Others.SendAsync("user_offline", new { userId, lastSeen = DateTime.UtcNow });
|
try
|
||||||
|
{
|
||||||
|
var isInvisible = await IsUserInvisibleAsync(_userContext.UserId, CancellationToken.None);
|
||||||
|
if (!isInvisible)
|
||||||
|
{
|
||||||
|
await BroadcastPresenceToVisibleUsersAsync(
|
||||||
|
"user_offline",
|
||||||
|
new { userId, lastSeen = DateTime.UtcNow },
|
||||||
|
_userContext.UserId,
|
||||||
|
CancellationToken.None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "Presence broadcast on disconnect failed for {UserId}", userId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_cache.Set("Global_OnlineUsersCount", _userConnections.Count);
|
_cache.Set("Global_OnlineUsersCount", _userConnections.Count);
|
||||||
@@ -91,6 +147,56 @@ public sealed class ChatHub : Hub
|
|||||||
await base.OnDisconnectedAsync(exception);
|
await base.OnDisconnectedAsync(exception);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async Task<bool> IsUserInvisibleAsync(Guid userId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var profile = await _profileRepository.GetAsync(userId, ct);
|
||||||
|
return profile?.IsInvisible ?? false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task BroadcastPresenceToVisibleUsersAsync(
|
||||||
|
string eventName,
|
||||||
|
object payload,
|
||||||
|
Guid sourceUserId,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var recipients = _userConnections.Keys
|
||||||
|
.Where(id => id != sourceUserId.ToString())
|
||||||
|
.Select(id => Guid.TryParse(id, out var parsed) ? parsed : Guid.Empty)
|
||||||
|
.Where(id => id != Guid.Empty)
|
||||||
|
.Distinct()
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
if (recipients.Count == 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var recipientProfiles = await _profileRepository.GetAsync(recipients, cancellationToken);
|
||||||
|
var invisibleRecipientIds = recipientProfiles
|
||||||
|
.Where(p => p.IsInvisible)
|
||||||
|
.Select(p => p.UserId)
|
||||||
|
.ToHashSet();
|
||||||
|
|
||||||
|
foreach (var kvp in _userConnections)
|
||||||
|
{
|
||||||
|
if (!Guid.TryParse(kvp.Key, out var recipientId))
|
||||||
|
continue;
|
||||||
|
if (recipientId == sourceUserId)
|
||||||
|
continue;
|
||||||
|
if (invisibleRecipientIds.Contains(recipientId))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
string[] connectionIds;
|
||||||
|
lock (kvp.Value)
|
||||||
|
{
|
||||||
|
connectionIds = kvp.Value.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var connectionId in connectionIds)
|
||||||
|
{
|
||||||
|
await Clients.Client(connectionId).SendAsync(eventName, payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ────────────────────────────────────────────────────────────────
|
// ────────────────────────────────────────────────────────────────
|
||||||
// Chat methods
|
// Chat methods
|
||||||
// ────────────────────────────────────────────────────────────────
|
// ────────────────────────────────────────────────────────────────
|
||||||
@@ -103,14 +209,18 @@ public sealed class ChatHub : Hub
|
|||||||
new AttachmentRequest(a.Type, a.Url, a.FileName, a.FileSize)).ToList();
|
new AttachmentRequest(a.Type, a.Url, a.FileName, a.FileSize)).ToList();
|
||||||
|
|
||||||
var command = new SendMessageCommand(
|
var command = new SendMessageCommand(
|
||||||
request.ChatId,
|
ChatId: request.ChatId,
|
||||||
_userContext.UserId,
|
SenderId: _userContext.UserId,
|
||||||
request.Content,
|
Content: request.Content,
|
||||||
request.Type,
|
Type: request.Type,
|
||||||
attachments,
|
Attachments: attachments,
|
||||||
request.ReplyToId,
|
ReplyToId: request.ReplyToId,
|
||||||
request.Quote,
|
Quote: request.Quote,
|
||||||
request.ForwardedFromId);
|
ForwardedFromId: request.ForwardedFromId,
|
||||||
|
PollOptions: request.PollOptions,
|
||||||
|
PollIsAnonymous: request.PollIsAnonymous,
|
||||||
|
PollAllowMultipleAnswers: request.PollAllowMultipleAnswers
|
||||||
|
);
|
||||||
|
|
||||||
await _sender.Send(command);
|
await _sender.Send(command);
|
||||||
}
|
}
|
||||||
@@ -218,6 +328,62 @@ public sealed class ChatHub : Hub
|
|||||||
_logger.LogInformation("RemoveReaction completed successfully");
|
_logger.LogInformation("RemoveReaction completed successfully");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HubMethodName("pin_message")]
|
||||||
|
public async Task PinMessage(PinMessageRequest request)
|
||||||
|
{
|
||||||
|
var command = new PinMessageCommand(request.MessageId, request.ChatId, _userContext.UserId);
|
||||||
|
var result = await _sender.Send(command);
|
||||||
|
var message = await _messageRepository.GetByIdAsync(request.MessageId, Context.ConnectionAborted);
|
||||||
|
if (message != null)
|
||||||
|
{
|
||||||
|
var senderInfo = await _userProvider.GetUsersInfoAsync(new[] { message.SenderId });
|
||||||
|
var dto = MessageMapper.MapToDto(message, senderInfo, Enumerable.Empty<MessageReaction>(), Enumerable.Empty<Guid>());
|
||||||
|
|
||||||
|
await Clients.Group(request.ChatId.ToString()).SendAsync("message_pinned", new
|
||||||
|
{
|
||||||
|
chatId = request.ChatId,
|
||||||
|
message = dto,
|
||||||
|
userId = _userContext.UserId
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HubMethodName("unpin_message")]
|
||||||
|
public async Task UnpinMessage(PinMessageRequest request)
|
||||||
|
{
|
||||||
|
var command = new UnpinMessageCommand(request.MessageId, request.ChatId, _userContext.UserId);
|
||||||
|
var result = await _sender.Send(command);
|
||||||
|
|
||||||
|
await Clients.Group(request.ChatId.ToString()).SendAsync("message_unpinned", new
|
||||||
|
{
|
||||||
|
chatId = request.ChatId,
|
||||||
|
messageId = request.MessageId,
|
||||||
|
userId = _userContext.UserId
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[HubMethodName("edit_message")]
|
||||||
|
public async Task EditMessage(EditMessageHubRequest request)
|
||||||
|
{
|
||||||
|
var command = new EditMessageCommand(request.MessageId, request.ChatId, _userContext.UserId, request.Content);
|
||||||
|
var result = await _sender.Send(command);
|
||||||
|
if (result.IsFailure)
|
||||||
|
{
|
||||||
|
throw new HubException(result.Error.Description);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HubMethodName("vote_poll")]
|
||||||
|
public async Task VotePoll(VotePollRequest request)
|
||||||
|
{
|
||||||
|
var command = new VotePollCommand(request.MessageId, request.ChatId, _userContext.UserId, request.OptionId);
|
||||||
|
var result = await _sender.Send(command);
|
||||||
|
if (result.IsFailure)
|
||||||
|
{
|
||||||
|
throw new HubException(result.Error.Description);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ────────────────────────────────────────────────────────────────
|
// ────────────────────────────────────────────────────────────────
|
||||||
// Friend signals (Proxy methods for real-time notification)
|
// Friend signals (Proxy methods for real-time notification)
|
||||||
// ────────────────────────────────────────────────────────────────
|
// ────────────────────────────────────────────────────────────────
|
||||||
@@ -284,10 +450,12 @@ public sealed class ChatHub : Hub
|
|||||||
[HubMethodName("call_offer")]
|
[HubMethodName("call_offer")]
|
||||||
public async Task CallOffer(CallOfferRequest request)
|
public async Task CallOffer(CallOfferRequest request)
|
||||||
{
|
{
|
||||||
// Try to get caller info from current user's claims
|
// Fetch fresh user info from repository instead of relying on potentially stale JWT claims
|
||||||
var displayName = Context.User?.FindFirstValue("name") ?? Context.User?.FindFirstValue(ClaimTypes.Name) ?? "User";
|
var user = await _userRepository.GetByIdAsync(_userContext.UserId);
|
||||||
var avatar = Context.User?.FindFirstValue("avatar");
|
|
||||||
var username = Context.User?.FindFirstValue("unique_name") ?? Context.User?.Identity?.Name;
|
var displayName = user?.DisplayName ?? Context.User?.FindFirstValue("name") ?? Context.User?.FindFirstValue(ClaimTypes.Name) ?? "User";
|
||||||
|
var avatar = user?.Avatar ?? Context.User?.FindFirstValue("avatar");
|
||||||
|
var username = user?.Username ?? Context.User?.FindFirstValue("unique_name") ?? Context.User?.Identity?.Name;
|
||||||
|
|
||||||
await SendToUserAsync(request.TargetUserId, "call_incoming", new
|
await SendToUserAsync(request.TargetUserId, "call_incoming", new
|
||||||
{
|
{
|
||||||
@@ -297,18 +465,41 @@ public sealed class ChatHub : Hub
|
|||||||
chatId = request.ChatId,
|
chatId = request.ChatId,
|
||||||
callerInfo = new
|
callerInfo = new
|
||||||
{
|
{
|
||||||
|
|
||||||
id = _userContext.UserId.ToString(),
|
id = _userContext.UserId.ToString(),
|
||||||
displayName = displayName,
|
displayName = displayName,
|
||||||
avatar = avatar,
|
avatar = avatar,
|
||||||
username = username
|
username = username
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Track session for history
|
||||||
|
Guid? chatId = null;
|
||||||
|
if (Guid.TryParse(request.ChatId, out var parsedChatId)) chatId = parsedChatId;
|
||||||
|
|
||||||
|
if (!chatId.HasValue)
|
||||||
|
{
|
||||||
|
var userChats = await _chatRepository.GetUserChatsAsync(_userContext.UserId, Context.ConnectionAborted);
|
||||||
|
if (Guid.TryParse(request.TargetUserId, out var targetId))
|
||||||
|
{
|
||||||
|
var personalChat = userChats.FirstOrDefault(c => c.Type == ChatType.Personal && c.Members.Any(m => m.UserId == targetId));
|
||||||
|
if (personalChat != null) chatId = personalChat.Id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var session = new CallSession(chatId, _userContext.UserId, Guid.Parse(request.TargetUserId), request.CallType, DateTime.UtcNow);
|
||||||
|
_activeSessionsByUser[_userContext.UserId.ToString()] = session;
|
||||||
|
_activeSessionsByUser[request.TargetUserId] = session;
|
||||||
}
|
}
|
||||||
|
|
||||||
[HubMethodName("call_answer")]
|
[HubMethodName("call_answer")]
|
||||||
public async Task CallAnswer(CallAnswerRequest request)
|
public async Task CallAnswer(CallAnswerRequest request)
|
||||||
{
|
{
|
||||||
|
if (_activeSessionsByUser.TryGetValue(_userContext.UserId.ToString(), out var session))
|
||||||
|
{
|
||||||
|
session.IsAnswered = true;
|
||||||
|
session.AnswerTime = DateTime.UtcNow;
|
||||||
|
}
|
||||||
|
|
||||||
await SendToUserAsync(request.TargetUserId, "call_answered", new
|
await SendToUserAsync(request.TargetUserId, "call_answered", new
|
||||||
{
|
{
|
||||||
from = _userContext.UserId.ToString(),
|
from = _userContext.UserId.ToString(),
|
||||||
@@ -319,6 +510,19 @@ public sealed class ChatHub : Hub
|
|||||||
[HubMethodName("call_decline")]
|
[HubMethodName("call_decline")]
|
||||||
public async Task CallDecline(TargetUserRequest request)
|
public async Task CallDecline(TargetUserRequest request)
|
||||||
{
|
{
|
||||||
|
var currentUserIdStr = _userContext.UserId.ToString();
|
||||||
|
if (_activeSessionsByUser.TryRemove(currentUserIdStr, out var session))
|
||||||
|
{
|
||||||
|
_activeSessionsByUser.TryRemove(request.TargetUserId, out _);
|
||||||
|
if (session.ChatId.HasValue)
|
||||||
|
{
|
||||||
|
// If declined by recipient, it's a "declined" call
|
||||||
|
// If current user is recipient (not the one who started), status is declined
|
||||||
|
string status = _userContext.UserId == session.FromUserId ? "cancelled" : "declined";
|
||||||
|
await CreateCallMessage(session.ChatId.Value, session.FromUserId, session.CallType, status, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
await SendToUserAsync(request.TargetUserId, "call_declined", new
|
await SendToUserAsync(request.TargetUserId, "call_declined", new
|
||||||
{
|
{
|
||||||
from = _userContext.UserId.ToString(),
|
from = _userContext.UserId.ToString(),
|
||||||
@@ -328,12 +532,53 @@ public sealed class ChatHub : Hub
|
|||||||
[HubMethodName("call_end")]
|
[HubMethodName("call_end")]
|
||||||
public async Task CallEnd(TargetUserRequest request)
|
public async Task CallEnd(TargetUserRequest request)
|
||||||
{
|
{
|
||||||
|
var currentUserIdStr = _userContext.UserId.ToString();
|
||||||
|
if (_activeSessionsByUser.TryRemove(currentUserIdStr, out var session))
|
||||||
|
{
|
||||||
|
_activeSessionsByUser.TryRemove(request.TargetUserId, out _);
|
||||||
|
if (session.ChatId.HasValue)
|
||||||
|
{
|
||||||
|
int duration = session.IsAnswered && session.AnswerTime.HasValue
|
||||||
|
? (int)(DateTime.UtcNow - session.AnswerTime.Value).TotalSeconds
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
string status = session.IsAnswered ? "completed" : (_userContext.UserId == session.FromUserId ? "cancelled" : "missed");
|
||||||
|
await CreateCallMessage(session.ChatId.Value, session.FromUserId, session.CallType, status, duration);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
await SendToUserAsync(request.TargetUserId, "call_ended", new
|
await SendToUserAsync(request.TargetUserId, "call_ended", new
|
||||||
{
|
{
|
||||||
from = _userContext.UserId.ToString(),
|
from = _userContext.UserId.ToString(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async Task CreateCallMessage(Guid chatId, Guid senderId, string callType, string status, int duration)
|
||||||
|
{
|
||||||
|
var command = new SendMessageCommand(
|
||||||
|
chatId,
|
||||||
|
senderId,
|
||||||
|
null,
|
||||||
|
"call",
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
callType,
|
||||||
|
status,
|
||||||
|
duration
|
||||||
|
);
|
||||||
|
|
||||||
|
await _sender.Send(command);
|
||||||
|
}
|
||||||
|
|
||||||
[HubMethodName("ice_candidate")]
|
[HubMethodName("ice_candidate")]
|
||||||
public async Task IceCandidate(IceCandidateRequest request)
|
public async Task IceCandidate(IceCandidateRequest request)
|
||||||
{
|
{
|
||||||
@@ -396,14 +641,20 @@ public sealed class ChatHub : Hub
|
|||||||
var chatId = request.ChatId;
|
var chatId = request.ChatId;
|
||||||
var userId = _userContext.UserId.ToString();
|
var userId = _userContext.UserId.ToString();
|
||||||
|
|
||||||
|
// Fetch fresh user info from repository
|
||||||
|
var user = await _userRepository.GetByIdAsync(_userContext.UserId);
|
||||||
|
|
||||||
var displayName = Context.User?.FindFirstValue("name") ?? Context.User?.FindFirstValue(ClaimTypes.Name) ?? "User";
|
var displayName = user?.DisplayName ?? Context.User?.FindFirstValue("name") ?? Context.User?.FindFirstValue(ClaimTypes.Name) ?? "User";
|
||||||
var avatar = Context.User?.FindFirstValue("avatar");
|
var avatar = user?.Avatar ?? Context.User?.FindFirstValue("avatar");
|
||||||
var username = Context.User?.FindFirstValue("unique_name") ?? Context.User?.Identity?.Name ?? "user";
|
var username = user?.Username ?? Context.User?.FindFirstValue("unique_name") ?? Context.User?.Identity?.Name ?? "user";
|
||||||
|
|
||||||
var userInfo = new ParticipantInfo(userId, username, displayName, avatar);
|
var userInfo = new ParticipantInfo(userId, username, displayName, avatar);
|
||||||
|
|
||||||
var participants = _groupCallParticipants.GetOrAdd(chatId, _ => new ConcurrentDictionary<string, ParticipantInfo>());
|
var participants = _groupCallParticipants.GetOrAdd(chatId, _ =>
|
||||||
|
{
|
||||||
|
_activeGroupCalls[chatId] = (DateTime.UtcNow, request.CallType);
|
||||||
|
return new ConcurrentDictionary<string, ParticipantInfo>();
|
||||||
|
});
|
||||||
var isFirst = participants.IsEmpty;
|
var isFirst = participants.IsEmpty;
|
||||||
participants.TryAdd(userId, userInfo);
|
participants.TryAdd(userId, userInfo);
|
||||||
|
|
||||||
@@ -461,6 +712,11 @@ public sealed class ChatHub : Hub
|
|||||||
if (participants.IsEmpty)
|
if (participants.IsEmpty)
|
||||||
{
|
{
|
||||||
_groupCallParticipants.TryRemove(chatId, out _);
|
_groupCallParticipants.TryRemove(chatId, out _);
|
||||||
|
if (_activeGroupCalls.TryRemove(chatId, out var info))
|
||||||
|
{
|
||||||
|
var duration = (int)(DateTime.UtcNow - info.StartTime).TotalSeconds;
|
||||||
|
await CreateCallMessage(Guid.Parse(chatId), _userContext.UserId, info.CallType, "completed", duration);
|
||||||
|
}
|
||||||
await Clients.Group(chatId).SendAsync("group_call_ended", new { chatId = chatId });
|
await Clients.Group(chatId).SendAsync("group_call_ended", new { chatId = chatId });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -549,7 +805,7 @@ public sealed class ChatHub : Hub
|
|||||||
await Clients.Group(request.ChatId).SendAsync("group_call_status_updated", new
|
await Clients.Group(request.ChatId).SendAsync("group_call_status_updated", new
|
||||||
{
|
{
|
||||||
chatId = request.ChatId,
|
chatId = request.ChatId,
|
||||||
userId = Context.UserIdentifier,
|
userId = _userContext.UserId.ToString(),
|
||||||
isMuted = request.IsMuted,
|
isMuted = request.IsMuted,
|
||||||
isVideoOff = request.IsVideoOff
|
isVideoOff = request.IsVideoOff
|
||||||
});
|
});
|
||||||
@@ -576,7 +832,7 @@ public sealed class ChatHub : Hub
|
|||||||
await Clients.Group(chatId).SendAsync("group_call_status_updated", new
|
await Clients.Group(chatId).SendAsync("group_call_status_updated", new
|
||||||
{
|
{
|
||||||
chatId = chatId,
|
chatId = chatId,
|
||||||
userId = Context.UserIdentifier,
|
userId = _userContext.UserId.ToString(),
|
||||||
isMuted = isMuted,
|
isMuted = isMuted,
|
||||||
isVideoOff = isVideoOff
|
isVideoOff = isVideoOff
|
||||||
});
|
});
|
||||||
@@ -660,7 +916,10 @@ public sealed class ChatHub : Hub
|
|||||||
List<AttachmentHubRequest>? Attachments = null,
|
List<AttachmentHubRequest>? Attachments = null,
|
||||||
Guid? ReplyToId = null,
|
Guid? ReplyToId = null,
|
||||||
string? Quote = null,
|
string? Quote = null,
|
||||||
Guid? ForwardedFromId = null);
|
Guid? ForwardedFromId = null,
|
||||||
|
List<string>? PollOptions = null,
|
||||||
|
bool? PollIsAnonymous = null,
|
||||||
|
bool? PollAllowMultipleAnswers = null);
|
||||||
public record ReadMessagesRequest(Guid ChatId, Guid LastReadMessageId, long LastReadSequenceId);
|
public record ReadMessagesRequest(Guid ChatId, Guid LastReadMessageId, long LastReadSequenceId);
|
||||||
public record CallOfferRequest(string TargetUserId, object Offer, string CallType, string? ChatId);
|
public record CallOfferRequest(string TargetUserId, object Offer, string CallType, string? ChatId);
|
||||||
public record CallAnswerRequest(string TargetUserId, object Answer);
|
public record CallAnswerRequest(string TargetUserId, object Answer);
|
||||||
@@ -672,6 +931,7 @@ public sealed class ChatHub : Hub
|
|||||||
public record CallStatusRequest(string TargetUserId, bool IsMuted, bool IsVideoOff);
|
public record CallStatusRequest(string TargetUserId, bool IsMuted, bool IsVideoOff);
|
||||||
public record AddReactionRequest(Guid MessageId, Guid ChatId, string Emoji);
|
public record AddReactionRequest(Guid MessageId, Guid ChatId, string Emoji);
|
||||||
public record RemoveReactionRequest(Guid MessageId, Guid ChatId, string Emoji);
|
public record RemoveReactionRequest(Guid MessageId, Guid ChatId, string Emoji);
|
||||||
|
public record PinMessageRequest(Guid MessageId, Guid ChatId);
|
||||||
public record DeleteMessagesHubRequest(Guid ChatId, List<string> MessageIds, bool DeleteForAll);
|
public record DeleteMessagesHubRequest(Guid ChatId, List<string> MessageIds, bool DeleteForAll);
|
||||||
public record GroupCallJoinRequest(string ChatId, string CallType);
|
public record GroupCallJoinRequest(string ChatId, string CallType);
|
||||||
public record ParticipantInfo(string Id, string Username, string DisplayName, string? Avatar, bool IsSharingScreen = false, bool IsMuted = false, bool IsVideoOff = false);
|
public record ParticipantInfo(string Id, string Username, string DisplayName, string? Avatar, bool IsSharingScreen = false, bool IsMuted = false, bool IsVideoOff = false);
|
||||||
@@ -684,5 +944,27 @@ public sealed class ChatHub : Hub
|
|||||||
public record GroupRenegotiateRequest(string ChatId, string TargetUserId, object Offer);
|
public record GroupRenegotiateRequest(string ChatId, string TargetUserId, object Offer);
|
||||||
public record GroupRenegotiateAnswerRequest(string ChatId, string TargetUserId, object Answer);
|
public record GroupRenegotiateAnswerRequest(string ChatId, string TargetUserId, object Answer);
|
||||||
public record FriendSignalRequest(string FriendId);
|
public record FriendSignalRequest(string FriendId);
|
||||||
|
public record VotePollRequest(Guid MessageId, Guid ChatId, Guid OptionId);
|
||||||
|
public record EditMessageHubRequest(Guid MessageId, Guid ChatId, string Content);
|
||||||
|
|
||||||
|
public class CallSession
|
||||||
|
{
|
||||||
|
public Guid? ChatId { get; }
|
||||||
|
public Guid FromUserId { get; }
|
||||||
|
public Guid ToUserId { get; }
|
||||||
|
public string CallType { get; }
|
||||||
|
public DateTime StartTime { get; }
|
||||||
|
public bool IsAnswered { get; set; }
|
||||||
|
public DateTime? AnswerTime { get; set; }
|
||||||
|
|
||||||
|
public CallSession(Guid? chatId, Guid fromUserId, Guid toUserId, string callType, DateTime startTime)
|
||||||
|
{
|
||||||
|
ChatId = chatId;
|
||||||
|
FromUserId = fromUserId;
|
||||||
|
ToUserId = toUserId;
|
||||||
|
CallType = callType;
|
||||||
|
StartTime = startTime;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,4 +5,23 @@ using System.Threading;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
using Microsoft.AspNetCore.SignalR;
|
using Microsoft.AspNetCore.SignalR;
|
||||||
public class MessageNotifier : IMessageNotifier { private readonly IHubContext<ChatHub> _hubContext; public MessageNotifier(IHubContext<ChatHub> hubContext) { _hubContext = hubContext; } public Task NotifyNewMessageAsync(Guid chatId, object messagePayload, CancellationToken cancellationToken) { return _hubContext.Clients.Group(chatId.ToString()).SendAsync("new_message", messagePayload, cancellationToken); } }
|
|
||||||
|
public class MessageNotifier : IMessageNotifier
|
||||||
|
{
|
||||||
|
private readonly IHubContext<ChatHub> _hubContext;
|
||||||
|
|
||||||
|
public MessageNotifier(IHubContext<ChatHub> hubContext)
|
||||||
|
{
|
||||||
|
_hubContext = hubContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task NotifyNewMessageAsync(Guid chatId, object messagePayload, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return _hubContext.Clients.Group(chatId.ToString()).SendAsync("new_message", messagePayload, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task NotifyMessageUpdateAsync(Guid chatId, string updateType, object updatePayload, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return _hubContext.Clients.Group(chatId.ToString()).SendAsync(updateType, updatePayload, cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
<ProjectReference Include="..\..\Contracts\Messaging\Knot.Contracts.Messaging.csproj" />
|
<ProjectReference Include="..\..\Contracts\Messaging\Knot.Contracts.Messaging.csproj" />
|
||||||
<ProjectReference Include="..\..\Contracts\Conversations\Knot.Contracts.Conversations.csproj" />
|
<ProjectReference Include="..\..\Contracts\Conversations\Knot.Contracts.Conversations.csproj" />
|
||||||
<ProjectReference Include="..\..\Contracts\Auth\Knot.Contracts.Auth.csproj" />
|
<ProjectReference Include="..\..\Contracts\Auth\Knot.Contracts.Auth.csproj" />
|
||||||
|
<ProjectReference Include="..\..\Contracts\Profiles\Knot.Contracts.Profiles.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
Generated
+3
-3
@@ -26,7 +26,7 @@ namespace Knot.Modules.Conversations.Migrations
|
|||||||
|
|
||||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||||
|
|
||||||
modelBuilder.Entity("Knot.Modules.Conversations.Domain.Chat", b =>
|
modelBuilder.Entity("Knot.Contracts.Conversations.Domain.Chat", b =>
|
||||||
{
|
{
|
||||||
b.Property<Guid>("Id")
|
b.Property<Guid>("Id")
|
||||||
.ValueGeneratedOnAdd()
|
.ValueGeneratedOnAdd()
|
||||||
@@ -56,9 +56,9 @@ namespace Knot.Modules.Conversations.Migrations
|
|||||||
b.ToTable("Chats", "chats");
|
b.ToTable("Chats", "chats");
|
||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Knot.Modules.Conversations.Domain.Chat", b =>
|
modelBuilder.Entity("Knot.Contracts.Conversations.Domain.Chat", b =>
|
||||||
{
|
{
|
||||||
b.OwnsMany("Knot.Modules.Conversations.Domain.ChatMember", "Members", b1 =>
|
b.OwnsMany("Knot.Contracts.Conversations.Domain.ChatMember", "Members", b1 =>
|
||||||
{
|
{
|
||||||
b1.Property<Guid>("Id")
|
b1.Property<Guid>("Id")
|
||||||
.ValueGeneratedOnAdd()
|
.ValueGeneratedOnAdd()
|
||||||
|
|||||||
Generated
+166
@@ -0,0 +1,166 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using Knot.Modules.Conversations.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 Knot.Modules.Conversations.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(ChatsDbContext))]
|
||||||
|
[Migration("20260406122703_AddIsImportingToChat")]
|
||||||
|
partial class AddIsImportingToChat
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder
|
||||||
|
.HasDefaultSchema("chats")
|
||||||
|
.HasAnnotation("ProductVersion", "10.0.4")
|
||||||
|
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||||
|
|
||||||
|
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||||
|
|
||||||
|
modelBuilder.Entity("Knot.Contracts.Conversations.Domain.Chat", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<string>("Avatar")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<DateTime>("CreatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<bool>("IsImporting")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<long>("LastMessageSequenceId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("Type")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Chats", "chats");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Knot.Contracts.Conversations.Domain.Folder", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<string>("Icon")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<bool>("IsDefault")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("Type")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Folders", "chats");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Knot.Contracts.Conversations.Domain.UserChatSettings", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Guid>("ChatId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<string>("FolderIds")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<bool>("IsMuted")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<Guid>("UserId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("UserId", "ChatId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.ToTable("UserChatSettings", "chats");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Knot.Contracts.Conversations.Domain.Chat", b =>
|
||||||
|
{
|
||||||
|
b.OwnsMany("Knot.Contracts.Conversations.Domain.ChatMember", "Members", b1 =>
|
||||||
|
{
|
||||||
|
b1.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b1.Property<Guid>("ChatId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b1.Property<bool>("IsMuted")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b1.Property<bool>("IsPinned")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b1.Property<DateTime>("JoinedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b1.Property<Guid?>("LastDeliveredMessageId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b1.Property<Guid?>("LastReadMessageId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b1.Property<long>("LastReadSequenceId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b1.Property<string>("Role")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b1.Property<Guid>("UserId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b1.HasKey("Id");
|
||||||
|
|
||||||
|
b1.HasIndex("ChatId", "UserId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b1.ToTable("ChatMembers", "chats");
|
||||||
|
|
||||||
|
b1.WithOwner()
|
||||||
|
.HasForeignKey("ChatId");
|
||||||
|
});
|
||||||
|
|
||||||
|
b.Navigation("Members");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Knot.Modules.Conversations.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddIsImportingToChat : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<bool>(
|
||||||
|
name: "IsImporting",
|
||||||
|
schema: "chats",
|
||||||
|
table: "Chats",
|
||||||
|
type: "boolean",
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "IsImporting",
|
||||||
|
schema: "chats",
|
||||||
|
table: "Chats");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+169
@@ -0,0 +1,169 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using Knot.Modules.Conversations.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 Knot.Modules.Conversations.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(ChatsDbContext))]
|
||||||
|
[Migration("20260406123444_AddImportJobIdToChat")]
|
||||||
|
partial class AddImportJobIdToChat
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder
|
||||||
|
.HasDefaultSchema("chats")
|
||||||
|
.HasAnnotation("ProductVersion", "10.0.4")
|
||||||
|
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||||
|
|
||||||
|
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||||
|
|
||||||
|
modelBuilder.Entity("Knot.Contracts.Conversations.Domain.Chat", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<string>("Avatar")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<DateTime>("CreatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Guid?>("ImportJobId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<bool>("IsImporting")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<long>("LastMessageSequenceId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("Type")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Chats", "chats");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Knot.Contracts.Conversations.Domain.Folder", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<string>("Icon")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<bool>("IsDefault")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("Type")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Folders", "chats");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Knot.Contracts.Conversations.Domain.UserChatSettings", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Guid>("ChatId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<string>("FolderIds")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<bool>("IsMuted")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<Guid>("UserId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("UserId", "ChatId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.ToTable("UserChatSettings", "chats");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Knot.Contracts.Conversations.Domain.Chat", b =>
|
||||||
|
{
|
||||||
|
b.OwnsMany("Knot.Contracts.Conversations.Domain.ChatMember", "Members", b1 =>
|
||||||
|
{
|
||||||
|
b1.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b1.Property<Guid>("ChatId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b1.Property<bool>("IsMuted")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b1.Property<bool>("IsPinned")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b1.Property<DateTime>("JoinedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b1.Property<Guid?>("LastDeliveredMessageId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b1.Property<Guid?>("LastReadMessageId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b1.Property<long>("LastReadSequenceId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b1.Property<string>("Role")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b1.Property<Guid>("UserId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b1.HasKey("Id");
|
||||||
|
|
||||||
|
b1.HasIndex("ChatId", "UserId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b1.ToTable("ChatMembers", "chats");
|
||||||
|
|
||||||
|
b1.WithOwner()
|
||||||
|
.HasForeignKey("ChatId");
|
||||||
|
});
|
||||||
|
|
||||||
|
b.Navigation("Members");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Knot.Modules.Conversations.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddImportJobIdToChat : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<Guid>(
|
||||||
|
name: "ImportJobId",
|
||||||
|
schema: "chats",
|
||||||
|
table: "Chats",
|
||||||
|
type: "uuid",
|
||||||
|
nullable: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "ImportJobId",
|
||||||
|
schema: "chats",
|
||||||
|
table: "Chats");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,7 +23,7 @@ namespace Knot.Modules.Conversations.Migrations
|
|||||||
|
|
||||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||||
|
|
||||||
modelBuilder.Entity("Knot.Modules.Conversations.Domain.Chat", b =>
|
modelBuilder.Entity("Knot.Contracts.Conversations.Domain.Chat", b =>
|
||||||
{
|
{
|
||||||
b.Property<Guid>("Id")
|
b.Property<Guid>("Id")
|
||||||
.ValueGeneratedOnAdd()
|
.ValueGeneratedOnAdd()
|
||||||
@@ -38,6 +38,12 @@ namespace Knot.Modules.Conversations.Migrations
|
|||||||
b.Property<string>("Description")
|
b.Property<string>("Description")
|
||||||
.HasColumnType("text");
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Guid?>("ImportJobId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<bool>("IsImporting")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
b.Property<long>("LastMessageSequenceId")
|
b.Property<long>("LastMessageSequenceId")
|
||||||
.HasColumnType("bigint");
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
@@ -53,9 +59,61 @@ namespace Knot.Modules.Conversations.Migrations
|
|||||||
b.ToTable("Chats", "chats");
|
b.ToTable("Chats", "chats");
|
||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Knot.Modules.Conversations.Domain.Chat", b =>
|
modelBuilder.Entity("Knot.Contracts.Conversations.Domain.Folder", b =>
|
||||||
{
|
{
|
||||||
b.OwnsMany("Knot.Modules.Conversations.Domain.ChatMember", "Members", b1 =>
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<string>("Icon")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<bool>("IsDefault")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("Type")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Folders", "chats");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Knot.Contracts.Conversations.Domain.UserChatSettings", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Guid>("ChatId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<string>("FolderIds")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<bool>("IsMuted")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<Guid>("UserId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("UserId", "ChatId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.ToTable("UserChatSettings", "chats");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Knot.Contracts.Conversations.Domain.Chat", b =>
|
||||||
|
{
|
||||||
|
b.OwnsMany("Knot.Contracts.Conversations.Domain.ChatMember", "Members", b1 =>
|
||||||
{
|
{
|
||||||
b1.Property<Guid>("Id")
|
b1.Property<Guid>("Id")
|
||||||
.ValueGeneratedOnAdd()
|
.ValueGeneratedOnAdd()
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ using Knot.Modules.Conversations.Application.Chats.Members;
|
|||||||
using Knot.Modules.Conversations.Application.Chats.TogglePin;
|
using Knot.Modules.Conversations.Application.Chats.TogglePin;
|
||||||
using Knot.Modules.Conversations.Application.Chats.Update;
|
using Knot.Modules.Conversations.Application.Chats.Update;
|
||||||
using Knot.Modules.Conversations.Application.DTOs;
|
using Knot.Modules.Conversations.Application.DTOs;
|
||||||
using Knot.Modules.Conversations.Domain;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ public class MediaMessage : Message
|
|||||||
public MediaType MediaType { get; private set; } // image, video, file, voice
|
public MediaType MediaType { get; private set; } // image, video, file, voice
|
||||||
|
|
||||||
private List<Media> _media = new();
|
private List<Media> _media = new();
|
||||||
public override IReadOnlyCollection<Media> Media => _media.AsReadOnly();
|
public IReadOnlyCollection<Media> Media => _media.AsReadOnly();
|
||||||
|
|
||||||
private MediaMessage() : base()
|
private MediaMessage() : base()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -34,12 +34,6 @@ public abstract class Message : AggregateRoot<Guid>
|
|||||||
public abstract string Type { get; }
|
public abstract string Type { get; }
|
||||||
public abstract string? Content { get; protected set; }
|
public abstract string? Content { get; protected set; }
|
||||||
|
|
||||||
public virtual string? Quote { get; protected set; } = null;
|
|
||||||
public virtual Guid? StoryId => null;
|
|
||||||
public virtual string? StoryMediaUrl => null;
|
|
||||||
public virtual string? StoryMediaType => null;
|
|
||||||
public virtual IReadOnlyCollection<Media> Media => Array.Empty<Media>();
|
|
||||||
|
|
||||||
public bool IsEdited => HasState(MessageState.IsEdited);
|
public bool IsEdited => HasState(MessageState.IsEdited);
|
||||||
public bool IsDeleted => HasState(MessageState.IsDeleted);
|
public bool IsDeleted => HasState(MessageState.IsDeleted);
|
||||||
public bool IsDeletedForUser(Guid userId) => _deletedFor.Exists(d => d.UserId == userId);
|
public bool IsDeletedForUser(Guid userId) => _deletedFor.Exists(d => d.UserId == userId);
|
||||||
|
|||||||
@@ -112,47 +112,3 @@ public class PollMessage : Message
|
|||||||
base.Delete();
|
base.Delete();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class PollOption
|
|
||||||
{
|
|
||||||
public Guid Id { get; private set; }
|
|
||||||
public Guid PollId { get; private set; }
|
|
||||||
public string Text { get; private set; }
|
|
||||||
|
|
||||||
// Денормализованные данные для быстрой отдачи
|
|
||||||
public int VotesCount { get; private set; }
|
|
||||||
public int Percentage { get; private set; }
|
|
||||||
|
|
||||||
private PollOption() { } // EF
|
|
||||||
|
|
||||||
public PollOption(Guid id, Guid pollId, string text)
|
|
||||||
{
|
|
||||||
Id = id;
|
|
||||||
PollId = pollId;
|
|
||||||
Text = text;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void UpdateResults(int count, int percentage)
|
|
||||||
{
|
|
||||||
VotesCount = count;
|
|
||||||
Percentage = percentage;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public class PollVote
|
|
||||||
{
|
|
||||||
public Guid PollId { get; private set; }
|
|
||||||
public Guid UserId { get; private set; }
|
|
||||||
public Guid OptionId { get; private set; }
|
|
||||||
public DateTime VotedAt { get; private set; }
|
|
||||||
|
|
||||||
private PollVote() { } // EF
|
|
||||||
|
|
||||||
public PollVote(Guid pollId, Guid userId, Guid optionId, DateTime votedAt)
|
|
||||||
{
|
|
||||||
PollId = pollId;
|
|
||||||
UserId = userId;
|
|
||||||
OptionId = optionId;
|
|
||||||
VotedAt = votedAt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace Knot.Modules.Messaging.Domain;
|
||||||
|
|
||||||
|
public class PollOption
|
||||||
|
{
|
||||||
|
public Guid Id { get; private set; }
|
||||||
|
public Guid PollId { get; private set; }
|
||||||
|
public string Text { get; private set; } = string.Empty;
|
||||||
|
|
||||||
|
// Денормализованные данные для быстрой отдачи
|
||||||
|
public int VotesCount { get; private set; }
|
||||||
|
public int Percentage { get; private set; }
|
||||||
|
|
||||||
|
private PollOption() { } // EF
|
||||||
|
|
||||||
|
public PollOption(Guid id, Guid pollId, string text)
|
||||||
|
{
|
||||||
|
Id = id;
|
||||||
|
PollId = pollId;
|
||||||
|
Text = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void UpdateResults(int count, int percentage)
|
||||||
|
{
|
||||||
|
VotesCount = count;
|
||||||
|
Percentage = percentage;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace Knot.Modules.Messaging.Domain;
|
||||||
|
|
||||||
|
public class PollVote
|
||||||
|
{
|
||||||
|
public Guid PollId { get; private set; }
|
||||||
|
public Guid UserId { get; private set; }
|
||||||
|
public Guid OptionId { get; private set; }
|
||||||
|
public DateTime VotedAt { get; private set; }
|
||||||
|
|
||||||
|
private PollVote() { } // EF
|
||||||
|
|
||||||
|
public PollVote(Guid pollId, Guid userId, Guid optionId, DateTime votedAt)
|
||||||
|
{
|
||||||
|
PollId = pollId;
|
||||||
|
UserId = userId;
|
||||||
|
OptionId = optionId;
|
||||||
|
VotedAt = votedAt;
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user