Add online pinging and friendship verification features

Introduces OnlinePingingController and related integration/unit tests for user online status updates. Adds PingHandlerService with memory cache throttling, IPingHandlerService interface, and service registration. Implements VerifyFriendship service and interface for friendship validation, with exception handling. Refactors CurrentUserService for improved user ID extraction and testability. Updates ChatsHub to verify friendship before messaging. Cleans up MediaController and optimizes UsersRepository queries by removing unnecessary includes.
This commit is contained in:
Artemy
2025-07-02 19:16:49 +07:00
parent 0669614a5e
commit 565d3249e5
14 changed files with 483 additions and 32 deletions
@@ -0,0 +1,9 @@
using Govor.Core;
namespace Govor.Application.Exceptions.VerifyFriendship;
public class FriendshipException : GovorCoreException
{
public FriendshipException(string s)
:base(s) { }
}
@@ -6,21 +6,23 @@ namespace Govor.Application.Infrastructure.Extensions;
public class CurrentUserService : ICurrentUserService
{
private readonly ClaimsPrincipal _user;
private readonly IHttpContextAccessor _httpContextAccessor;
public CurrentUserService(IHttpContextAccessor httpContextAccessor)
{
_user = httpContextAccessor.HttpContext.User;
_httpContextAccessor = httpContextAccessor;
}
public Guid GetCurrentUserId()
{
var userIdClaim = _user.FindFirst("userId")?.Value;
var user = _httpContextAccessor.HttpContext?.User;
var userIdClaim = user?.FindFirst("userId")?.Value;
if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
{
throw new UnauthorizedAccessException("userID claim is missing or invalid");
}
return userId;
}
}
}
@@ -0,0 +1,6 @@
namespace Govor.Application.Interfaces;
public interface IPingHandlerService
{
Task Ping(Guid userId);
}
@@ -0,0 +1,7 @@
namespace Govor.Application.Interfaces;
public interface IVerifyFriendship
{
Task VerifyAsync(Guid targetUserId, Guid friendUserId);
Task<bool> TryVerifyAsync(Guid targetUserId, Guid friendUserId);
}
@@ -0,0 +1,34 @@
using Govor.Application.Interfaces;
using Govor.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
namespace Govor.Application.Services;
public class PingHandlerService : IPingHandlerService
{
private readonly GovorDbContext _context;
private readonly IMemoryCache _cache;
public PingHandlerService(GovorDbContext context, IMemoryCache cache)
{
_context = context;
_cache = cache;
}
public async Task Ping(Guid userId)
{
var cacheKey = $"LastPing_{userId}";
if (_cache.TryGetValue(cacheKey, out DateTime lastPing) &&
DateTime.UtcNow.Subtract(lastPing).TotalSeconds < 30)
{
return; // Пропускаем слишком частые пинги
}
await _context.Users
.Where(u => u.Id == userId)
.ExecuteUpdateAsync(u => u.SetProperty(x => x.WasOnline, DateTime.UtcNow));
_cache.Set(cacheKey, DateTime.UtcNow, TimeSpan.FromSeconds(30));
}
}
@@ -0,0 +1,55 @@
using Govor.Application.Exceptions.VerifyFriendship;
using Govor.Application.Interfaces;
using Govor.Core.Models;
using Govor.Core.Repositories.Friendships;
using Microsoft.Extensions.Logging;
namespace Govor.Application.Services;
public class VerifyFriendship : IVerifyFriendship
{
private readonly IFriendshipsRepository _friendshipsRepository;
private readonly ILogger<VerifyFriendship> _logger;
private const string FriendshipNotAcceptedError = "Friendship between user {0} and friend {1} does not exist or is not accepted.";
public VerifyFriendship(IFriendshipsRepository friendshipsRepository, ILogger<VerifyFriendship> logger = null)
{
_friendshipsRepository = friendshipsRepository ?? throw new ArgumentNullException(nameof(friendshipsRepository));
_logger = logger;
}
public async Task VerifyAsync(Guid targetUserId, Guid friendUserId)
{
if (targetUserId == Guid.Empty || friendUserId == Guid.Empty)
{
_logger?.LogWarning("Invalid user IDs provided: targetUserId={TargetUserId}, friendUserId={FriendUserId}", targetUserId, friendUserId);
throw new ArgumentException("User IDs cannot be empty.", nameof(targetUserId));
}
var friendships = await _friendshipsRepository.FindByUserIdAsync(targetUserId);
var friendship = friendships.Where(f => f.AddresseeId == friendUserId || f.RequesterId == friendUserId)?.FirstOrDefault();
if (friendship == null || friendship.Status != FriendshipStatus.Accepted)
{
var errorMessage = string.Format(FriendshipNotAcceptedError, targetUserId, friendUserId);
_logger?.LogError(errorMessage);
throw new FriendshipException(errorMessage);
}
_logger?.LogInformation("Friendship verified successfully for targetUserId={TargetUserId}, friendUserId={FriendUserId}", targetUserId, friendUserId);
}
public async Task<bool> TryVerifyAsync(Guid targetUserId, Guid friendUserId)
{
try
{
await VerifyAsync(targetUserId, friendUserId);
return true;
}
catch (FriendshipException ex)
{
return false;
}
}
}