mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-17 04:58:46 +00:00
Add reactions, reliable push & session checks
Implements message reactions and reaction packs (domain models, services, admin HTTP API, media processing via ImageSharp and limits) and adds reliable push delivery (ChatPushNotification, ChatPushDispatcher, ChatPushWorker, improved ChatNotificationService). Enhances message reading (ReadChat API, unread counts, concurrency-safe receipts) and tightens session security (access-token session validation in JWT, hub filter, SessionAuthorization). Improves SignalR behavior (session groups, reaction/channel events, hub/error mappings). Adds EF migrations, many controller fixes (Forbid handling, password API), tests (Govor.Server.Tests), docs, CI and tooling updates (Dockerfile → .NET 10, GH Actions matrix for sqlite/postgres, Govor.Server.slnx, global.json), and small infra changes (AutoMapper bump, NullPushProvider, storage/token handling).
This commit is contained in:
+80
-13
@@ -1,8 +1,12 @@
|
||||
using Govor.API.Common.SignalR.Helpers;
|
||||
using Govor.API.Common.Extensions;
|
||||
using Govor.Contracts.Requests;
|
||||
using Govor.API.Hubs.Infrastructure;
|
||||
using Govor.Application.Exceptions.VerifyFriendship;
|
||||
using Govor.Application.Infrastructure.Common;
|
||||
using Govor.Application.Messages;
|
||||
using Govor.Application.Reactions;
|
||||
using AutoMapper;
|
||||
using Govor.Application.Messages.Parameters;
|
||||
using Govor.Contracts.Requests.SignalR;
|
||||
using Govor.Contracts.Responses.SignalR;
|
||||
@@ -24,6 +28,8 @@ public class ChatsHub : Hub
|
||||
private readonly IChatNotificationService _notifier;
|
||||
private readonly IConnectionManager _connectionManager;
|
||||
private readonly INowDateTimeProvider _nowDateTimeProvider;
|
||||
private readonly IMessageReactionService _reactions;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public ChatsHub(ILogger<ChatsHub> logger,
|
||||
IMessageReadingService messageReadingService,
|
||||
@@ -33,7 +39,9 @@ public class ChatsHub : Hub
|
||||
IHubUserAccessor userAccessor,
|
||||
IChatNotificationService notifier,
|
||||
INowDateTimeProvider nowDateTimeProvider,
|
||||
IConnectionManager connectionManager)
|
||||
IConnectionManager connectionManager,
|
||||
IMessageReactionService reactions,
|
||||
IMapper mapper)
|
||||
{
|
||||
_logger = logger;
|
||||
_nowDateTimeProvider = nowDateTimeProvider;
|
||||
@@ -44,6 +52,8 @@ public class ChatsHub : Hub
|
||||
_userAccessor = userAccessor;
|
||||
_notifier = notifier;
|
||||
_connectionManager = connectionManager;
|
||||
_reactions = reactions;
|
||||
_mapper = mapper;
|
||||
}
|
||||
|
||||
public override async Task OnConnectedAsync()
|
||||
@@ -56,6 +66,12 @@ public class ChatsHub : Hub
|
||||
}
|
||||
|
||||
await _connectionManager.OnConnectedAsync(Context.ConnectionId, userId);
|
||||
if (!Guid.TryParse(Context.User?.FindFirst("sid")?.Value, out var sessionId))
|
||||
{
|
||||
Context.Abort();
|
||||
return;
|
||||
}
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, ChatHubConstants.GetSessionGroup(sessionId));
|
||||
_logger.LogInformation("User {UserId} connected", userId);
|
||||
await base.OnConnectedAsync();
|
||||
}
|
||||
@@ -84,23 +100,25 @@ public class ChatsHub : Hub
|
||||
var result = await _messageSendingService.SendMessageAsync(sendParams);
|
||||
|
||||
if (!result.IsSuccess)
|
||||
throw new InvalidOperationException(result.Exception.Message ?? "Failed to send message");
|
||||
throw result.Exception ?? new InvalidOperationException("Failed to send message");
|
||||
|
||||
var response = MapToResponse(result.Message, request.ReplyToMessageId);
|
||||
|
||||
await _notifier.NotifyMessageSentAsync(response);
|
||||
|
||||
return HubResult<UserMessageResponse>.Ok(response);
|
||||
}, request.RecipientId);
|
||||
}, request?.RecipientId ?? Guid.Empty);
|
||||
}
|
||||
|
||||
// --- Read ---
|
||||
public async Task<HubResult<MessageReadResponse>> Read(ReadMessageRequest request)
|
||||
{
|
||||
return await SafeExecute(async (userId) =>
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var result = await _messageReadingService.ReadMessageAsync(userId, request.MessageId);
|
||||
if(!result.IsSuccess)
|
||||
throw new InvalidOperationException(result.Error.ToString());
|
||||
return result.Error.ToHubResult<MessageReadResponse>();
|
||||
|
||||
var message = result.Value;
|
||||
|
||||
@@ -119,13 +137,36 @@ public class ChatsHub : Hub
|
||||
await _notifier.NotifyMessageWasReadAsync(response);
|
||||
|
||||
return HubResult<MessageReadResponse>.Ok(response);
|
||||
}, request.MessageId);
|
||||
}, request?.MessageId ?? Guid.Empty);
|
||||
}
|
||||
// --- REMOVE ---
|
||||
public async Task<HubResult<ChatReadResponse>> ReadChat(Guid chatId, ReadChatRequest request)
|
||||
{
|
||||
return await SafeExecute(async userId =>
|
||||
{
|
||||
if (request is null)
|
||||
return HubResult<ChatReadResponse>.BadRequest("Request is required.");
|
||||
var result = await _messageReadingService.ReadChatAsync(userId, chatId,
|
||||
request.RecipientType, request.MessageIds, request.UpToMessageId);
|
||||
if (result.IsFailure)
|
||||
return result.Error.ToHubResult<ChatReadResponse>();
|
||||
var read = result.Value;
|
||||
var response = new ChatReadResponse
|
||||
{
|
||||
ChatId = read.ChatId, RecipientType = read.RecipientType, ReaderId = read.ReaderId,
|
||||
ReadAt = read.ReadAt, UpToMessageId = read.UpToMessageId, UpToSentAt = read.UpToSentAt,
|
||||
MessageIds = read.MessageIds, ReadCount = read.ReadCount, UnreadCount = read.UnreadCount
|
||||
};
|
||||
await _notifier.NotifyChatReadAsync(response);
|
||||
return HubResult<ChatReadResponse>.Ok(response);
|
||||
}, chatId);
|
||||
}
|
||||
|
||||
public async Task<HubResult<MessageRemovedResponse>> Remove(RemoveMessageRequest request)
|
||||
{
|
||||
return await SafeExecute(async (userId) =>
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var deletemessage = new DeleteMessage(
|
||||
userId,
|
||||
request.MessageId,
|
||||
@@ -140,7 +181,7 @@ public class ChatsHub : Hub
|
||||
var result = await _messageRemovingService.DeleteMessageAsync(deletemessage);
|
||||
|
||||
if (!result.IsSuccess)
|
||||
throw new InvalidOperationException(result.Error.ToString());
|
||||
return result.Error.ToHubResult<MessageRemovedResponse>();
|
||||
|
||||
var notification = new MessageRemovedResponse
|
||||
{
|
||||
@@ -154,7 +195,26 @@ public class ChatsHub : Hub
|
||||
await _notifier.NotifyMessageRemovedAsync(notification);
|
||||
|
||||
return HubResult<MessageRemovedResponse>.Ok(notification);
|
||||
}, request.MessageId);
|
||||
}, request?.MessageId ?? Guid.Empty);
|
||||
}
|
||||
|
||||
public Task<HubResult<MessageReactionsChangedResponse>> React(Guid messageId, SetReactionRequest request) =>
|
||||
SafeExecute(async userId =>
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
return await ChangeReactionAsync(userId, messageId, request.ReactionId);
|
||||
}, messageId);
|
||||
|
||||
public Task<HubResult<MessageReactionsChangedResponse>> RemoveReaction(Guid messageId) =>
|
||||
SafeExecute(userId => ChangeReactionAsync(userId, messageId, null), messageId);
|
||||
|
||||
private async Task<HubResult<MessageReactionsChangedResponse>> ChangeReactionAsync(Guid userId, Guid messageId, Guid? reactionId)
|
||||
{
|
||||
var result = await _reactions.SetAsync(userId, messageId, reactionId);
|
||||
if (result.IsFailure) return result.Error.ToHubResult<MessageReactionsChangedResponse>();
|
||||
var response = _mapper.Map<MessageReactionsChangedResponse>(result.Value);
|
||||
if (result.Value.Changed) await _notifier.NotifyMessageReactionsChangedAsync(response);
|
||||
return HubResult<MessageReactionsChangedResponse>.Ok(response);
|
||||
}
|
||||
|
||||
// --- EDIT ---
|
||||
@@ -162,6 +222,7 @@ public class ChatsHub : Hub
|
||||
{
|
||||
return await SafeExecute(async (userId) =>
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var editParams = new EditMessage(
|
||||
userId,
|
||||
request.MessageId,
|
||||
@@ -171,7 +232,7 @@ public class ChatsHub : Hub
|
||||
var result = await _messageEditingService.EditMessageAsync(editParams);
|
||||
|
||||
if (!result.IsSuccess || result.OriginalMessage == null)
|
||||
throw new InvalidOperationException("Edit message error");
|
||||
throw result.Exception ?? new InvalidOperationException("Edit message error");
|
||||
|
||||
var response = new MessageEditResponse
|
||||
{
|
||||
@@ -186,20 +247,21 @@ public class ChatsHub : Hub
|
||||
await _notifier.NotifyMessageEditedAsync(response);
|
||||
|
||||
return HubResult<MessageEditResponse>.Ok(response);
|
||||
}, request.MessageId);
|
||||
}, request?.MessageId ?? Guid.Empty);
|
||||
}
|
||||
|
||||
private async Task<HubResult<T>> SafeExecute<T>(Func<Guid, Task<HubResult<T>>> action, Guid targetIdForLog)
|
||||
{
|
||||
var userId = _userAccessor.GetUserId(Context);
|
||||
var userId = Guid.Empty;
|
||||
try
|
||||
{
|
||||
userId = _userAccessor.GetUserId(Context);
|
||||
return await action(userId);
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Unauthorized: {UserId} -> {TargetId}", userId, targetIdForLog);
|
||||
return HubResult<T>.Unauthorized("You are not authorized.");
|
||||
return HubResult<T>.Forbidden("You do not have permission to perform this action.");
|
||||
}
|
||||
catch (FriendshipException)
|
||||
{
|
||||
@@ -213,6 +275,10 @@ public class ChatsHub : Hub
|
||||
{
|
||||
return HubResult<T>.NotFound("Resource not found.");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return HubResult<T>.BadRequest(ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error executing hub method for {UserId}", userId);
|
||||
@@ -222,12 +288,13 @@ public class ChatsHub : Hub
|
||||
|
||||
private void ValidateMessageRequest(MessageRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (string.IsNullOrWhiteSpace(request.EncryptedContent) &&
|
||||
(request.MediaAttachments == null || !request.MediaAttachments.Any()))
|
||||
{
|
||||
throw new ArgumentException("Message must contain content or media.");
|
||||
}
|
||||
if (request.EncryptedContent.Length > 50_000)
|
||||
if ((request.EncryptedContent?.Length ?? 0) > 50_000)
|
||||
{
|
||||
throw new ArgumentException("Message is too long.");
|
||||
}
|
||||
@@ -262,4 +329,4 @@ public class ChatsHub : Hub
|
||||
ReplyToMessageId = replyToId
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,11 @@ using Govor.Application.Friends;
|
||||
using Govor.Contracts.DTOs;
|
||||
using Govor.Contracts.Responses.SignalR;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace Govor.API.Hubs;
|
||||
|
||||
[Authorize(Roles = "Admin,User")]
|
||||
public class FriendsHub : Hub
|
||||
{
|
||||
private readonly ILogger<FriendsHub> _logger;
|
||||
@@ -194,4 +196,4 @@ public class FriendsHub : Hub
|
||||
return HubResult<object>.Error("Unexpected error! Please try later!");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,8 +7,12 @@ public static class ChatHubConstants
|
||||
public const string MessageRemoved = "MessageRemoved";
|
||||
public const string MessageEdited = "MessageEdited";
|
||||
public static string MessageRead = "MessageReaded";
|
||||
public const string ChatRead = "ChatRead";
|
||||
public const string MessageReactionsChanged = "MessageReactionsChanged";
|
||||
public const string ChannelReactionPolicyChanged = "ChannelReactionPolicyChanged";
|
||||
|
||||
public static string GetUserGroup(Guid userId) => userId.ToString();
|
||||
public static string GetSessionGroup(Guid sessionId) => $"session_{sessionId}";
|
||||
public static string GetChatGroup(Guid groupId) => $"group_{groupId}";
|
||||
public static string GetPrivateChat(Guid groupId) => $"private_{groupId}";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,130 +2,161 @@ using Govor.Application.PrivateUserChats;
|
||||
using Govor.Application.Profiles;
|
||||
using Govor.Application.PushNotifications;
|
||||
using Govor.Contracts.Responses.SignalR;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Govor.API.Hubs.Infrastructure;
|
||||
|
||||
public class ChatNotificationService : IChatNotificationService
|
||||
public class ChatNotificationService : IChatNotificationService
|
||||
{
|
||||
private readonly IHubContext<ChatsHub> _hubContext;
|
||||
private readonly IPushNotificationService _notificationService;
|
||||
private readonly IUserPrivateChatsGetterService _userPrivateChatsGetterService;
|
||||
private readonly IProfileService _profileService;
|
||||
private readonly IUserPrivateChatsGetterService _chats;
|
||||
private readonly IProfileService _profiles;
|
||||
private readonly GovorDbContext _context;
|
||||
private readonly ILogger<ChatNotificationService> _logger;
|
||||
|
||||
public ChatNotificationService(
|
||||
IHubContext<ChatsHub> hubContext,
|
||||
IPushNotificationService notificationService,
|
||||
IUserPrivateChatsGetterService userPrivateChatsGetterService,
|
||||
IProfileService profileService)
|
||||
public ChatNotificationService(IHubContext<ChatsHub> hubContext,
|
||||
IPushNotificationService notificationService, IUserPrivateChatsGetterService chats,
|
||||
IProfileService profiles, GovorDbContext context, ILogger<ChatNotificationService> logger)
|
||||
{
|
||||
_hubContext = hubContext;
|
||||
_notificationService = notificationService;
|
||||
_userPrivateChatsGetterService = userPrivateChatsGetterService;
|
||||
_profileService = profileService;
|
||||
_chats = chats;
|
||||
_profiles = profiles;
|
||||
_context = context;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task NotifyMessageSentAsync(UserMessageResponse message)
|
||||
{
|
||||
if (message.RecipientType == RecipientType.User)
|
||||
await TryNotifyAsync(() => NotifyParticipantsAsync(message.RecipientId,
|
||||
message.RecipientType, ChatHubConstants.ReceiveMessage, message));
|
||||
await TryNotifyAsync(() => NotifyUsersAsync(new[] { message.SenderId }, ChatHubConstants.MessageSent, message));
|
||||
|
||||
}
|
||||
|
||||
public async Task<bool> DeliverPushAsync(UserMessageResponse message)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _hubContext.Clients.Group(ChatHubConstants.GetPrivateChat(message.RecipientId))
|
||||
.SendAsync(ChatHubConstants.ReceiveMessage, message);
|
||||
|
||||
await NotifyMessageReceivedInPrivateChatAsync(message);
|
||||
List<Guid> recipients;
|
||||
if (message.RecipientType == RecipientType.User)
|
||||
{
|
||||
var result = await _chats.GetPrivateChatAsync(message.RecipientId);
|
||||
if (result.IsFailure)
|
||||
return result.Error.Type == ErrorType.NotFound;
|
||||
recipients = new[] { result.Value.UserAId, result.Value.UserBId }
|
||||
.Where(id => id != message.SenderId).Distinct().ToList();
|
||||
}
|
||||
else
|
||||
recipients = await _context.GroupMemberships.AsNoTracking()
|
||||
.Where(m => m.GroupId == message.RecipientId && m.UserId != message.SenderId && !m.IsBanned)
|
||||
.Select(m => m.UserId).Distinct().ToListAsync();
|
||||
|
||||
if (recipients.Count == 0)
|
||||
return true;
|
||||
var readers = await _context.MessageViews.AsNoTracking()
|
||||
.Where(v => v.MessageId == message.MessageId).Select(v => v.UserId).ToListAsync();
|
||||
recipients = recipients.Except(readers).ToList();
|
||||
if (recipients.Count == 0)
|
||||
return true;
|
||||
var profile = await _profiles.GetUserProfileAsync(message.SenderId);
|
||||
var title = profile.IsSuccess ? profile.Value.Username : "Govor";
|
||||
var content = message.EncryptedContent ?? string.Empty;
|
||||
var body = content.Length == 0 ? "Attachment" : content[..Math.Min(40, content.Length)];
|
||||
var data = new Dictionary<string, string>
|
||||
{
|
||||
["chatId"] = message.RecipientId.ToString(),
|
||||
["messageId"] = message.MessageId.ToString(),
|
||||
["isGroup"] = message.RecipientType == RecipientType.Group ? "true" : "false"
|
||||
};
|
||||
var push = await _notificationService.SendToUsersAsync(recipients, title, body,
|
||||
"chat_messages", $"chat_{message.RecipientId}", data);
|
||||
if (push.IsFailure)
|
||||
_logger.LogWarning("Push failed for message {MessageId}: {Error}",
|
||||
message.MessageId, push.Error);
|
||||
return push.IsSuccess;
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
await _hubContext.Clients.Group(ChatHubConstants.GetChatGroup(message.RecipientId))
|
||||
.SendAsync(ChatHubConstants.ReceiveMessage, message);
|
||||
_logger.LogError(ex, "Failed to deliver push for message {MessageId}", message.MessageId);
|
||||
return false;
|
||||
}
|
||||
|
||||
// await _hubContext.Clients.Group(ChatHubConstants.GetUserGroup(message.SenderId))
|
||||
// .SendAsync(ChatHubConstants.MessageSent, message);
|
||||
}
|
||||
|
||||
public async Task NotifyMessageWasReadAsync(MessageReadResponse response)
|
||||
{
|
||||
await NotifyParticipantsAsync(
|
||||
response.ReaderId,
|
||||
response.RecipientId,
|
||||
response.RecipientType,
|
||||
ChatHubConstants.MessageRead,
|
||||
response);
|
||||
// Keep the existing wire name for old clients; new clients can use MessageRead.
|
||||
await TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId,
|
||||
response.RecipientType, ChatHubConstants.MessageRead, response));
|
||||
await TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId,
|
||||
response.RecipientType, "MessageRead", response));
|
||||
}
|
||||
|
||||
private async Task NotifyMessageReceivedInPrivateChatAsync(UserMessageResponse message)
|
||||
{
|
||||
|
||||
var result = await _userPrivateChatsGetterService.GetPrivateChatAsync(message.RecipientId);
|
||||
|
||||
if(result.IsFailure)
|
||||
return;
|
||||
var privateChat = result.Value;
|
||||
|
||||
var text = message.EncryptedContent.Substring(0, Math.Min(40, message.EncryptedContent.Length));
|
||||
var userId = message.SenderId == privateChat.UserAId ? privateChat.UserBId : privateChat.UserAId;
|
||||
|
||||
var resultProf = await _profileService.GetUserProfileAsync(message.SenderId);
|
||||
|
||||
if(resultProf.IsFailure)
|
||||
return;
|
||||
var profile = resultProf.Value;
|
||||
|
||||
var title = profile.Username;
|
||||
Dictionary<string, string> data = new Dictionary<string, string>();
|
||||
|
||||
data["chatId"] = message.RecipientId.ToString();
|
||||
data["isGroup"] = message.RecipientType == RecipientType.Group ? "true" : "false";
|
||||
|
||||
await _notificationService.SendToUserAsync(
|
||||
userId,
|
||||
title,
|
||||
text,
|
||||
"chat_messages",
|
||||
$"private_chat_{message.RecipientId}",
|
||||
data);
|
||||
}
|
||||
|
||||
public async Task NotifyMessageRemovedAsync(MessageRemovedResponse response)
|
||||
{
|
||||
await NotifyParticipantsAsync(
|
||||
response.SenderId,
|
||||
response.RecipientId,
|
||||
response.RecipientType,
|
||||
ChatHubConstants.MessageRemoved,
|
||||
response);
|
||||
}
|
||||
public Task NotifyChatReadAsync(ChatReadResponse response) =>
|
||||
TryNotifyAsync(() => NotifyParticipantsAsync(response.ChatId,
|
||||
response.RecipientType, ChatHubConstants.ChatRead, response));
|
||||
|
||||
public async Task NotifyMessageEditedAsync(MessageEditResponse response)
|
||||
{
|
||||
await NotifyParticipantsAsync(
|
||||
response.EditorId,
|
||||
response.RecipientId,
|
||||
response.RecipientType,
|
||||
ChatHubConstants.MessageEdited,
|
||||
response);
|
||||
}
|
||||
|
||||
private async Task NotifyParticipantsAsync(Guid initiatorId, Guid targetId, RecipientType type, string method, object payload)
|
||||
public Task NotifyMessageReactionsChangedAsync(MessageReactionsChangedResponse response) =>
|
||||
TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId,
|
||||
response.RecipientType, ChatHubConstants.MessageReactionsChanged, response));
|
||||
|
||||
public Task NotifyChannelReactionPolicyChangedAsync(ChannelReactionPolicyResponse response) =>
|
||||
TryNotifyAsync(() => NotifyParticipantsAsync(response.GroupId,
|
||||
RecipientType.Group, ChatHubConstants.ChannelReactionPolicyChanged, response));
|
||||
|
||||
public Task NotifyMessageRemovedAsync(MessageRemovedResponse response) =>
|
||||
TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId,
|
||||
response.RecipientType, ChatHubConstants.MessageRemoved, response));
|
||||
|
||||
public Task NotifyMessageEditedAsync(MessageEditResponse response) =>
|
||||
TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId,
|
||||
response.RecipientType, ChatHubConstants.MessageEdited, response));
|
||||
|
||||
private async Task NotifyParticipantsAsync(Guid chatId, RecipientType type, string method, object payload)
|
||||
{
|
||||
// Resolve current participants instead of treating a chat ID as a user ID.
|
||||
// Deliver only to active sessions, including all of a participant's devices.
|
||||
List<Guid> participants;
|
||||
if (type == RecipientType.User)
|
||||
{
|
||||
await _hubContext.Clients.Group(ChatHubConstants.GetUserGroup(initiatorId))
|
||||
.SendAsync(method, payload);
|
||||
|
||||
if (initiatorId != targetId)
|
||||
{
|
||||
await _hubContext.Clients.Group(ChatHubConstants.GetUserGroup(targetId))
|
||||
.SendAsync(method, payload);
|
||||
}
|
||||
var result = await _chats.GetPrivateChatAsync(chatId);
|
||||
if (result.IsFailure)
|
||||
return;
|
||||
participants = new[] { result.Value.UserAId, result.Value.UserBId }.Distinct().ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
// to groups
|
||||
await _hubContext.Clients.Group(ChatHubConstants.GetChatGroup(targetId))
|
||||
participants = await _context.GroupMemberships.AsNoTracking()
|
||||
.Where(m => m.GroupId == chatId && !m.IsBanned).Select(m => m.UserId).Distinct().ToListAsync();
|
||||
|
||||
if (participants.Count > 0)
|
||||
await NotifyUsersAsync(participants, method, payload);
|
||||
}
|
||||
|
||||
private async Task NotifyUsersAsync(IEnumerable<Guid> users, string method, object payload)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
var sessions = await _context.UserSessions.AsNoTracking()
|
||||
.Where(s => users.Contains(s.UserId) && !s.IsRevoked && s.ExpiresAt > now)
|
||||
.Select(s => s.Id).ToListAsync();
|
||||
if (sessions.Count > 0)
|
||||
await _hubContext.Clients.Groups(sessions.Select(ChatHubConstants.GetSessionGroup).ToList())
|
||||
.SendAsync(method, payload);
|
||||
}
|
||||
|
||||
private async Task TryNotifyAsync(Func<Task> notify)
|
||||
{
|
||||
try
|
||||
{
|
||||
await notify();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to deliver chat notification; clients can resync from history.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
using Govor.Application.Infrastructure.Common;
|
||||
using Govor.Contracts.Responses.SignalR;
|
||||
using Govor.Domain;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Govor.API.Hubs.Infrastructure;
|
||||
|
||||
public class ChatPushDispatcher(GovorDbContext context, IChatNotificationService notifier,
|
||||
INowDateTimeProvider dateTimeProvider)
|
||||
{
|
||||
public async Task DispatchAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var now = dateTimeProvider.Now;
|
||||
var pending = await context.ChatPushNotifications.AsNoTracking()
|
||||
.Where(n => n.NextAttemptAt <= now).OrderBy(n => n.NextAttemptAt)
|
||||
.Take(20).Select(n => n.MessageId).ToListAsync(cancellationToken);
|
||||
|
||||
foreach (var id in pending)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// Conditional update claims a two-minute lease, including across server instances.
|
||||
// An interrupted worker leaves a retryable row rather than losing the notification.
|
||||
var claimed = await context.ChatPushNotifications
|
||||
.Where(n => n.MessageId == id && n.NextAttemptAt <= now)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(n => n.NextAttemptAt, now.AddMinutes(2))
|
||||
.SetProperty(n => n.Attempts, n => n.Attempts + 1), cancellationToken);
|
||||
if (claimed == 0)
|
||||
continue;
|
||||
|
||||
var message = await context.Messages.AsNoTracking()
|
||||
.Where(m => m.Id == id).Select(m => new UserMessageResponse
|
||||
{
|
||||
MessageId = m.Id, SenderId = m.SenderId, RecipientId = m.RecipientId,
|
||||
RecipientType = m.RecipientType, EncryptedContent = m.EncryptedContent,
|
||||
SentAt = m.SentAt, ReplyToMessageId = m.ReplyToMessageId
|
||||
}).FirstOrDefaultAsync(cancellationToken);
|
||||
var delivered = message is null || await notifier.DeliverPushAsync(message);
|
||||
if (delivered)
|
||||
await context.ChatPushNotifications.Where(n => n.MessageId == id)
|
||||
.ExecuteDeleteAsync(cancellationToken);
|
||||
else
|
||||
{
|
||||
var attempts = await context.ChatPushNotifications.Where(n => n.MessageId == id)
|
||||
.Select(n => n.Attempts).FirstOrDefaultAsync(cancellationToken);
|
||||
var retryAt = dateTimeProvider.Now.AddSeconds(Math.Min(300, Math.Pow(2, Math.Min(attempts, 9))));
|
||||
await context.ChatPushNotifications.Where(n => n.MessageId == id)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(n => n.NextAttemptAt, retryAt), cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace Govor.API.Hubs.Infrastructure;
|
||||
|
||||
public class ChatPushWorker(IServiceScopeFactory scopeFactory, ILogger<ChatPushWorker> logger) : BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var scope = scopeFactory.CreateScope();
|
||||
await scope.ServiceProvider.GetRequiredService<ChatPushDispatcher>().DispatchAsync(stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Chat push dispatch failed; pending notifications will be retried.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,11 @@ namespace Govor.API.Hubs.Infrastructure;
|
||||
public interface IChatNotificationService
|
||||
{
|
||||
Task NotifyMessageSentAsync(UserMessageResponse message);
|
||||
Task<bool> DeliverPushAsync(UserMessageResponse message);
|
||||
Task NotifyMessageWasReadAsync(MessageReadResponse response);
|
||||
Task NotifyChatReadAsync(ChatReadResponse response);
|
||||
Task NotifyMessageReactionsChangedAsync(MessageReactionsChangedResponse response);
|
||||
Task NotifyChannelReactionPolicyChangedAsync(ChannelReactionPolicyResponse response);
|
||||
Task NotifyMessageRemovedAsync(MessageRemovedResponse response);
|
||||
Task NotifyMessageEditedAsync(MessageEditResponse response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Govor.API.Common.SignalR.Helpers;
|
||||
using Govor.Application.Friends;
|
||||
using Govor.API.Common.Extensions;
|
||||
using Govor.Application.Medias;
|
||||
using Govor.Application.Profiles;
|
||||
using Govor.Application.Synching;
|
||||
@@ -101,9 +102,11 @@ public sealed class ProfileHub : Hub
|
||||
|
||||
try
|
||||
{
|
||||
await _profileService.SetDescription(
|
||||
var result = await _profileService.SetDescription(
|
||||
description,
|
||||
userId);
|
||||
if (result.IsFailure)
|
||||
return result.Error.ToHubResult<bool>();
|
||||
|
||||
var payload = new DescriptionUpdatePayload
|
||||
{
|
||||
@@ -146,9 +149,11 @@ public sealed class ProfileHub : Hub
|
||||
return HubResult<bool>.BadRequest(
|
||||
"Invalid icon id.");
|
||||
|
||||
await _profileService.SetNewIcon(
|
||||
var result = await _profileService.SetNewIcon(
|
||||
userId,
|
||||
iconId);
|
||||
if (result.IsFailure)
|
||||
return result.Error.ToHubResult<bool>();
|
||||
|
||||
var payload = new AvatarUpdatePayload
|
||||
{
|
||||
@@ -265,4 +270,4 @@ public sealed class ProfileHub : Hub
|
||||
{
|
||||
return $"{UserGroupPrefix}{userId}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user