technical edits

This commit is contained in:
Artemy
2025-12-12 17:23:01 +07:00
parent bf2aca40d3
commit 7e6f914878
23 changed files with 461 additions and 114 deletions
@@ -1,24 +1,35 @@
using AutoMapper; using System.Text;
using AutoMapper;
using Govor.API.Controllers; using Govor.API.Controllers;
using Govor.API.Hubs;
using Govor.Application.Interfaces; using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Infrastructure.Extensions; using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Interfaces.Medias; using Govor.Application.Interfaces.Medias;
using Govor.Application.Profiles; using Govor.Application.Profiles;
using Govor.Contracts.DTOs; using Govor.Contracts.DTOs;
using Govor.Contracts.Requests;
using Govor.Core.Models;
using Govor.Core.Models.Messages;
using Govor.Data.Repositories.Exceptions; using Govor.Data.Repositories.Exceptions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Moq; using Moq;
using Newtonsoft.Json.Linq;
namespace Govor.API.Tests; namespace Govor.API.Tests;
[TestFixture] [TestFixture]
public class ProfileControllerTests public class ProfileControllerTests
{ {
private Mock<ILogger<ProfileController>> _mockLogger = null!; private Mock<ILogger<ProfileController>> _mockLogger = null!;
private Mock<IMediaService> _mockMediaService = null!; private Mock<IMediaService> _mockMediaService = null!;
private Mock<IProfileService> _mockProfileService = null!; private Mock<IProfileService> _mockProfileService = null!;
private Mock<ICurrentUserService> _mockCurrentUserService = null!; private Mock<ICurrentUserService> _mockCurrentUserService = null!;
private Mock<IHubContext<ProfileHub>> _mockProfileHubContext = null!;
private Mock<IHubClients> _mockClients = null!;
private Mock<IClientProxy> _mockClientProxy = null!;
private Mock<IMapper> _mockMapper = null!; private Mock<IMapper> _mockMapper = null!;
private ProfileController _controller = null!; private ProfileController _controller = null!;
@@ -32,18 +43,162 @@ public class ProfileControllerTests
_mockProfileService = new Mock<IProfileService>(); _mockProfileService = new Mock<IProfileService>();
_mockCurrentUserService = new Mock<ICurrentUserService>(); _mockCurrentUserService = new Mock<ICurrentUserService>();
_mockMapper = new Mock<IMapper>(); _mockMapper = new Mock<IMapper>();
_mockProfileHubContext = new Mock<IHubContext<ProfileHub>>();
_mockClients = new Mock<IHubClients>();
_mockClientProxy = new Mock<IClientProxy>();
_mockProfileHubContext.Setup(x => x.Clients).Returns(_mockClients.Object);
_mockClients.Setup(x => x.All).Returns(_mockClientProxy.Object);
_mockClientProxy.Setup(x => x.SendCoreAsync(It.IsAny<string>(), It.IsAny<object?[]?>(), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
_controller = new ProfileController( _controller = new ProfileController(
_mockLogger.Object, _mockLogger.Object,
_mockMediaService.Object, _mockMediaService.Object,
_mockProfileService.Object, _mockProfileService.Object,
_mockCurrentUserService.Object, _mockCurrentUserService.Object,
_mockProfileHubContext.Object,
_mockMapper.Object); _mockMapper.Object);
_userId = Guid.NewGuid(); _userId = Guid.NewGuid();
_mockCurrentUserService.Setup(x => x.GetCurrentUserId()).Returns(_userId); _mockCurrentUserService.Setup(x => x.GetCurrentUserId()).Returns(_userId);
} }
[Test]
public async Task UploadAvatar_ReturnsBadRequest_WhenFileIsEmpty()
{
// Arrange
var request = new AvatarUploadRequest
{
FromFile = null
};
// Act
var result = await _controller.UploadAvatar(request);
// Assert
Assert.That(result, Is.InstanceOf<BadRequestObjectResult>());
var badRequestResult = (BadRequestObjectResult)result;
Assert.That(badRequestResult.Value, Is.EqualTo("File is empty."));
_mockMediaService.Verify(s => s.UploadMediaAsync(It.IsAny<Media>()), Times.Never);
}
[Test]
public async Task UploadAvatar_ReturnsBadRequest_WhenFileLengthIsZero()
{
// Arrange
var mockFile = new Mock<IFormFile>();
mockFile.Setup(f => f.Length).Returns(0);
var request = new AvatarUploadRequest
{
FromFile = mockFile.Object
};
// Act
var result = await _controller.UploadAvatar(request);
// Assert
Assert.That(result, Is.InstanceOf<BadRequestObjectResult>());
var badRequestResult = (BadRequestObjectResult)result;
Assert.That(badRequestResult.Value, Is.EqualTo("File is empty."));
_mockMediaService.Verify(s => s.UploadMediaAsync(It.IsAny<Media>()), Times.Never);
}
[Test]
public async Task UploadAvatar_ReturnsOkAndPerformsAllActions_WhenFileIsValid()
{
// Arrange
var mediaId = Guid.NewGuid();
var expectedMediaInfo = new MediaUploadResult(mediaId, $"/media/{mediaId}");
var fileName = "test_avatar.jpg";
var fileContent = "This is a test image content";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(fileContent));
var mockFile = new Mock<IFormFile>();
mockFile.Setup(f => f.FileName).Returns(fileName);
mockFile.Setup(f => f.Length).Returns(stream.Length);
mockFile.Setup(f => f.OpenReadStream()).Returns(stream);
mockFile.Setup(f => f.CopyToAsync(It.IsAny<Stream>(), It.IsAny<CancellationToken>()))
.Callback<Stream, CancellationToken>((s, t) => stream.CopyTo(s)); // Для ReadFileAsync
var request = new AvatarUploadRequest
{
FromFile = mockFile.Object,
Type = MediaType.Image,
MimeType = "image/jpeg"
};
_mockMediaService.Setup(s => s.UploadMediaAsync(It.IsAny<Media>()))
.ReturnsAsync(expectedMediaInfo);
_mockProfileService.Setup(s => s.SetNewIcon(_userId, mediaId))
.Returns(Task.CompletedTask);
// Act
var result = await _controller.UploadAvatar(request);
// Assert
Assert.That(result, Is.InstanceOf<OkObjectResult>());
var okResult = (OkObjectResult)result;
Assert.That(okResult.StatusCode, Is.EqualTo(200));
Assert.That(okResult.Value, Is.EqualTo(expectedMediaInfo));
mockFile.Verify(f => f.CopyToAsync(It.IsAny<Stream>(), It.IsAny<CancellationToken>()), Times.Once);
_mockMediaService.Verify(s => s.UploadMediaAsync(It.Is<Media>(m =>
m.OwnerId == _userId &&
m.OwnerType == MediaOwnerType.Avatar &&
m.FileName == fileName
)), Times.Once);
_mockProfileService.Verify(s => s.SetNewIcon(_userId, mediaId), Times.Once);
_mockClientProxy.Verify(
c => c.SendCoreAsync("AvatarUpdated", It.Is<object?[]>(
args => args.Length == 1 &&
JObject.FromObject(args[0]!).Value<Guid>("userId") == _userId &&
JObject.FromObject(args[0]!).Value<Guid>("iconId") == mediaId
), It.IsAny<CancellationToken>()),
Times.Once,
"Hub SendAsync must be called to notify clients."
);
}
[Test]
public async Task UploadAvatar_ReturnsInternalServerError_WhenMediaServiceFails()
{
// Arrange
var mockFile = new Mock<IFormFile>();
mockFile.Setup(f => f.Length).Returns(100);
mockFile.Setup(f => f.OpenReadStream()).Returns(new MemoryStream(Encoding.UTF8.GetBytes("test")));
var request = new AvatarUploadRequest { FromFile = mockFile.Object };
_mockMediaService.Setup(s => s.UploadMediaAsync(It.IsAny<Media>()))
.ThrowsAsync(new System.Exception("Simulated upload failure"));
// Act
var result = await _controller.UploadAvatar(request);
// Assert
Assert.That(result, Is.InstanceOf<ObjectResult>());
var objectResult = (ObjectResult)result;
Assert.That(objectResult.StatusCode, Is.EqualTo(500));
_mockProfileService.Verify(s => s.SetNewIcon(It.IsAny<Guid>(), It.IsAny<Guid>()), Times.Never);
_mockClientProxy.Verify(
c => c.SendCoreAsync(It.IsAny<string>(), It.IsAny<object?[]?>(), It.IsAny<CancellationToken>()),
Times.Never,
"The Hub should not be called in case of a service error."
);
}
[Test] [Test]
public async Task DowloadProfile_ReturnsOk_WhenProfileExists() public async Task DowloadProfile_ReturnsOk_WhenProfileExists()
{ {
@@ -71,7 +226,7 @@ public class ProfileControllerTests
.Returns(userProfileDto); .Returns(userProfileDto);
// Act // Act
var result = await _controller.DowloadProfile(); var result = await _controller.DownloadProfile();
// Assert // Assert
var okResult = result as OkObjectResult; var okResult = result as OkObjectResult;
@@ -80,22 +235,6 @@ public class ProfileControllerTests
Assert.That(okResult.Value, Is.EqualTo(userProfileDto)); Assert.That(okResult.Value, Is.EqualTo(userProfileDto));
} }
[Test]
public async Task DowloadProfile_ReturnsNotFound_WhenProfileIsNull()
{
// Arrange
_mockProfileService.Setup(s => s.GetUserProfileAsync(_userId))
.ReturnsAsync((UserProfile?)null);
// Act
var result = await _controller.DowloadProfile();
// Assert
var notFoundResult = result as NotFoundObjectResult;
Assert.That(notFoundResult, Is.Not.Null);
Assert.That(notFoundResult!.Value, Is.EqualTo("Profile not found"));
}
[Test] [Test]
public async Task DowloadProfile_ReturnsForbid_WhenUnauthorizedAccessExceptionThrown() public async Task DowloadProfile_ReturnsForbid_WhenUnauthorizedAccessExceptionThrown()
{ {
@@ -104,7 +243,7 @@ public class ProfileControllerTests
.ThrowsAsync(new UnauthorizedAccessException("Access denied")); .ThrowsAsync(new UnauthorizedAccessException("Access denied"));
// Act // Act
var result = await _controller.DowloadProfile(); var result = await _controller.DownloadProfile();
// Assert // Assert
Assert.That(result, Is.InstanceOf<ForbidResult>()); Assert.That(result, Is.InstanceOf<ForbidResult>());
@@ -115,15 +254,15 @@ public class ProfileControllerTests
{ {
// Arrange // Arrange
_mockProfileService.Setup(s => s.GetUserProfileAsync(_userId)) _mockProfileService.Setup(s => s.GetUserProfileAsync(_userId))
.ThrowsAsync(new NotFoundException("User not found")); .ThrowsAsync(new NotFoundException("Cannot find profile"));
// Act // Act
var result = await _controller.DowloadProfile(); var result = await _controller.DownloadProfile();
// Assert // Assert
var badRequest = result as BadRequestObjectResult; var notFoundResult = result as NotFoundObjectResult;
Assert.That(badRequest, Is.Not.Null); Assert.That(notFoundResult, Is.Not.Null);
Assert.That(badRequest!.Value, Is.EqualTo("User not found")); Assert.That(notFoundResult!.Value, Is.EqualTo("Profile not found"));
} }
[Test] [Test]
@@ -134,7 +273,7 @@ public class ProfileControllerTests
.ThrowsAsync(new Exception("Unexpected error")); .ThrowsAsync(new Exception("Unexpected error"));
// Act // Act
var result = await _controller.DowloadProfile(); var result = await _controller.DownloadProfile();
// Assert // Assert
var objectResult = result as ObjectResult; var objectResult = result as ObjectResult;
@@ -30,7 +30,7 @@ public class AuthController : Controller
_logger = logger; _logger = logger;
} }
[RequireHttps] //[RequireHttps]
[HttpPost("register")]// api/auth/register [HttpPost("register")]// api/auth/register
public async Task<IActionResult> Register([FromBody] RegistrationRequest registrationRequest) public async Task<IActionResult> Register([FromBody] RegistrationRequest registrationRequest)
{ {
@@ -74,7 +74,7 @@ public class AuthController : Controller
} }
} }
[RequireHttps] //[RequireHttps]
[HttpPost("login")]// api/auth/login [HttpPost("login")]// api/auth/login
public async Task<IActionResult> Login([FromBody] LoginRequest loginRequest) public async Task<IActionResult> Login([FromBody] LoginRequest loginRequest)
{ {
@@ -14,13 +14,15 @@ public class RefreshController : Controller
private readonly ILogger<RefreshController> _logger; private readonly ILogger<RefreshController> _logger;
private readonly IUserSessionRefresher _userSession; private readonly IUserSessionRefresher _userSession;
public RefreshController(ILogger<RefreshController> logger, IUserSessionRefresher userSession) public RefreshController(
ILogger<RefreshController> logger,
IUserSessionRefresher userSession)
{ {
_logger = logger; _logger = logger;
_userSession = userSession; _userSession = userSession;
} }
[RequireHttps] //[RequireHttps]
[HttpPost("refresh")] // api/auth/token/refresh [HttpPost("refresh")] // api/auth/token/refresh
public async Task<IActionResult> Refresh([FromBody] RefreshTokenRequest refreshRequest) public async Task<IActionResult> Refresh([FromBody] RefreshTokenRequest refreshRequest)
{ {
@@ -8,9 +8,10 @@ using Microsoft.AspNetCore.Mvc;
namespace Govor.API.Controllers.Friends; namespace Govor.API.Controllers.Friends;
[ApiController]
[Authorize] [Authorize]
[Route("api/friends")] [Route("api/friends")]
[ApiController]
public class FriendsRequestQueryController : Controller public class FriendsRequestQueryController : Controller
{ {
private readonly ILogger<FriendsRequestQueryController> _logger; private readonly ILogger<FriendsRequestQueryController> _logger;
@@ -18,7 +19,8 @@ public class FriendsRequestQueryController : Controller
private readonly ICurrentUserService _currentUserService; private readonly ICurrentUserService _currentUserService;
private readonly IMapper _mapper; private readonly IMapper _mapper;
public FriendsRequestQueryController(ILogger<FriendsRequestQueryController> logger, public FriendsRequestQueryController(
ILogger<FriendsRequestQueryController> logger,
IFriendRequestQueryService friendsService, IFriendRequestQueryService friendsService,
ICurrentUserService currentUserService, ICurrentUserService currentUserService,
IMapper mapper) IMapper mapper)
@@ -16,7 +16,8 @@ public class FriendshipController : Controller
private readonly ICurrentUserService _currentUserService; private readonly ICurrentUserService _currentUserService;
private readonly IMapper _mapper; private readonly IMapper _mapper;
public FriendshipController(ILogger<FriendshipController> logger, public FriendshipController(
ILogger<FriendshipController> logger,
IFriendshipService friendsService, IFriendshipService friendsService,
ICurrentUserService currentUserService, ICurrentUserService currentUserService,
IMapper mapper) IMapper mapper)
+93 -7
View File
@@ -1,11 +1,15 @@
using AutoMapper; using AutoMapper;
using Govor.API.Hubs;
using Govor.Application.Interfaces; using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Infrastructure.Extensions; using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Interfaces.Medias; using Govor.Application.Interfaces.Medias;
using Govor.Contracts.DTOs; using Govor.Contracts.DTOs;
using Govor.Contracts.Requests;
using Govor.Core.Models;
using Govor.Data.Repositories.Exceptions; using Govor.Data.Repositories.Exceptions;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
namespace Govor.API.Controllers; namespace Govor.API.Controllers;
@@ -18,6 +22,7 @@ public class ProfileController : ControllerBase
private readonly IMediaService _mediaService; private readonly IMediaService _mediaService;
private readonly IProfileService _profileService; private readonly IProfileService _profileService;
private readonly ICurrentUserService _currentUserService; private readonly ICurrentUserService _currentUserService;
private readonly IHubContext<ProfileHub> _profileHubContext;
private readonly IMapper _mapper; private readonly IMapper _mapper;
public ProfileController( public ProfileController(
@@ -25,26 +30,80 @@ public class ProfileController : ControllerBase
IMediaService mediaService, IMediaService mediaService,
IProfileService profileService, IProfileService profileService,
ICurrentUserService currentUserService, ICurrentUserService currentUserService,
IHubContext<ProfileHub> profileHubContext,
IMapper mapper) IMapper mapper)
{ {
_logger = logger; _logger = logger;
_mediaService = mediaService; _mediaService = mediaService;
_profileService = profileService; _profileService = profileService;
_profileHubContext = profileHubContext;
_currentUserService = currentUserService; _currentUserService = currentUserService;
_mapper = mapper; _mapper = mapper;
} }
[RequestSizeLimit(40_000)]
[HttpPost("avatar")] // api/profile/avatar
public async Task<IActionResult> UploadAvatar([FromForm] AvatarUploadRequest request)
{
var userId = _currentUserService.GetCurrentUserId();
if (request.FromFile == null || request.FromFile.Length == 0)
{
return BadRequest("File is empty.");
}
try
{
byte[] fileBytes = await ReadFileAsync(request.FromFile);
[HttpGet("dowload")] var media = new Media(
public async Task<IActionResult> DowloadProfile() _currentUserService.GetCurrentUserId(),
DateTime.UtcNow,
Path.GetFileName(request.FromFile.FileName),
fileBytes,
request.Type,
request.MimeType,
String.Empty,
MediaOwnerType.Avatar,
userId);
var mediaInfo = await _mediaService.UploadMediaAsync(media);
await _profileService.SetNewIcon(userId, mediaInfo.MediaId);
var iconId = mediaInfo.MediaId;
var payload = new { userId, iconId };
await _profileHubContext.Clients.All.SendAsync(
"AvatarUpdated",
payload
);
return Ok(mediaInfo);
}
catch (System.Exception ex)
{
return StatusCode(500, new { Message = "Avatar processing error.", Details = ex.Message });
}
}
private async Task<byte[]> ReadFileAsync(IFormFile file)
{
await using var ms = new MemoryStream();
await file.CopyToAsync(ms);
return ms.ToArray();
}
[HttpGet("dowload/me")]
public async Task<IActionResult> DownloadProfile()
{ {
try try
{ {
var userId = _currentUserService.GetCurrentUserId(); var userId = _currentUserService.GetCurrentUserId();
var user = await _profileService.GetUserProfileAsync(userId); var user = await _profileService.GetUserProfileAsync(userId);
if (user is null)
return NotFound("Profile not found");
var dto = _mapper.Map<UserProfileDto>(user); var dto = _mapper.Map<UserProfileDto>(user);
return Ok(dto); return Ok(dto);
} }
@@ -56,7 +115,34 @@ public class ProfileController : ControllerBase
catch (NotFoundException ex) catch (NotFoundException ex)
{ {
_logger.LogWarning(ex, ex.Message); _logger.LogWarning(ex, ex.Message);
return BadRequest(ex.Message); return NotFound("Profile not found");
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return StatusCode(500, "Unexpected Error! Please try again later.");
}
}
[HttpGet("download/{id}")]
public async Task<IActionResult> DowloadProfileByUserId(Guid id)
{
try
{
var user = await _profileService.GetUserProfileAsync(id);
var dto = _mapper.Map<UserProfileDto>(user);
return Ok(dto);
}
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex.Message);
return Forbid(ex.Message);
}
catch (NotFoundException ex)
{
_logger.LogWarning(ex, ex.Message);
return NotFound("Profile not found");
} }
catch (Exception ex) catch (Exception ex)
{ {
+8 -5
View File
@@ -19,7 +19,11 @@ public class ChatsHub : Hub
private readonly IUserGroupsService _userService; private readonly IUserGroupsService _userService;
private readonly IHubUserAccessor _userAccessor; private readonly IHubUserAccessor _userAccessor;
public ChatsHub(ILogger<ChatsHub> logger, IMessageCommandService messageCommandService, IUserGroupsService userService, IHubUserAccessor userAccessor) public ChatsHub(
ILogger<ChatsHub> logger,
IMessageCommandService messageCommandService,
IUserGroupsService userService,
IHubUserAccessor userAccessor)
{ {
_logger = logger; _logger = logger;
_messageCommandService = messageCommandService; _messageCommandService = messageCommandService;
@@ -60,10 +64,8 @@ public class ChatsHub : Hub
_logger.LogInformation("User {UserId} disconnected with ConnectionId {ConnectionId} and removed from their group", _logger.LogInformation("User {UserId} disconnected with ConnectionId {ConnectionId} and removed from their group",
userId, Context.ConnectionId); userId, Context.ConnectionId);
var userGroups = var userGroups = await _userService.GetUserGroupsAsync(userId);
await _userService
.GetUserGroupsAsync(
userId);
foreach (var group in userGroups) foreach (var group in userGroups)
{ {
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"group_{group.Id}"); await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"group_{group.Id}");
@@ -236,6 +238,7 @@ public class ChatsHub : Hub
} }
} }
#region common #region common
private UserMessageResponse BuildUserMessageResponse(Message message, Guid? replyToId) private UserMessageResponse BuildUserMessageResponse(Message message, Guid? replyToId)
{ {
+13 -4
View File
@@ -111,9 +111,13 @@ public class FriendsHub : Hub
{ {
var userId = _userAccessor.GetUserId(Context); var userId = _userAccessor.GetUserId(Context);
var friendship = await _friendRequestService.AcceptAsync(friendshipId, userId); var friendship = await _friendRequestService.AcceptAsync(friendshipId, userId);
await Clients.Group(userId.ToString())
.SendAsync("FriendRequestAccepted", _mapper.Map<FriendshipDto>(friendship));
await Clients.Group(userId.ToString())
.SendAsync("FriendRequestAccepted", _mapper.Map<FriendshipDto>(friendship));
await Clients.Group(friendship.RequesterId.ToString())
.SendAsync( "YourFriendRequestAccepted", _mapper.Map<UserDto>(friendship.Addressee));
_logger.LogInformation($"Friend request accepted for user {userId} from {userId}."); _logger.LogInformation($"Friend request accepted for user {userId} from {userId}.");
return HubResult<object>.Ok(); return HubResult<object>.Ok();
} }
@@ -140,9 +144,14 @@ public class FriendsHub : Hub
{ {
var userId = _userAccessor.GetUserId(Context); var userId = _userAccessor.GetUserId(Context);
var friendship = await _friendRequestService.RejectAsync(friendshipId, userId); var friendship = await _friendRequestService.RejectAsync(friendshipId, userId);
var dto = _mapper.Map<FriendshipDto>(friendship);
await Clients.Group(userId.ToString()) await Clients.Group(userId.ToString())
.SendAsync("FriendRequestRejected", _mapper.Map<FriendshipDto>(friendship)); .SendAsync("FriendRequestRejected", dto);
await Clients.Group(friendship.RequesterId.ToString())
.SendAsync("YourFriendRequestRejected", dto);
_logger.LogInformation($"Friend request rejected for user {userId} from {userId}."); _logger.LogInformation($"Friend request rejected for user {userId} from {userId}.");
return HubResult<object>.Ok(); return HubResult<object>.Ok();
} }
+91 -28
View File
@@ -1,6 +1,11 @@
using Govor.API.Common.SignalR.Helpers; using Govor.API.Common.SignalR.Helpers;
using Govor.Application.Interfaces; using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Friends;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Interfaces.Medias;
using Govor.Contracts.Responses.SignalR; using Govor.Contracts.Responses.SignalR;
using Govor.Core.Models;
using Govor.Core.Models.Users;
using Govor.Core.Repositories.Groups; using Govor.Core.Repositories.Groups;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
@@ -11,14 +16,15 @@ namespace Govor.API.Hubs;
public class ProfileHub : Hub public class ProfileHub : Hub
{ {
private readonly IGroupsRepository _groupsRepository; private readonly IGroupsRepository _groupsRepository;
private readonly IFriendsService _friendsService; private readonly IFriendshipService _friendsService;
private readonly IProfileService _profileService; private readonly IProfileService _profileService;
private readonly IHubUserAccessor _userAccessor; private readonly IHubUserAccessor _userAccessor;
private readonly ILogger<ProfileHub> _logger; private readonly ILogger<ProfileHub> _logger;
private readonly IMediaService _mediaService;
public ProfileHub( public ProfileHub(
IGroupsRepository groupsRepository, IGroupsRepository groupsRepository,
IFriendsService friendsService, IFriendshipService friendsService,
IProfileService profileService, IProfileService profileService,
IHubUserAccessor userAccessor, IHubUserAccessor userAccessor,
ILogger<ProfileHub> logger) ILogger<ProfileHub> logger)
@@ -33,19 +39,32 @@ public class ProfileHub : Hub
public override async Task OnConnectedAsync() public override async Task OnConnectedAsync()
{ {
var userId = _userAccessor.GetUserId(Context); var userId = _userAccessor.GetUserId(Context);
// Добавляем в персональную группу
await Groups.AddToGroupAsync(Context.ConnectionId, $"user-{userId}"); await Groups.AddToGroupAsync(Context.ConnectionId, $"user-{userId}");
// Friends // Friends
var friendships = await _friendsService.GetFriendsAsync(userId); try
foreach (var friends in friendships) {
await Groups.AddToGroupAsync(Context.ConnectionId, $"friends-{friends.Id}"); var friendships = await _friendsService.GetFriendsAsync(userId);
foreach (var friends in friendships)
await Groups.AddToGroupAsync(Context.ConnectionId, $"friends-{friends.Id}");
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to get friends for user {userId}", userId);
}
// Groups // Groups
var groups = await _groupsRepository.GetByUserIdAsync(userId); try
foreach (var group in groups) {
await Groups.AddToGroupAsync(Context.ConnectionId, $"group-{group.Id}"); var groups = await _groupsRepository.GetByUserIdAsync(userId);
foreach (var group in groups)
await Groups.AddToGroupAsync(Context.ConnectionId, $"group-{group.Id}");
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to get groups for user {userId}", userId);
}
_logger.LogInformation("User {UserId} connected with ConnectionId {ConnectionId}", userId, Context.ConnectionId); _logger.LogInformation("User {UserId} connected with ConnectionId {ConnectionId}", userId, Context.ConnectionId);
@@ -55,24 +74,43 @@ public class ProfileHub : Hub
public override async Task OnDisconnectedAsync(Exception exception) public override async Task OnDisconnectedAsync(Exception exception)
{ {
var userId = _userAccessor.GetUserId(Context); var userId = _userAccessor.GetUserId(Context);
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"user-{userId}"); await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"user-{userId}");
// Friends // Friends
var friendships = await _friendsService.GetFriendsAsync(userId); try
foreach (var friendship in friendships) {
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"friends-{friendship.Id}"); var friendships = await _friendsService.GetFriendsAsync(userId);
foreach (var friendship in friendships)
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"friends-{friendship.Id}");
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to remove user {userId} from friend groups", userId);
}
// Groups // Groups
var groups = await _groupsRepository.GetByUserIdAsync(userId); try
foreach (var group in groups) {
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"group-{group.Id}"); var groups = await _groupsRepository.GetByUserIdAsync(userId);
foreach (var group in groups)
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"group-{group.Id}");
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to remove user {userId} from groups", userId);
}
await base.OnDisconnectedAsync(exception); await base.OnDisconnectedAsync(exception);
} }
public async Task<HubResult<bool>> SetDescription(string description) public async Task<HubResult<bool>> SetDescription(string description)
{ {
if(description.Length > 500)
return HubResult<bool>.Error("The description cannot be longer than 500 characters.");
var userId = _userAccessor.GetUserId(Context); var userId = _userAccessor.GetUserId(Context);
try try
@@ -115,26 +153,51 @@ public class ProfileHub : Hub
return HubResult<bool>.Error("An unaccounted error on the server!"); return HubResult<bool>.Error("An unaccounted error on the server!");
} }
} }
private async Task NotifyFriendsAndGroupsAsync(Guid userId, string eventName, object payload) private async Task NotifyFriendsAndGroupsAsync(Guid userId, string eventName, object payload)
{ {
var friendIds = await _friendsService.GetFriendsAsync(userId); var friendIds = Enumerable.Empty<User>();
var groups = await _groupsRepository.GetByUserIdAsync(userId); var groups = Enumerable.Empty<ChatGroup>();
try
{
friendIds = await _friendsService.GetFriendsAsync(userId);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to load friend list for notifications. userId: {userId}", userId);
}
try
{
groups = await _groupsRepository.GetByUserIdAsync(userId);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to load group list for notifications. userId: {userId}", userId);
}
var groupIds = groups.Select(g => g.Id).ToList(); var groupIds = groups.Select(g => g.Id).ToList();
await Clients.Group($"user-{userId}") // current user // Current user
await Clients.Group($"user-{userId}")
.SendAsync(eventName, payload); .SendAsync(eventName, payload);
foreach (var friendId in friendIds) // Friends
await Clients.Group($"friends-{friendId}") foreach (var friend in friendIds)
{
await Clients.Group($"friends-{friend.Id}")
.SendAsync(eventName, payload); .SendAsync(eventName, payload);
}
// Groups
foreach (var groupId in groupIds) foreach (var groupId in groupIds)
{
await Clients.Group($"group-{groupId}") await Clients.Group($"group-{groupId}")
.SendAsync(eventName, payload); .SendAsync(eventName, payload);
}
_logger.LogInformation("Sent {EventName} for {UserId} to {Friends} friends and {Groups} groups", _logger.LogInformation("Sent {EventName} for {UserId} to {Friends} friends and {Groups} groups",
eventName, userId, friendIds.Count, groupIds.Count); eventName, userId, friendIds.Count(), groupIds.Count);
} }
} }
+2 -1
View File
@@ -133,7 +133,8 @@ app.MapHub<ChatsHub>("/hubs/chats");
app.MapHub<FriendsHub>("/hubs/friends"); app.MapHub<FriendsHub>("/hubs/friends");
app.MapHub<ProfileHub>("/hubs/profiles"); app.MapHub<ProfileHub>("/hubs/profiles");
app.MapSwagger().RequireAuthorization(); app.MapSwagger()
.RequireAuthorization();
app.Map("/", () => "Not for browsers"); app.Map("/", () => "Not for browsers");
+3 -3
View File
@@ -5,7 +5,7 @@
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": false, "launchBrowser": false,
"applicationUrl": "https://0.0.0.0:8080;http://localhost:5041", "applicationUrl": "http://0.0.0.0:8080;",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} }
@@ -13,8 +13,8 @@
"https": { "https": {
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": false, "launchBrowser": true,
"applicationUrl": "https://0.0.0.0:8080;https://localhost:7155;http://localhost:5041", "applicationUrl": "https://0.0.0.0:8080;",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} }
+1 -1
View File
@@ -6,7 +6,7 @@
} }
}, },
"ConnectionStrings": { "ConnectionStrings": {
"GovorDbContext": "Host=77.233.213.226;Port=5432;Database=GovorDb;Username=gen_user;Password=co|HPq}JI6D@,t;" "GovorDbContext": "Host=localhost;Port=5432;Database=GovorDb;Username=postgres;Password=stalcker;"
}, },
"UseMySql": false, "UseMySql": false,
"AllowedHosts": "*", "AllowedHosts": "*",
@@ -43,7 +43,6 @@ public class AuthServiceTests
_accountService = new AuthService( _accountService = new AuthService(
_usersRepositoryMock.Object, _usersRepositoryMock.Object,
_jwtServiceMock.Object,
_passwordHasherMock.Object, _passwordHasherMock.Object,
_adminsRepositoryMock.Object, _adminsRepositoryMock.Object,
_usernameValidatorMock.Object _usernameValidatorMock.Object
@@ -1,5 +1,4 @@
using AutoFixture; using AutoFixture;
using Govor.Application.Exceptions.FriendsService;
using Govor.Application.Interfaces.Friends; using Govor.Application.Interfaces.Friends;
using Govor.Application.Services.Friends; using Govor.Application.Services.Friends;
using Govor.Core.Models; using Govor.Core.Models;
@@ -115,12 +114,14 @@ public class FriendshipServiceTests
public void SearchUsersAsync_Throws_UnauthorizedAccessException_IfThrowsSomeExceptionInFriendshipsRepository() public void SearchUsersAsync_Throws_UnauthorizedAccessException_IfThrowsSomeExceptionInFriendshipsRepository()
{ {
// Arrange // Arrange
_friendshipsRepositoryMock _usersRepositoryMock
.Setup(u => u.FindByUserIdAsync(It.IsAny<Guid>())) .Setup(u => u.SearchPotentialFriendsAsync(It.IsAny<Guid>(), "test"))
.ThrowsAsync(new Exception("test")); .ThrowsAsync(new Exception("test"));
// Act & Assert // Act & Assert
Assert.ThrowsAsync<UnauthorizedAccessException>(async () => await _service.SearchUsersAsync("test", Guid.NewGuid())); Assert.ThrowsAsync<UnauthorizedAccessException>(
async () => await _service.SearchUsersAsync("test", Guid.NewGuid())
);
} }
// GetFriendsAsync // GetFriendsAsync
@@ -31,7 +31,7 @@ public class AccesserToDownloadMediaServiceTests
_groupId = Guid.NewGuid(); _groupId = Guid.NewGuid();
_mediaFileId = Guid.NewGuid(); _mediaFileId = Guid.NewGuid();
// Áàçîâîå ñîîáùåíèå è ìåäèà //
var message = new Message var message = new Message
{ {
Id = Guid.NewGuid(), Id = Guid.NewGuid(),
@@ -170,7 +170,7 @@ public class AccesserToDownloadMediaServiceTests
} }
[Test] [Test]
public async Task HasAccessAsync_ReturnsFalse_ForOtherUserAvatar() public async Task HasAccessAsync_ReturnsTrue_ForOtherUserAvatar()
{ {
var avatarMedia = new MediaFile var avatarMedia = new MediaFile
{ {
@@ -188,7 +188,7 @@ public class AccesserToDownloadMediaServiceTests
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
var result = await _accesser.HasAccessAsync(avatarMedia.Id, _userId); var result = await _accesser.HasAccessAsync(avatarMedia.Id, _userId);
Assert.That(result, Is.False); Assert.That(result, Is.True);
} }
[Test] [Test]
@@ -275,7 +275,7 @@ public class AccesserToDownloadMediaServiceTests
MineType = "image/png", MineType = "image/png",
MediaType = MediaType.Image, MediaType = MediaType.Image,
UploaderId = _userId, UploaderId = _userId,
OwnerType = (MediaOwnerType)999, // íåèçâåñòíûé òèï OwnerType = (MediaOwnerType)999, //
DateCreated = DateTime.UtcNow DateCreated = DateTime.UtcNow
}; };
@@ -1,6 +1,7 @@
using Govor.Application.Services; using Govor.Application.Services;
using Govor.Core.Models.Users; using Govor.Core.Models.Users;
using Govor.Core.Repositories.Users; using Govor.Core.Repositories.Users;
using Govor.Data.Repositories.Exceptions;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Moq; using Moq;
@@ -64,7 +65,19 @@ public class ProfileServiceTests
Assert.ThrowsAsync<NullReferenceException>(() => Assert.ThrowsAsync<NullReferenceException>(() =>
_service.GetUserProfileAsync(Guid.NewGuid())); _service.GetUserProfileAsync(Guid.NewGuid()));
} }
[Test]
public void GetUserProfileAsync_ThrowsNotFoundException_WhenNotFoundByKeyException()
{
// Arrange
var userId = Guid.NewGuid();
_mockUsersRepo.Setup(r => r.FindByIdAsync(It.IsAny<Guid>()))
.ThrowsAsync(new NotFoundByKeyException<Guid>(userId));
// Act + Assert
Assert.ThrowsAsync<NotFoundException>(() =>
_service.GetUserProfileAsync(userId));
}
// ---------- SetDescription ---------- // ---------- SetDescription ----------
[Test] [Test]
@@ -22,4 +22,4 @@ public record Media(Guid UploaderId,
MediaOwnerType OwnerType, MediaOwnerType OwnerType,
Guid? OwnerId); Guid? OwnerId);
public record MediaUploadResult(Guid? MediaId, string Url); public record MediaUploadResult(Guid MediaId, string Url);
@@ -11,20 +11,17 @@ namespace Govor.Application.Services.Authentication;
public class AuthService : IAccountService public class AuthService : IAccountService
{ {
private readonly IPasswordHasher _passwordHasher; private readonly IPasswordHasher _passwordHasher;
private readonly IJwtService _jwtService;
private readonly IUsersRepository _usersRepository; private readonly IUsersRepository _usersRepository;
private readonly IAdminsRepository _adminsRepository; private readonly IAdminsRepository _adminsRepository;
private readonly IUsernameValidator _usernameValidator; private readonly IUsernameValidator _usernameValidator;
public AuthService(IUsersRepository usersRepository, public AuthService(IUsersRepository usersRepository,
IJwtService jwtService,
IPasswordHasher passwordHasher, IPasswordHasher passwordHasher,
IAdminsRepository adminsRepository, IAdminsRepository adminsRepository,
IUsernameValidator usernameValidator IUsernameValidator usernameValidator
) )
{ {
_usersRepository = usersRepository; _usersRepository = usersRepository;
_jwtService = jwtService;
_passwordHasher = passwordHasher; _passwordHasher = passwordHasher;
_adminsRepository = adminsRepository; _adminsRepository = adminsRepository;
_usernameValidator = usernameValidator; _usernameValidator = usernameValidator;
@@ -27,9 +27,7 @@ public class FriendshipService : IFriendshipService
{ {
all = await _usersRepository.SearchPotentialFriendsAsync(currentId, query); all = await _usersRepository.SearchPotentialFriendsAsync(currentId, query);
return all return all;
.Where(u => u.Id != currentId)
.ToList();
} }
catch (NotFoundByKeyException<(string, Guid)> ex) catch (NotFoundByKeyException<(string, Guid)> ex)
{ {
@@ -37,7 +35,7 @@ public class FriendshipService : IFriendshipService
} }
catch (NotFoundByKeyException<Guid> ex) catch (NotFoundByKeyException<Guid> ex)
{ {
return all.Where(u => u.Id != currentId).ToList(); return [];
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -58,7 +56,7 @@ public class FriendshipService : IFriendshipService
} }
catch (NotFoundByKeyException<Guid> ex) catch (NotFoundByKeyException<Guid> ex)
{ {
throw new InvalidOperationException("User not found", ex); throw new InvalidOperationException("Nothing was found for the specified id.", ex);
} }
} }
} }
@@ -49,11 +49,5 @@ public class InvitesService : IInvitesService
throw new InviteLinkInvalidException(inviteCode); throw new InviteLinkInvalidException(inviteCode);
} }
} }
public string GenerateInvitationLink(Invitation invitation)
{
throw new NotImplementedException();
}
} }
+17 -8
View File
@@ -1,6 +1,7 @@
using Govor.Application.Interfaces; using Govor.Application.Interfaces;
using Govor.Application.Profiles; using Govor.Application.Profiles;
using Govor.Core.Repositories.Users; using Govor.Core.Repositories.Users;
using Govor.Data.Repositories.Exceptions;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace Govor.Application.Services; namespace Govor.Application.Services;
@@ -19,15 +20,23 @@ public class ProfileService : IProfileService
public async Task<UserProfile> GetUserProfileAsync(Guid userId) public async Task<UserProfile> GetUserProfileAsync(Guid userId)
{ {
_logger.LogInformation("Gettings user {userId} profile", userId); _logger.LogInformation("Gettings user {userId} profile", userId);
var user = await _userRepository.FindByIdAsync(userId); try
return new UserProfile
{ {
Id = user.Id, var user = await _userRepository.FindByIdAsync(userId);
Username = user.Username,
Description = user.Description, return new UserProfile
IconId = user.IconId {
}; Id = user.Id,
Username = user.Username,
Description = user.Description,
IconId = user.IconId
};
}
catch (NotFoundByKeyException<Guid> ex)
{
throw new NotFoundException("User's profile cant be found with given id", ex);
}
} }
public async Task SetDescription(string description, Guid userId) public async Task SetDescription(string description, Guid userId)
@@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
using Govor.Core.Models;
using Govor.Core.Models.Messages;
using Microsoft.AspNetCore.Http;
namespace Govor.Contracts.Requests;
public class AvatarUploadRequest
{
[Required]
public IFormFile FromFile { get; set; }
[Required]
public MediaType Type { get; set; }
[Required, MaxLength(255)]
public string MimeType { get; set; } = string.Empty;
}
@@ -13,5 +13,19 @@ public class UserConfiguration : IEntityTypeConfiguration<User>
builder.HasOne(u => u.Invite) builder.HasOne(u => u.Invite)
.WithMany(i => i.Users) .WithMany(i => i.Users)
.HasForeignKey(u => u.InviteId); .HasForeignKey(u => u.InviteId);
builder.Property(u => u.Username)
.IsRequired()
.HasMaxLength(50);
builder.HasIndex(u => u.Username).IsUnique();
builder.Property(u => u.Description)
.HasMaxLength(500)
.IsRequired(false);
builder.Property(u => u.PasswordHash)
.IsRequired()
.HasMaxLength(128);
} }
} }