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
@@ -30,7 +30,7 @@ public class AuthController : Controller
_logger = logger;
}
[RequireHttps]
//[RequireHttps]
[HttpPost("register")]// api/auth/register
public async Task<IActionResult> Register([FromBody] RegistrationRequest registrationRequest)
{
@@ -74,7 +74,7 @@ public class AuthController : Controller
}
}
[RequireHttps]
//[RequireHttps]
[HttpPost("login")]// api/auth/login
public async Task<IActionResult> Login([FromBody] LoginRequest loginRequest)
{
@@ -14,13 +14,15 @@ public class RefreshController : Controller
private readonly ILogger<RefreshController> _logger;
private readonly IUserSessionRefresher _userSession;
public RefreshController(ILogger<RefreshController> logger, IUserSessionRefresher userSession)
public RefreshController(
ILogger<RefreshController> logger,
IUserSessionRefresher userSession)
{
_logger = logger;
_userSession = userSession;
}
[RequireHttps]
//[RequireHttps]
[HttpPost("refresh")] // api/auth/token/refresh
public async Task<IActionResult> Refresh([FromBody] RefreshTokenRequest refreshRequest)
{
@@ -8,9 +8,10 @@ using Microsoft.AspNetCore.Mvc;
namespace Govor.API.Controllers.Friends;
[ApiController]
[Authorize]
[Route("api/friends")]
[ApiController]
public class FriendsRequestQueryController : Controller
{
private readonly ILogger<FriendsRequestQueryController> _logger;
@@ -18,7 +19,8 @@ public class FriendsRequestQueryController : Controller
private readonly ICurrentUserService _currentUserService;
private readonly IMapper _mapper;
public FriendsRequestQueryController(ILogger<FriendsRequestQueryController> logger,
public FriendsRequestQueryController(
ILogger<FriendsRequestQueryController> logger,
IFriendRequestQueryService friendsService,
ICurrentUserService currentUserService,
IMapper mapper)
@@ -16,7 +16,8 @@ public class FriendshipController : Controller
private readonly ICurrentUserService _currentUserService;
private readonly IMapper _mapper;
public FriendshipController(ILogger<FriendshipController> logger,
public FriendshipController(
ILogger<FriendshipController> logger,
IFriendshipService friendsService,
ICurrentUserService currentUserService,
IMapper mapper)
+93 -7
View File
@@ -1,11 +1,15 @@
using AutoMapper;
using Govor.API.Hubs;
using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Interfaces.Medias;
using Govor.Contracts.DTOs;
using Govor.Contracts.Requests;
using Govor.Core.Models;
using Govor.Data.Repositories.Exceptions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
namespace Govor.API.Controllers;
@@ -18,6 +22,7 @@ public class ProfileController : ControllerBase
private readonly IMediaService _mediaService;
private readonly IProfileService _profileService;
private readonly ICurrentUserService _currentUserService;
private readonly IHubContext<ProfileHub> _profileHubContext;
private readonly IMapper _mapper;
public ProfileController(
@@ -25,26 +30,80 @@ public class ProfileController : ControllerBase
IMediaService mediaService,
IProfileService profileService,
ICurrentUserService currentUserService,
IHubContext<ProfileHub> profileHubContext,
IMapper mapper)
{
_logger = logger;
_mediaService = mediaService;
_profileService = profileService;
_profileHubContext = profileHubContext;
_currentUserService = currentUserService;
_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")]
public async Task<IActionResult> DowloadProfile()
var media = new Media(
_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
{
var userId = _currentUserService.GetCurrentUserId();
var user = await _profileService.GetUserProfileAsync(userId);
if (user is null)
return NotFound("Profile not found");
var dto = _mapper.Map<UserProfileDto>(user);
return Ok(dto);
}
@@ -56,7 +115,34 @@ public class ProfileController : ControllerBase
catch (NotFoundException ex)
{
_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)
{
+8 -5
View File
@@ -19,7 +19,11 @@ public class ChatsHub : Hub
private readonly IUserGroupsService _userService;
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;
_messageCommandService = messageCommandService;
@@ -60,10 +64,8 @@ public class ChatsHub : Hub
_logger.LogInformation("User {UserId} disconnected with ConnectionId {ConnectionId} and removed from their group",
userId, Context.ConnectionId);
var userGroups =
await _userService
.GetUserGroupsAsync(
userId);
var userGroups = await _userService.GetUserGroupsAsync(userId);
foreach (var group in userGroups)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"group_{group.Id}");
@@ -236,6 +238,7 @@ public class ChatsHub : Hub
}
}
#region common
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 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}.");
return HubResult<object>.Ok();
}
@@ -140,9 +144,14 @@ public class FriendsHub : Hub
{
var userId = _userAccessor.GetUserId(Context);
var friendship = await _friendRequestService.RejectAsync(friendshipId, userId);
var dto = _mapper.Map<FriendshipDto>(friendship);
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}.");
return HubResult<object>.Ok();
}
+91 -28
View File
@@ -1,6 +1,11 @@
using Govor.API.Common.SignalR.Helpers;
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.Core.Models;
using Govor.Core.Models.Users;
using Govor.Core.Repositories.Groups;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
@@ -11,14 +16,15 @@ namespace Govor.API.Hubs;
public class ProfileHub : Hub
{
private readonly IGroupsRepository _groupsRepository;
private readonly IFriendsService _friendsService;
private readonly IFriendshipService _friendsService;
private readonly IProfileService _profileService;
private readonly IHubUserAccessor _userAccessor;
private readonly ILogger<ProfileHub> _logger;
private readonly IMediaService _mediaService;
public ProfileHub(
IGroupsRepository groupsRepository,
IFriendsService friendsService,
IFriendshipService friendsService,
IProfileService profileService,
IHubUserAccessor userAccessor,
ILogger<ProfileHub> logger)
@@ -33,19 +39,32 @@ public class ProfileHub : Hub
public override async Task OnConnectedAsync()
{
var userId = _userAccessor.GetUserId(Context);
// Добавляем в персональную группу
await Groups.AddToGroupAsync(Context.ConnectionId, $"user-{userId}");
// Friends
var friendships = await _friendsService.GetFriendsAsync(userId);
foreach (var friends in friendships)
await Groups.AddToGroupAsync(Context.ConnectionId, $"friends-{friends.Id}");
try
{
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
var groups = await _groupsRepository.GetByUserIdAsync(userId);
foreach (var group in groups)
await Groups.AddToGroupAsync(Context.ConnectionId, $"group-{group.Id}");
try
{
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);
@@ -55,24 +74,43 @@ public class ProfileHub : Hub
public override async Task OnDisconnectedAsync(Exception exception)
{
var userId = _userAccessor.GetUserId(Context);
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"user-{userId}");
// Friends
var friendships = await _friendsService.GetFriendsAsync(userId);
foreach (var friendship in friendships)
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"friends-{friendship.Id}");
try
{
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
var groups = await _groupsRepository.GetByUserIdAsync(userId);
foreach (var group in groups)
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"group-{group.Id}");
try
{
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);
}
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);
try
@@ -115,26 +153,51 @@ public class ProfileHub : Hub
return HubResult<bool>.Error("An unaccounted error on the server!");
}
}
private async Task NotifyFriendsAndGroupsAsync(Guid userId, string eventName, object payload)
{
var friendIds = await _friendsService.GetFriendsAsync(userId);
var groups = await _groupsRepository.GetByUserIdAsync(userId);
var friendIds = Enumerable.Empty<User>();
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();
await Clients.Group($"user-{userId}") // current user
// Current user
await Clients.Group($"user-{userId}")
.SendAsync(eventName, payload);
foreach (var friendId in friendIds)
await Clients.Group($"friends-{friendId}")
// Friends
foreach (var friend in friendIds)
{
await Clients.Group($"friends-{friend.Id}")
.SendAsync(eventName, payload);
}
// Groups
foreach (var groupId in groupIds)
{
await Clients.Group($"group-{groupId}")
.SendAsync(eventName, payload);
}
_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<ProfileHub>("/hubs/profiles");
app.MapSwagger().RequireAuthorization();
app.MapSwagger()
.RequireAuthorization();
app.Map("/", () => "Not for browsers");
+3 -3
View File
@@ -5,7 +5,7 @@
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://0.0.0.0:8080;http://localhost:5041",
"applicationUrl": "http://0.0.0.0:8080;",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
@@ -13,8 +13,8 @@
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://0.0.0.0:8080;https://localhost:7155;http://localhost:5041",
"launchBrowser": true,
"applicationUrl": "https://0.0.0.0:8080;",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
+1 -1
View File
@@ -6,7 +6,7 @@
}
},
"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,
"AllowedHosts": "*",