mirror of
https://github.com/Govor-team/Govor.git
synced 2026-09-20 09:53:12 +00:00
Stable server
was added removing messages many fixes bugs and moving to result pattern from throwing exceptions
This commit is contained in:
@@ -91,17 +91,27 @@ public class ChatsHub : Hub
|
||||
{
|
||||
return await SafeExecute(async (userId) =>
|
||||
{
|
||||
var result = await _messageRemovingService.DeleteMessageAsync(new DeleteMessage(userId, request.MessageId));
|
||||
var result = await _messageRemovingService.DeleteMessageAsync(
|
||||
new DeleteMessage(
|
||||
userId,
|
||||
request.MessageId,
|
||||
ForceRemove: request.RequestType switch
|
||||
{
|
||||
RemoveMessageRequestType.HideForMe => false,
|
||||
RemoveMessageRequestType.ForceRemove => true,
|
||||
_ => false
|
||||
})
|
||||
);
|
||||
|
||||
if (!result.IsSuccess || result.OriginalMessage == null)
|
||||
throw new InvalidOperationException("Message deletion failed");
|
||||
if (!result.IsSuccess)
|
||||
throw new InvalidOperationException(result.Error.ToString());
|
||||
|
||||
var notification = new MessageRemovedResponse
|
||||
{
|
||||
MessageId = request.MessageId,
|
||||
SenderId = result.OriginalMessage.SenderId,
|
||||
RecipientId = result.OriginalMessage.RecipientId,
|
||||
RecipientType = result.OriginalMessage.RecipientType
|
||||
SenderId = result.Value.SenderId,
|
||||
RecipientId = result.Value.RecipientId,
|
||||
RecipientType = result.Value.RecipientType
|
||||
};
|
||||
|
||||
await _notifier.NotifyMessageRemovedAsync(notification);
|
||||
|
||||
@@ -82,7 +82,7 @@ public class FriendsHub : Hub
|
||||
return HubResult<object>.Error(result.Error.ToString());
|
||||
|
||||
var friendship = result.Value;
|
||||
var dto = _mapper.Map<FriendshipDto>(friendship);
|
||||
var dto = _mapper.Map<FriendshipDto>(friendship);
|
||||
|
||||
await Clients.Group(targetUserId.ToString())
|
||||
.SendAsync("FriendRequestReceived", dto);
|
||||
@@ -127,7 +127,7 @@ public class FriendsHub : Hub
|
||||
|
||||
var friendship = result.Value;
|
||||
|
||||
var dto = _mapper.Map<FriendshipDto>(friendship);
|
||||
var dto = _mapper.Map<FriendshipDto>(friendship);
|
||||
|
||||
await Clients.Group(userId.ToString())
|
||||
.SendAsync("FriendRequestAccepted", dto);
|
||||
|
||||
+170
-78
@@ -11,24 +11,29 @@ using Microsoft.AspNetCore.SignalR;
|
||||
namespace Govor.API.Hubs;
|
||||
|
||||
[Authorize]
|
||||
public class ProfileHub : Hub
|
||||
public sealed class ProfileHub : Hub
|
||||
{
|
||||
private readonly IFriendshipService _friendsService;
|
||||
private const string UserGroupPrefix = "user:";
|
||||
|
||||
private const string DescriptionUpdatedEvent = "DescriptionUpdated";
|
||||
private const string AvatarUpdatedEvent = "AvatarUpdated";
|
||||
|
||||
private readonly IFriendshipService _friendshipService;
|
||||
private readonly IProfileService _profileService;
|
||||
private readonly IHubUserAccessor _userAccessor;
|
||||
private readonly ISynchingService _synchingService;
|
||||
private readonly IMediaService _mediaService;
|
||||
private readonly ILogger<ProfileHub> _logger;
|
||||
private readonly IMediaService _mediaService;
|
||||
|
||||
|
||||
public ProfileHub(
|
||||
IFriendshipService friendsService,
|
||||
IFriendshipService friendshipService,
|
||||
IProfileService profileService,
|
||||
IHubUserAccessor userAccessor,
|
||||
ISynchingService synchingService,
|
||||
IMediaService mediaService,
|
||||
ILogger<ProfileHub> logger)
|
||||
{
|
||||
_friendsService = friendsService;
|
||||
_friendshipService = friendshipService;
|
||||
_profileService = profileService;
|
||||
_userAccessor = userAccessor;
|
||||
_synchingService = synchingService;
|
||||
@@ -39,32 +44,66 @@ public class ProfileHub : Hub
|
||||
public override async Task OnConnectedAsync()
|
||||
{
|
||||
var userId = _userAccessor.GetUserId(Context);
|
||||
var groupName = GetUserGroup(userId);
|
||||
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, $"user:{userId}");
|
||||
await Groups.AddToGroupAsync(
|
||||
Context.ConnectionId,
|
||||
groupName);
|
||||
|
||||
_logger.LogDebug(
|
||||
"User {UserId} connected to ProfileHub with connection {ConnectionId}",
|
||||
userId,
|
||||
Context.ConnectionId);
|
||||
|
||||
await base.OnConnectedAsync();
|
||||
}
|
||||
|
||||
public override async Task OnDisconnectedAsync(Exception exception)
|
||||
public override async Task OnDisconnectedAsync(Exception? exception)
|
||||
{
|
||||
var userId = _userAccessor.GetUserId(Context);
|
||||
|
||||
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"user-{userId}");
|
||||
|
||||
var groupName = GetUserGroup(userId);
|
||||
|
||||
await Groups.RemoveFromGroupAsync(
|
||||
Context.ConnectionId,
|
||||
groupName);
|
||||
|
||||
if (exception is not null)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
exception,
|
||||
"User {UserId} disconnected from ProfileHub with connection {ConnectionId}",
|
||||
userId,
|
||||
Context.ConnectionId);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"User {UserId} disconnected from ProfileHub with connection {ConnectionId}",
|
||||
userId,
|
||||
Context.ConnectionId);
|
||||
}
|
||||
|
||||
await base.OnDisconnectedAsync(exception);
|
||||
}
|
||||
|
||||
public async Task<HubResult<bool>> SetDescription(string description)
|
||||
|
||||
public async Task<HubResult<bool>> SetDescription(string? description)
|
||||
{
|
||||
if (description is null)
|
||||
return HubResult<bool>.BadRequest("Description cannot be null.");
|
||||
|
||||
description = _synchingService.NormalizeNewlines(description);
|
||||
|
||||
if (description.Length > 500)
|
||||
return HubResult<bool>.Error("Description length exceeded.");
|
||||
return HubResult<bool>.BadRequest(
|
||||
"Description length exceeded.");
|
||||
|
||||
var userId = _userAccessor.GetUserId(Context);
|
||||
|
||||
try
|
||||
{
|
||||
description = _synchingService.NormalizeNewlines(description);
|
||||
await _profileService.SetDescription(description, userId);
|
||||
await _profileService.SetDescription(
|
||||
description,
|
||||
userId);
|
||||
|
||||
var payload = new DescriptionUpdatePayload
|
||||
{
|
||||
@@ -72,105 +111,158 @@ public class ProfileHub : Hub
|
||||
Description = description
|
||||
};
|
||||
|
||||
await NotifyProfileUpdatedAsync(userId, "DescriptionUpdated", payload);
|
||||
await NotifyProfileUpdatedAsync(
|
||||
userId,
|
||||
DescriptionUpdatedEvent,
|
||||
payload);
|
||||
|
||||
return HubResult<bool>.Ok(true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to update description for user {UserId}", userId);
|
||||
return HubResult<bool>.Error("Server error.");
|
||||
_logger.LogError(
|
||||
ex,
|
||||
"Failed to update description for user {UserId}",
|
||||
userId);
|
||||
|
||||
return HubResult<bool>.Error(
|
||||
"Server error.");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<HubResult<bool>> SetAvatar(Guid iconId)
|
||||
{
|
||||
if (iconId == Guid.Empty)
|
||||
return HubResult<bool>.BadRequest(
|
||||
"Invalid icon id.");
|
||||
|
||||
var userId = _userAccessor.GetUserId(Context);
|
||||
|
||||
try
|
||||
{
|
||||
if (iconId == Guid.Empty || !await _mediaService.HasMediaAsync(iconId))
|
||||
return HubResult<bool>.BadRequest("Invalid icon id.");
|
||||
var mediaExists = await _mediaService.HasMediaAsync(iconId);
|
||||
|
||||
await _profileService.SetNewIcon(userId, iconId);
|
||||
if (!mediaExists)
|
||||
return HubResult<bool>.BadRequest(
|
||||
"Invalid icon id.");
|
||||
|
||||
var payload = new AvatarUpdatePayload(){UserId = userId, IconId = iconId};
|
||||
await _profileService.SetNewIcon(
|
||||
userId,
|
||||
iconId);
|
||||
|
||||
await NotifyProfileUpdatedAsync(userId, "AvatarUpdated", payload);
|
||||
var payload = new AvatarUpdatePayload
|
||||
{
|
||||
UserId = userId,
|
||||
IconId = iconId
|
||||
};
|
||||
|
||||
await NotifyProfileUpdatedAsync(
|
||||
userId,
|
||||
AvatarUpdatedEvent,
|
||||
payload);
|
||||
|
||||
return HubResult<bool>.Ok(true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "An error occurred while updating the user's {userId} avatar {iconId}", userId, iconId);
|
||||
return HubResult<bool>.Error("An unaccounted error on the server!");
|
||||
_logger.LogError(
|
||||
ex,
|
||||
"Failed to update avatar for user {UserId}. IconId: {IconId}",
|
||||
userId,
|
||||
iconId);
|
||||
|
||||
return HubResult<bool>.Error(
|
||||
"Server error.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private async Task NotifyProfileUpdatedAsync(
|
||||
Guid UserId,
|
||||
Guid userId,
|
||||
string eventName,
|
||||
object payload)
|
||||
{
|
||||
try
|
||||
{
|
||||
var recipients = new HashSet<Guid>();
|
||||
var recipients = await GetProfileUpdateRecipientsAsync(userId);
|
||||
|
||||
// 1. Friends
|
||||
try
|
||||
{
|
||||
var friends = await _friendsService.GetFriendsAsync(UserId);
|
||||
recipients.UnionWith(friends.Select(f => f.Id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "User has no friends for user {userId}", UserId);
|
||||
}
|
||||
|
||||
// 2. (pending)
|
||||
try
|
||||
{
|
||||
var potentialFriends = await _friendsService.GetPotentialFriendsAsync(UserId);
|
||||
recipients.UnionWith(potentialFriends.Select(p => p.Id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "User has potential friends for user {userId}", UserId);
|
||||
}
|
||||
if (recipients.Count == 0)
|
||||
return;
|
||||
|
||||
var groups = recipients
|
||||
.Select(GetUserGroup)
|
||||
.ToArray();
|
||||
|
||||
// 3. groups
|
||||
/*var groups = await _groupsRepository.GetByUserIdAsync(authorUserId);
|
||||
foreach (var group in groups)
|
||||
await Clients
|
||||
.Groups(groups)
|
||||
.SendAsync(eventName, payload);
|
||||
|
||||
_logger.LogDebug(
|
||||
"Profile update {EventName} for user {UserId} sent to {RecipientCount} users",
|
||||
eventName,
|
||||
userId,
|
||||
recipients.Count);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(
|
||||
ex,
|
||||
"Failed to notify profile update for user {UserId}",
|
||||
userId);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<HashSet<Guid>> GetProfileUpdateRecipientsAsync(
|
||||
Guid userId)
|
||||
{
|
||||
var recipients = new HashSet<Guid>();
|
||||
|
||||
// User himself.
|
||||
recipients.Add(userId);
|
||||
|
||||
// Friends.
|
||||
try
|
||||
{
|
||||
var friends = await _friendshipService.GetFriendsAsync(userId);
|
||||
|
||||
foreach (var friend in friends)
|
||||
{
|
||||
var members =
|
||||
await _groupsRepository.Get(group.Id);
|
||||
|
||||
recipients.UnionWith(members.Select(m => m.Id));
|
||||
}*/
|
||||
|
||||
recipients.Add(UserId);
|
||||
|
||||
// 5.
|
||||
// recipients.RemoveWhere(id =>
|
||||
// !_profileVisibilityService.CanViewProfile(id, authorUserId));
|
||||
|
||||
|
||||
// 6. 1 user = 1 event
|
||||
var recipientsStrings =
|
||||
recipients.Select(r => $"user:{r}").ToList();
|
||||
|
||||
foreach (var recipientId in recipients)
|
||||
{
|
||||
await Clients.Groups(recipientsStrings)
|
||||
.SendAsync(eventName, payload);
|
||||
if (friend.Id != Guid.Empty)
|
||||
recipients.Add(friend.Id);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"Failed to notify profile update for user {UserId}",
|
||||
UserId);
|
||||
_logger.LogWarning(
|
||||
ex,
|
||||
"Failed to get friends for user {UserId}",
|
||||
userId);
|
||||
}
|
||||
|
||||
// Potential friends.
|
||||
try
|
||||
{
|
||||
var potentialFriends =
|
||||
await _friendshipService.GetPotentialFriendsAsync(userId);
|
||||
|
||||
foreach (var potentialFriend in potentialFriends)
|
||||
{
|
||||
if (potentialFriend.Id != Guid.Empty)
|
||||
recipients.Add(potentialFriend.Id);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
ex,
|
||||
"Failed to get potential friends for user {UserId}",
|
||||
userId);
|
||||
}
|
||||
|
||||
return recipients;
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetUserGroup(Guid userId)
|
||||
{
|
||||
return $"{UserGroupPrefix}{userId}";
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user