Stable server

was added removing messages
many fixes bugs and moving to result pattern from throwing exceptions
This commit is contained in:
Artemy
2026-08-22 19:28:42 +07:00
parent 27fdcf85da
commit 3ec61fa2c0
36 changed files with 452 additions and 278 deletions
@@ -9,22 +9,21 @@ namespace Govor.API.Controllers.AdminStuff;
[ApiController] [ApiController]
[Route("api/admin/[controller]")] [Route("api/admin/[controller]")]
[Authorize(Roles = "Admin")] [Authorize]//(Roles = "Admin")
public class UsersController : Controller public class UsersController : Controller
{ {
private readonly ILogger<UsersController> _logger; private readonly ILogger<UsersController> _logger;
private readonly IUsersAdministration _users; private readonly IUsersAdministration _users;
public UsersController(ILogger<UsersController> logger, public UsersController(
IUsersAdministration users, ILogger<UsersController> logger,
IInvitationGenerator invitationGenerator) IUsersAdministration users)
{ {
_logger = logger; _logger = logger;
_users = users; _users = users;
} }
[HttpGet] [HttpGet("all")]
public async Task<IActionResult> AllUsers() public async Task<IActionResult> AllUsers()
{ {
try try
+16 -26
View File
@@ -1,10 +1,14 @@
using AutoMapper; using AutoMapper;
using Govor.API.Common.Extensions;
using Govor.Application.Infrastructure.Extensions; using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Messages; using Govor.Application.Messages;
using Govor.Contracts.Requests; using Govor.Contracts.Requests;
using Govor.Contracts.Responses; using Govor.Contracts.Responses;
using Govor.Domain.Common;
using Govor.Domain.Models.Messages;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using SmartRes;
namespace Govor.API.Controllers; namespace Govor.API.Controllers;
@@ -40,21 +44,14 @@ public class ChatLoadController : Controller
if (query.Before < 0 || query.After < 0 || query.After + query.Before > 100) if (query.Before < 0 || query.After < 0 || query.After + query.Before > 100)
return BadRequest("Values must be non-negative and total must not exceed 100."); return BadRequest("Values must be non-negative and total must not exceed 100.");
var result = await _messagesLoader.LoadMessagesInChatGroup( var result = (await _messagesLoader.LoadMessagesInChatGroup(
groupId, groupId,
_currentUser.GetCurrentUserId(), _currentUser.GetCurrentUserId(),
query.StartMessageId, query.StartMessageId,
query.Before, query.Before,
query.After); query.After)).Map(messages => _mapper.Map<List<MessageResponse>>(messages));
var response = _mapper.Map<List<MessageResponse>>(result); return result.ToActionResult();
return Ok(response);
}
catch (ArgumentException ex)
{
_logger.LogWarning(ex, ex.Message);
return BadRequest(ex.Message);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -73,21 +70,15 @@ public class ChatLoadController : Controller
if (query.Before < 0 || query.After < 0 || query.After + query.Before > 100) if (query.Before < 0 || query.After < 0 || query.After + query.Before > 100)
return BadRequest("Values must be non-negative and total must not exceed 100."); return BadRequest("Values must be non-negative and total must not exceed 100.");
var result = await _messagesLoader.LoadMessagesInUserChat( var result = (await _messagesLoader.LoadMessagesInUserChat(
userId, userId,
_currentUser.GetCurrentUserId(), _currentUser.GetCurrentUserId(),
query.StartMessageId, query.StartMessageId,
query.Before, query.Before,
query.After); query.After)
).Map(messages => _mapper.Map<List<MessageResponse>>(messages));
var response = _mapper.Map<List<MessageResponse>>(result); return result.ToActionResult();
return Ok(response);
}
catch (ArgumentException ex)
{
_logger.LogWarning(ex, ex.Message);
return BadRequest(ex.Message);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -95,5 +86,4 @@ public class ChatLoadController : Controller
return StatusCode(500, "Unexpected Error! Please try again later."); return StatusCode(500, "Unexpected Error! Please try again later.");
} }
} }
} }
@@ -7,7 +7,6 @@ using Microsoft.AspNetCore.Mvc;
namespace Govor.API.Controllers.Friends; namespace Govor.API.Controllers.Friends;
[Authorize] [Authorize]
[Route("api/friends")] [Route("api/friends")]
[ApiController] [ApiController]
@@ -2,11 +2,14 @@ using AutoMapper;
using Govor.Application.Friends; using Govor.Application.Friends;
using Govor.Application.Infrastructure.Extensions; using Govor.Application.Infrastructure.Extensions;
using Govor.Contracts.DTOs; using Govor.Contracts.DTOs;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace Govor.API.Controllers.Friends; namespace Govor.API.Controllers.Friends;
[Authorize]
[Route("api/friends")] [Route("api/friends")]
[ApiController]
public class FriendshipController : Controller public class FriendshipController : Controller
{ {
private readonly ILogger<FriendshipController> _logger; private readonly ILogger<FriendshipController> _logger;
@@ -40,11 +43,6 @@ public class FriendshipController : Controller
return Ok(response); return Ok(response);
} }
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message);
}
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, ex.Message); _logger.LogError(ex, ex.Message);
@@ -63,16 +61,6 @@ public class FriendshipController : Controller
return Ok(response); return Ok(response);
} }
catch (InvalidOperationException ex)
{
_logger.LogError(ex, ex.Message);
return Ok(Array.Empty<UserDto>());
}
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message);
}
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, ex.Message); _logger.LogError(ex, ex.Message);
+2 -2
View File
@@ -21,11 +21,11 @@ public class InviteController : ControllerBase
[Authorize] [Authorize]
[HttpGet("{code}")] [HttpGet("{code}")]
public IActionResult JoinGroup(string code) public async Task<IActionResult> JoinGroup(string code)
{ {
try try
{ {
_groupService.AddUserToGroupByInvitationAsync(_currentUser.GetCurrentUserId(), code); var groupRes = await _groupService.AddUserToGroupByInvitationAsync(_currentUser.GetCurrentUserId(), code);
var group = _groupService.GetGroupByInviteCode(code); var group = _groupService.GetGroupByInviteCode(code);
+21 -26
View File
@@ -1,3 +1,4 @@
using Govor.API.Common.Extensions;
using Govor.Application.Infrastructure.Extensions; using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Medias; using Govor.Application.Medias;
using Govor.Contracts.Requests; using Govor.Contracts.Requests;
@@ -70,19 +71,22 @@ public class MediaController : Controller
_logger.LogInformation("Uploaded file {FileName} from user {UserId}", _logger.LogInformation("Uploaded file {FileName} from user {UserId}",
media.FileName, media.UploaderId); media.FileName, media.UploaderId);
return Ok(result); if (result.IsFailure)
{
_logger.LogWarning("Uploaded file {FileName} from user {UserId} finished with error: {Error}",
media.FileName,
media.UploaderId,
result.Error);
}
return result.ToActionResult();
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
_logger.LogWarning(ex, ex.Message); _logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message); return Forbid(ex.Message);
} }
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, ex.Message);
return BadRequest(ex.Message);
}
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error uploading media"); _logger.LogError(ex, "Error uploading media");
@@ -101,26 +105,17 @@ public class MediaController : Controller
[HttpGet("download/{id}")] [HttpGet("download/{id}")]
public async Task<IActionResult> Download(Guid id) public async Task<IActionResult> Download(Guid id)
{ {
try var userId = _currentUserService.GetCurrentUserId();
{
var userId = _currentUserService.GetCurrentUserId();
if (!await _accesser.HasAccessAsync(id, userId)) if (!await _accesser.HasAccessAsync(id, userId))
return Forbid(); return Forbid();
var media = await _mediaService.GetMediaByIdAsync(id); var mediaResult = await _mediaService.GetMediaByIdAsync(id);
return File(media.Data, media.MimeType, Path.GetFileName(media.FileName)); if (mediaResult.IsFailure)
} return mediaResult.ToActionResult();
catch (KeyNotFoundException ex)
{ var media = mediaResult.Value;
_logger.LogWarning(ex, ex.Message); return File(media.Data, media.MimeType, Path.GetFileName(media.FileName));
return NotFound("Media not found");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error downloading media");
return StatusCode(500, "Internal server error");
}
} }
} }
+16 -16
View File
@@ -1,4 +1,5 @@
using AutoMapper; using AutoMapper;
using Govor.API.Common.Extensions;
using Govor.API.Hubs; using Govor.API.Hubs;
using Govor.Application.Infrastructure.Extensions; using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Medias; using Govor.Application.Medias;
@@ -9,6 +10,7 @@ using Govor.Domain.Models;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using SmartRes;
namespace Govor.API.Controllers; namespace Govor.API.Controllers;
@@ -43,10 +45,9 @@ public class ProfileController : ControllerBase
[HttpPost("avatar")] // api/profile/avatar [HttpPost("avatar")] // api/profile/avatar
public async Task<IActionResult> UploadAvatar([FromForm] AvatarUploadRequest request) public async Task<IActionResult> UploadAvatar([FromForm] AvatarUploadRequest request)
{ {
var userId = _currentUserService.GetCurrentUserId(); var userId = _currentUserService.GetCurrentUserId();
if (request.FromFile == null || request.FromFile.Length == 0) if (request?.FromFile == null || request.FromFile.Length == 0)
{ {
return BadRequest("File is empty."); return BadRequest("File is empty.");
} }
@@ -65,11 +66,13 @@ public class ProfileController : ControllerBase
String.Empty, String.Empty,
MediaOwnerType.Avatar, MediaOwnerType.Avatar,
userId); userId);
var mediaInfo = await _mediaService.UploadMediaAsync(media); var mediaInfo = await _mediaService.UploadMediaAsync(media)
await _profileService.SetNewIcon(userId, mediaInfo.MediaId); .TapAsync(m => _logger.LogInformation("Uploaded avatar file {filename} by user {id}.",
request.FromFile.FileName, userId))
return Ok(mediaInfo); .TapAsync(mediaInfo => _profileService.SetNewIcon(userId, mediaInfo.MediaId));
return mediaInfo.ToActionResult();
} }
catch (System.Exception ex) catch (System.Exception ex)
{ {
@@ -92,12 +95,9 @@ public class ProfileController : ControllerBase
var userId = _currentUserService.GetCurrentUserId(); var userId = _currentUserService.GetCurrentUserId();
var result = await _profileService.GetUserProfileAsync(userId); var result = await _profileService.GetUserProfileAsync(userId);
if(result.IsFailure) return result
return NotFound(result.Error); .Map(user => _mapper.Map<UserProfileDto>(user))
.ToActionResult();
var user = result.Value;
var dto = _mapper.Map<UserProfileDto>(user);
return Ok(dto);
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
@@ -116,10 +116,10 @@ public class ProfileController : ControllerBase
{ {
try try
{ {
var user = await _profileService.GetUserProfileAsync(id); var user = (await _profileService.GetUserProfileAsync(id))
.Map(user => _mapper.Map<UserProfileDto>(user));
var dto = _mapper.Map<UserProfileDto>(user); return user.ToActionResult();
return Ok(dto);
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
@@ -1,3 +1,4 @@
using Govor.API.Common.Extensions;
using Govor.Application.Infrastructure.Extensions; using Govor.Application.Infrastructure.Extensions;
using Govor.Application.PushNotifications; using Govor.Application.PushNotifications;
using Govor.Contracts.Requests; using Govor.Contracts.Requests;
@@ -39,13 +40,13 @@ public class PushTokensController : Controller
var currentId = _currentUser.GetCurrentUserId(); var currentId = _currentUser.GetCurrentUserId();
var currentSessionId = _currentSession.GetUserSessionId(); var currentSessionId = _currentSession.GetUserSessionId();
await _pushTokenService.AddOrUpdateTokenAsync( var result = await _pushTokenService.AddOrUpdateTokenAsync(
userId: currentId, userId: currentId,
sessionId: currentSessionId, sessionId: currentSessionId,
token: req.Token, token: req.Token,
platform: req.Platform); platform: req.Platform);
return Ok(); return result.ToActionResult();
} }
catch (ArgumentException ex) catch (ArgumentException ex)
{ {
+9 -29
View File
@@ -1,4 +1,5 @@
using AutoMapper; using AutoMapper;
using Govor.API.Common.Extensions;
using Govor.Application.Infrastructure.Extensions; using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Users.UserSessions; using Govor.Application.Users.UserSessions;
using Govor.Contracts.DTOs; using Govor.Contracts.DTOs;
@@ -40,12 +41,10 @@ public class SessionController : Controller
{ {
try try
{ {
var sessions = await _userSessionReader.GetAllSessionsAsync(_currentUserService.GetCurrentUserId()); var sessions = (await _userSessionReader.GetAllSessionsAsync(_currentUserService.GetCurrentUserId()))
.Map(sessions => _mapper.Map<List<SessionDto>>(sessions));
if(sessions.IsFailure)
return NotFound(sessions.Error); return sessions.ToActionResult();
return Ok(_mapper.Map<List<SessionDto>>(sessions.Value));
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
@@ -70,15 +69,7 @@ public class SessionController : Controller
var res = await _userSessionRevoker.CloseSessionByIdAsync(sessionId, var res = await _userSessionRevoker.CloseSessionByIdAsync(sessionId,
_currentUserService.GetCurrentUserId()); _currentUserService.GetCurrentUserId());
if (res.IsFailure) return res.ToActionResult();
return BadRequest(res.Error);
return Ok();
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, ex.Message);
return BadRequest(ex.Message);
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
@@ -97,19 +88,11 @@ public class SessionController : Controller
{ {
try try
{ {
var res = await _userSessionRevoker.CloseSessionByIdAsync( var res = await _userSessionRevoker.CloseSessionByIdAsync(
_currentUserSessionService.GetUserSessionId(), _currentUserSessionService.GetUserSessionId(),
_currentUserService.GetCurrentUserId()); _currentUserService.GetCurrentUserId());
if(res.IsFailure) return res.ToActionResult();
return NotFound(res.Error);
return Ok();
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, ex.Message);
return BadRequest(ex.Message);
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
@@ -130,10 +113,7 @@ public class SessionController : Controller
{ {
var res = await _userSessionRevoker.CloseAllSessionsAsync(_currentUserService.GetCurrentUserId()); var res = await _userSessionRevoker.CloseAllSessionsAsync(_currentUserService.GetCurrentUserId());
if(res.IsFailure) return res.ToActionResult();
return NotFound(res.Error);
return Ok();
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
+4
View File
@@ -33,5 +33,9 @@
<ProjectReference Include="..\Govor.Domain\Govor.Domain.csproj" /> <ProjectReference Include="..\Govor.Domain\Govor.Domain.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="uploads\2026.08\" />
</ItemGroup>
</Project> </Project>
+16 -6
View File
@@ -91,17 +91,27 @@ public class ChatsHub : Hub
{ {
return await SafeExecute(async (userId) => 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) if (!result.IsSuccess)
throw new InvalidOperationException("Message deletion failed"); throw new InvalidOperationException(result.Error.ToString());
var notification = new MessageRemovedResponse var notification = new MessageRemovedResponse
{ {
MessageId = request.MessageId, MessageId = request.MessageId,
SenderId = result.OriginalMessage.SenderId, SenderId = result.Value.SenderId,
RecipientId = result.OriginalMessage.RecipientId, RecipientId = result.Value.RecipientId,
RecipientType = result.OriginalMessage.RecipientType RecipientType = result.Value.RecipientType
}; };
await _notifier.NotifyMessageRemovedAsync(notification); await _notifier.NotifyMessageRemovedAsync(notification);
+2 -2
View File
@@ -82,7 +82,7 @@ public class FriendsHub : Hub
return HubResult<object>.Error(result.Error.ToString()); return HubResult<object>.Error(result.Error.ToString());
var friendship = result.Value; var friendship = result.Value;
var dto = _mapper.Map<FriendshipDto>(friendship); var dto = _mapper.Map<FriendshipDto>(friendship);
await Clients.Group(targetUserId.ToString()) await Clients.Group(targetUserId.ToString())
.SendAsync("FriendRequestReceived", dto); .SendAsync("FriendRequestReceived", dto);
@@ -127,7 +127,7 @@ public class FriendsHub : Hub
var friendship = result.Value; var friendship = result.Value;
var dto = _mapper.Map<FriendshipDto>(friendship); var dto = _mapper.Map<FriendshipDto>(friendship);
await Clients.Group(userId.ToString()) await Clients.Group(userId.ToString())
.SendAsync("FriendRequestAccepted", dto); .SendAsync("FriendRequestAccepted", dto);
+170 -78
View File
@@ -11,24 +11,29 @@ using Microsoft.AspNetCore.SignalR;
namespace Govor.API.Hubs; namespace Govor.API.Hubs;
[Authorize] [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 IProfileService _profileService;
private readonly IHubUserAccessor _userAccessor; private readonly IHubUserAccessor _userAccessor;
private readonly ISynchingService _synchingService; private readonly ISynchingService _synchingService;
private readonly IMediaService _mediaService;
private readonly ILogger<ProfileHub> _logger; private readonly ILogger<ProfileHub> _logger;
private readonly IMediaService _mediaService;
public ProfileHub( public ProfileHub(
IFriendshipService friendsService, IFriendshipService friendshipService,
IProfileService profileService, IProfileService profileService,
IHubUserAccessor userAccessor, IHubUserAccessor userAccessor,
ISynchingService synchingService, ISynchingService synchingService,
IMediaService mediaService, IMediaService mediaService,
ILogger<ProfileHub> logger) ILogger<ProfileHub> logger)
{ {
_friendsService = friendsService; _friendshipService = friendshipService;
_profileService = profileService; _profileService = profileService;
_userAccessor = userAccessor; _userAccessor = userAccessor;
_synchingService = synchingService; _synchingService = synchingService;
@@ -39,32 +44,66 @@ public class ProfileHub : Hub
public override async Task OnConnectedAsync() public override async Task OnConnectedAsync()
{ {
var userId = _userAccessor.GetUserId(Context); 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(); await base.OnConnectedAsync();
} }
public override async Task OnDisconnectedAsync(Exception exception) public override async Task OnDisconnectedAsync(Exception? exception)
{ {
var userId = _userAccessor.GetUserId(Context); var userId = _userAccessor.GetUserId(Context);
var groupName = GetUserGroup(userId);
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"user-{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); 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) if (description.Length > 500)
return HubResult<bool>.Error("Description length exceeded."); return HubResult<bool>.BadRequest(
"Description length exceeded.");
var userId = _userAccessor.GetUserId(Context); var userId = _userAccessor.GetUserId(Context);
try try
{ {
description = _synchingService.NormalizeNewlines(description); await _profileService.SetDescription(
await _profileService.SetDescription(description, userId); description,
userId);
var payload = new DescriptionUpdatePayload var payload = new DescriptionUpdatePayload
{ {
@@ -72,105 +111,158 @@ public class ProfileHub : Hub
Description = description Description = description
}; };
await NotifyProfileUpdatedAsync(userId, "DescriptionUpdated", payload); await NotifyProfileUpdatedAsync(
userId,
DescriptionUpdatedEvent,
payload);
return HubResult<bool>.Ok(true); return HubResult<bool>.Ok(true);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Failed to update description for user {UserId}", userId); _logger.LogError(
return HubResult<bool>.Error("Server error."); ex,
"Failed to update description for user {UserId}",
userId);
return HubResult<bool>.Error(
"Server error.");
} }
} }
public async Task<HubResult<bool>> SetAvatar(Guid iconId) public async Task<HubResult<bool>> SetAvatar(Guid iconId)
{ {
if (iconId == Guid.Empty)
return HubResult<bool>.BadRequest(
"Invalid icon id.");
var userId = _userAccessor.GetUserId(Context); var userId = _userAccessor.GetUserId(Context);
try try
{ {
if (iconId == Guid.Empty || !await _mediaService.HasMediaAsync(iconId)) var mediaExists = await _mediaService.HasMediaAsync(iconId);
return HubResult<bool>.BadRequest("Invalid icon id.");
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); return HubResult<bool>.Ok(true);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "An error occurred while updating the user's {userId} avatar {iconId}", userId, iconId); _logger.LogError(
return HubResult<bool>.Error("An unaccounted error on the server!"); ex,
"Failed to update avatar for user {UserId}. IconId: {IconId}",
userId,
iconId);
return HubResult<bool>.Error(
"Server error.");
} }
} }
private async Task NotifyProfileUpdatedAsync( private async Task NotifyProfileUpdatedAsync(
Guid UserId, Guid userId,
string eventName, string eventName,
object payload) object payload)
{ {
try try
{ {
var recipients = new HashSet<Guid>(); var recipients = await GetProfileUpdateRecipientsAsync(userId);
// 1. Friends if (recipients.Count == 0)
try return;
{
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);
}
var groups = recipients
.Select(GetUserGroup)
.ToArray();
// 3. groups await Clients
/*var groups = await _groupsRepository.GetByUserIdAsync(authorUserId); .Groups(groups)
foreach (var group in 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 = if (friend.Id != Guid.Empty)
await _groupsRepository.Get(group.Id); recipients.Add(friend.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);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, _logger.LogWarning(
"Failed to notify profile update for user {UserId}", ex,
UserId); "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}";
}
}
+4 -14
View File
@@ -16,7 +16,6 @@ var services = builder.Services;
builder.AddLogger();// Serilog builder.AddLogger();// Serilog
builder.Configuration.AddJsonFile("configs/ban_usernames.json", optional: false, reloadOnChange: true); builder.Configuration.AddJsonFile("configs/ban_usernames.json", optional: false, reloadOnChange: true);
#if DEBUG #if DEBUG
@@ -65,7 +64,8 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
{ {
var accessToken = context.Request.Query["access_token"]; var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path; var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/api/chats"))
if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
{ {
context.Token = accessToken; context.Token = accessToken;
} }
@@ -101,19 +101,9 @@ services.AddSwaggerGen(options =>
Description = "JWT Authorization header using the Bearer scheme. Example: 'Bearer {token}'" Description = "JWT Authorization header using the Bearer scheme. Example: 'Bearer {token}'"
}); });
options.AddSecurityRequirement(document => options.AddSecurityRequirement(document => new OpenApiSecurityRequirement
{ {
var requirement = new OpenApiSecurityRequirement [new OpenApiSecuritySchemeReference("Bearer", document)] = new List<string>(0)
{
{
new OpenApiSecuritySchemeReference(schemeId)
{
Reference = new OpenApiReferenceWithDescription { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
},
[]
}
};
return requirement;
}); });
}); });
@@ -31,7 +31,6 @@ public class AuthService : IAccountService
public async Task<Result<User, Error>> RegistrationAsync(string name, string password, Invitation invitation) public async Task<Result<User, Error>> RegistrationAsync(string name, string password, Invitation invitation)
{ {
var validationResult = _usernameValidator.Validate(name); var validationResult = _usernameValidator.Validate(name);
if (validationResult.IsFailure) if (validationResult.IsFailure)
{ {
@@ -63,8 +62,8 @@ public class AuthService : IAccountService
await _context.Users.AddAsync(user); await _context.Users.AddAsync(user);
await SetRoleAsync(user, invitation); await SetRoleAsync(user, invitation);
// TODO: inv.participantCount -= 1; db.save(); invitation.Participants += 1;
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
@@ -1,4 +1,3 @@
using Govor.Application.Exceptions.InvitesService;
using Govor.Domain; using Govor.Domain;
using Govor.Domain.Common; using Govor.Domain.Common;
using Govor.Domain.Models; using Govor.Domain.Models;
@@ -24,7 +23,7 @@ public class InvitesService : IInvitesService
public async Task<string> GetRoleNameAsync(Guid sessionId) public async Task<string> GetRoleNameAsync(Guid sessionId)
{ {
var invitation = await _context.Invitations.FirstOrDefaultAsync(s => s.Id == sessionId); var invitation = await _context.Invitations.AsNoTracking().FirstOrDefaultAsync(s => s.Id == sessionId);
if (invitation == null) if (invitation == null)
return "User"; return "User";
@@ -41,7 +40,7 @@ public class InvitesService : IInvitesService
if (invite == null) if (invite == null)
return Result.Failure<Invitation>(Error.NotFound("Auth.LinkNotFount","Invitation not found.")); return Result.Failure<Invitation>(Error.NotFound("Auth.LinkNotFount","Invitation not found."));
if (invite.EndDate < DateTime.Now || invite.MaxParticipants <= invite.Users.Count) if (invite.EndDate < DateTime.Now || invite.MaxParticipants <= invite.Users.Count || invite.MaxParticipants <= invite.Participants)
{ {
invite.IsActive = false; invite.IsActive = false;
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
@@ -26,7 +26,8 @@ public class JwtService : IJwtService
{ {
new Claim("userId", user.Id.ToString()), new Claim("userId", user.Id.ToString()),
new Claim("sid", sessionId.ToString()), new Claim("sid", sessionId.ToString()),
new Claim(ClaimTypes.Role, await _invitesService.GetRoleNameAsync(user), ClaimValueTypes.String) new Claim(ClaimTypes.Role, await _invitesService.GetRoleNameAsync(user))
//new Claim(ClaimTypes.Role, await _invitesService.GetRoleNameAsync(user), ClaimValueTypes.String)
}; };
var singing = new SigningCredentials( var singing = new SigningCredentials(
+7 -5
View File
@@ -1,17 +1,19 @@
using Govor.Domain.Common;
using Govor.Domain.Models; using Govor.Domain.Models;
using Govor.Domain.Models.Messages; using Govor.Domain.Models.Messages;
using SmartRes;
namespace Govor.Application.Medias; namespace Govor.Application.Medias;
public interface IMediaService public interface IMediaService
{ {
public Task<MediaUploadResult> UploadMediaAsync(Media file); public Task<Result<MediaUploadResult, Error>> UploadMediaAsync(Media file);
public Task DeleteMediaAsync(Guid fileId); public Task<Result<Unit, Error>> DeleteMediaAsync(Guid fileId);
public Task<Media> GetMediaByUrlAsync(string url); public Task<Result<Media, Error>> GetMediaByUrlAsync(string url);
public Task<Media> GetMediaByIdAsync(Guid mediaId); public Task<Result<Media, Error>> GetMediaByIdAsync(Guid mediaId);
public Task<bool> HasMediaAsync(Guid mediaId); public Task<bool> HasMediaAsync(Guid mediaId);
public Task<bool> HasMediaByUrlAsync(string url); public Task<bool> HasMediaByUrlAsync(string url);
Task AttachToMessageAsync(Guid mediaId, Guid messageId); public Task<Result<Unit, Error>> AttachToMessageAsync(Guid mediaId, Guid messageId);
} }
public record Media(Guid UploaderId, public record Media(Guid UploaderId,
+54 -20
View File
@@ -1,8 +1,10 @@
using Govor.Application.Storage; using Govor.Application.Storage;
using Govor.Domain.Models; using Govor.Domain.Models;
using Govor.Domain; using Govor.Domain;
using Govor.Domain.Common;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SmartRes;
namespace Govor.Application.Medias; namespace Govor.Application.Medias;
@@ -19,7 +21,7 @@ public class MediaService : IMediaService
_logger = logger; _logger = logger;
} }
public async Task<MediaUploadResult> UploadMediaAsync(Media file) public async Task<Result<MediaUploadResult, Error>> UploadMediaAsync(Media file)
{ {
try try
{ {
@@ -47,37 +49,56 @@ public class MediaService : IMediaService
} }
catch (ArgumentException ex) catch (ArgumentException ex)
{ {
throw new InvalidOperationException($"An error occured while uploading the media file: {ex.Message}"); return Result<MediaUploadResult, Error>.Failure(Error.Failure(
nameof(InvalidOperationException),
$"An error occured while uploading the media file: {ex.Message}")
);
} }
} }
public async Task DeleteMediaAsync(Guid mediaId) public async Task<Result<Unit, Error>> DeleteMediaAsync(Guid mediaId)
{ {
var mediaFile = await _dbContext.MediaFiles var mediaFile = await _dbContext.MediaFiles
.FirstOrDefaultAsync(x => x.Id == mediaId) .FirstOrDefaultAsync(x => x.Id == mediaId);
?? throw new KeyNotFoundException($"No media found by given id {mediaId}");
if (mediaFile is null)
{
return Result<Unit, Error>.Failure(Error.NotFound(
"File.DeleteMedia",
$"File with given id ({mediaId}) doesn't exist!")
);
}
await _storageService.RemoveAsync(mediaFile.Url); await _storageService.RemoveAsync(mediaFile.Url);
_dbContext.MediaFiles.Remove(mediaFile); _dbContext.MediaFiles.Remove(mediaFile);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return new Unit();
} }
public Task<Media> GetMediaByUrlAsync(string url) public Task<Result<Media, Error>> GetMediaByUrlAsync(string url)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public async Task<Media> GetMediaByIdAsync(Guid mediaId) public async Task<Result<Media, Error>> GetMediaByIdAsync(Guid mediaId)
{ {
try try
{ {
var mediaFile = await _dbContext.MediaFiles var mediaFile = await _dbContext.MediaFiles
.AsNoTracking() .AsNoTracking()
.FirstOrDefaultAsync(x => x.Id == mediaId) .FirstOrDefaultAsync(x => x.Id == mediaId);
?? throw new KeyNotFoundException($"No media found by given id {mediaId}");
if (mediaFile is null)
{
return Result<Media, Error>.Failure(Error.NotFound(
"File.GetMediaById",
$"File with given id ({mediaId}) doesn't exist!")
);
}
// Загрузить бинарные данные из хранилища // Загрузить бинарные данные из хранилища
Stream dataStream = await _storageService.LoadAsync(mediaFile.Url); Stream dataStream = await _storageService.LoadAsync(mediaFile.Url);
@@ -86,7 +107,8 @@ public class MediaService : IMediaService
await dataStream.CopyToAsync(memoryStream); await dataStream.CopyToAsync(memoryStream);
var contentBytes = memoryStream.ToArray(); var contentBytes = memoryStream.ToArray();
_logger.LogInformation($"Media found: {mediaFile.MediaType} with id: {mediaFile.Id} and url: {mediaFile.Url}"); _logger.LogInformation("Media found: {mediaFile.MediaType} with id: {mediaFile.Id} and url: {mediaFile.Url}",
mediaFile.MediaType, mediaFile.Id, mediaFile.Url);
// Вернуть объект Media // Вернуть объект Media
return new Media( return new Media(
@@ -103,33 +125,43 @@ public class MediaService : IMediaService
} }
catch (FileNotFoundException ex) catch (FileNotFoundException ex)
{ {
_logger.LogWarning(ex, "Media file not found on storage."); _logger.LogWarning(ex, "Media file ({0}) not found on storage.", mediaId);
throw; return Result<Media, Error>.Failure(Error.ServerError("File.GetMediaById", $"Media file not found on storage!"));
} }
} }
public async Task<bool> HasMediaAsync(Guid mediaId) public async Task<bool> HasMediaAsync(Guid mediaId)
{ {
return await _dbContext.MediaFiles.AsNoTracking() return await _dbContext.MediaFiles.AsNoTracking()
.FirstOrDefaultAsync(x => x.Id == mediaId) is not null; .AnyAsync(x => x.Id == mediaId);
} }
public async Task<bool> HasMediaByUrlAsync(string url) public async Task<bool> HasMediaByUrlAsync(string url)
{ {
return await _dbContext.MediaFiles.AsNoTracking() return await _dbContext.MediaFiles.AsNoTracking()
.FirstOrDefaultAsync(x => x.Url == url) is not null; .AnyAsync(x => x.Url == url);
} }
public async Task AttachToMessageAsync(Guid mediaId, Guid messageId) public async Task<Result<Unit, Error>> AttachToMessageAsync(Guid mediaId, Guid messageId)
{ {
var mediaFile = await _dbContext.MediaFiles var mediaFile = await _dbContext.MediaFiles
.FirstOrDefaultAsync(x => x.Id == mediaId) .FirstOrDefaultAsync(x => x.Id == mediaId);
?? throw new KeyNotFoundException($"No media found by given id {mediaId}");
if (mediaFile is null)
{
return Result<Unit, Error>.Failure(Error.NotFound(
"File.AttachToMessage",
$"File with given id ({mediaId}) doesn't exist!")
);
}
if (mediaFile.OwnerType != MediaOwnerType.Message) if (mediaFile.OwnerType != MediaOwnerType.Message)
{ {
_logger.LogWarning("Attempt to attach already owned media {MediaId}", mediaId); _logger.LogWarning("Attempt to attach already owned media {MediaId}", mediaId);
throw new InvalidOperationException($"Media {mediaId} is already attached to {mediaFile.OwnerType}"); return Result<Unit, Error>.Failure(Error.Failure(
"File.AttachToMessage",
$"Media {mediaId} is already attached to {mediaFile.OwnerType}")
);
} }
mediaFile.OwnerType = MediaOwnerType.Message; mediaFile.OwnerType = MediaOwnerType.Message;
@@ -139,5 +171,7 @@ public class MediaService : IMediaService
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
_logger.LogInformation("Media {MediaId} successfully attached to message {MessageId}", mediaId, messageId); _logger.LogInformation("Media {MediaId} successfully attached to message {MessageId}", mediaId, messageId);
return new Unit();
} }
} }
@@ -1,8 +1,11 @@
using Govor.Application.Messages.Parameters; using Govor.Application.Messages.Parameters;
using Govor.Domain.Common;
using Govor.Domain.Models.Messages;
using SmartRes;
namespace Govor.Application.Messages; namespace Govor.Application.Messages;
public interface IMessageRemovingService public interface IMessageRemovingService
{ {
Task<DeleteMessageResult> DeleteMessageAsync(DeleteMessage deleteParams); Task<Result<Message,Error>> DeleteMessageAsync(DeleteMessage deleteParams);
} }
@@ -1,9 +1,11 @@
using Govor.Domain.Common;
using Govor.Domain.Models.Messages; using Govor.Domain.Models.Messages;
using SmartRes;
namespace Govor.Application.Messages; namespace Govor.Application.Messages;
public interface IMessagesLoader public interface IMessagesLoader
{ {
Task<List<Message>> LoadMessagesInUserChat(Guid privateChatId,Guid currentId, Guid? startMessageId, int before = 20, int after = 2); Task<Result<List<Message>,Error>> LoadMessagesInUserChat(Guid privateChatId,Guid currentId, Guid? startMessageId, int before = 20, int after = 2);
Task<List<Message>> LoadMessagesInChatGroup(Guid chatId,Guid currentId, Guid? startMessageId, int before = 20, int after = 2); Task<Result<List<Message>,Error>> LoadMessagesInChatGroup(Guid chatId,Guid currentId, Guid? startMessageId, int before = 20, int after = 2);
} }
@@ -1,6 +1,10 @@
using Govor.Application.Messages.Parameters; using Govor.Application.Messages.Parameters;
using Govor.Domain; using Govor.Domain;
using Govor.Domain.Common;
using Govor.Domain.Models.Messages;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SmartRes;
namespace Govor.Application.Messages; namespace Govor.Application.Messages;
@@ -17,8 +21,67 @@ public class MessageRemovingService : IMessageRemovingService
_logger = logger; _logger = logger;
} }
public Task<DeleteMessageResult> DeleteMessageAsync(DeleteMessage deleteParams) public async Task<Result<Message,Error>> DeleteMessageAsync(DeleteMessage deleteParams)
{ {
throw new NotImplementedException(); var message = await _govorDbContext.Messages.FirstOrDefaultAsync(m => m.Id == deleteParams.MessageId);
if (message == null)
return Result<Message, Error>.Failure(
Error.NotFound(
"MessageRemoving",
"Message with given id doesn't exist")
);
var result = message.RecipientType switch
{
RecipientType.Group => await ValidateGroupRecipientAsync(message, deleteParams),
RecipientType.User => await ValidateUserRecipientAsync(message, deleteParams),
_ => Result<Message, Error>.Failure(Error.Failure(
"MessageRemoving.ArgumentOutOfRangeException",
$"Argument out of range: {nameof(message.RecipientType)}"
)
)
};
return result;
}
private async Task<Result<Message,Error>> ValidateGroupRecipientAsync(Message message, DeleteMessage deleteParams)
{
if (deleteParams.DeleterId == message.RecipientId)
{
return await ForceRemoveAsync(message);
}
else
{
// TODO made admin rules
return Result<Message, Error>.Failure(Error.Failure("MessageRemoving.HaveNoPermission",
$"You do not have permission to delete message {message.Id}"
));
}
}
private async Task<Result<Message,Error>> ValidateUserRecipientAsync(Message message, DeleteMessage deleteParams)
{
if (deleteParams.DeleterId == message.RecipientId)
{
return await ForceRemoveAsync(message);
}
else
{
// TODO made hide rules
return Result<Message, Error>.Failure(Error.Failure("MessageRemoving.HaveNoPermission",
$"You do not have permission to delete message {message.Id}"
));
}
}
private async Task<Result<Message, Error>> ForceRemoveAsync(Message message)
{
_govorDbContext.Messages.Remove(message);
await _govorDbContext.SaveChangesAsync();
return message;
} }
} }
+8 -6
View File
@@ -1,7 +1,9 @@
using Govor.Application.Interfaces; using Govor.Application.Interfaces;
using Govor.Domain.Models.Messages; using Govor.Domain.Models.Messages;
using Govor.Domain; using Govor.Domain;
using Govor.Domain.Common;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using SmartRes;
namespace Govor.Application.Messages; namespace Govor.Application.Messages;
@@ -14,7 +16,7 @@ public class MessagesLoader : IMessagesLoader
_dbContext = dbContext; _dbContext = dbContext;
} }
public async Task<List<Message>> LoadMessagesInUserChat( public async Task<Result<List<Message>,Error>> LoadMessagesInUserChat(
Guid privateChatId, Guid privateChatId,
Guid currentUser, Guid currentUser,
Guid? startMessageId, Guid? startMessageId,
@@ -22,11 +24,11 @@ public class MessagesLoader : IMessagesLoader
int after = 2) int after = 2)
{ {
if (privateChatId == Guid.Empty) if (privateChatId == Guid.Empty)
throw new ArgumentException("PrivateChatId id cannot be empty", nameof(privateChatId)); return Result.Failure<List<Message>>(Error.Failure(nameof(ArgumentException),"PrivateChatId id cannot be empty."));
var chatExists = await _dbContext.PrivateChats.AnyAsync(c => c.Id == privateChatId); var chatExists = await _dbContext.PrivateChats.AnyAsync(c => c.Id == privateChatId);
if (!chatExists) if (!chatExists)
return []; return new List<Message>(0);
var query = _dbContext.Messages var query = _dbContext.Messages
.AsNoTracking() .AsNoTracking()
@@ -37,7 +39,7 @@ public class MessagesLoader : IMessagesLoader
return await FetchPaginatedMessagesAsync(query, startMessageId, before, after); return await FetchPaginatedMessagesAsync(query, startMessageId, before, after);
} }
public async Task<List<Message>> LoadMessagesInChatGroup( public async Task<Result<List<Message>,Error>> LoadMessagesInChatGroup(
Guid chatId, Guid chatId,
Guid currentUser, Guid currentUser,
Guid? startMessageId, Guid? startMessageId,
@@ -45,13 +47,13 @@ public class MessagesLoader : IMessagesLoader
int after = 2) int after = 2)
{ {
if (chatId == Guid.Empty) if (chatId == Guid.Empty)
throw new ArgumentException("Chat id cannot be empty", nameof(chatId)); return Result.Failure<List<Message>>(Error.Failure(nameof(ArgumentException),"Chat id cannot be empty."));
var isMember = await _dbContext.GroupMemberships var isMember = await _dbContext.GroupMemberships
.AnyAsync(gm => gm.UserId == currentUser && gm.GroupId == chatId); .AnyAsync(gm => gm.UserId == currentUser && gm.GroupId == chatId);
if (!isMember) if (!isMember)
return []; return new List<Message>(0);
var query = _dbContext.Messages var query = _dbContext.Messages
.AsNoTracking() .AsNoTracking()
@@ -2,4 +2,5 @@ namespace Govor.Application.Messages.Parameters;
public record DeleteMessage( public record DeleteMessage(
Guid DeleterId, Guid DeleterId,
Guid MessageId); Guid MessageId,
bool ForceRemove = false);
@@ -119,7 +119,9 @@ public class PushTokenService : IPushTokenService
await _context.UserPushTokens await _context.UserPushTokens
.Where(t => tokens.Contains(t.Token)) .Where(t => tokens.Contains(t.Token))
.ExecuteDeleteAsync(); .ExecuteDeleteAsync();
await _context.SaveChangesAsync();
return Result.Success(); return Result.Success();
} }
catch (Exception ex) catch (Exception ex)
@@ -42,7 +42,6 @@ public class UserSessionRefresher : IUserSessionRefresher
try try
{ {
var session = await _context.UserSessions var session = await _context.UserSessions
.AsNoTracking()
.Include(userSession => userSession.User) .Include(userSession => userSession.User)
.FirstOrDefaultAsync(s => s.RefreshTokenHash == hashedToken); .FirstOrDefaultAsync(s => s.RefreshTokenHash == hashedToken);
@@ -3,4 +3,5 @@ namespace Govor.Contracts.Requests.SignalR;
public class RemoveMessageRequest public class RemoveMessageRequest
{ {
public Guid MessageId { get; set; } public Guid MessageId { get; set; }
public RemoveMessageRequestType RequestType { get; set; }
} }
@@ -0,0 +1,7 @@
namespace Govor.Contracts.Requests.SignalR;
public enum RemoveMessageRequestType : int
{
HideForMe = 0,
ForceRemove = 1
}
@@ -1,11 +1,13 @@
using Govor.Contracts.Requests.SignalR;
using Govor.Domain.Models.Messages; using Govor.Domain.Models.Messages;
namespace Govor.Contracts.Responses.SignalR; namespace Govor.Contracts.Responses.SignalR;
public class MessageRemovedResponse public class MessageRemovedResponse
{ {
public Guid MessageId { get; set; } public required Guid MessageId { get; set; }
public Guid SenderId { get; set; } public required Guid SenderId { get; set; }
public Guid RecipientId { get; set; } public required Guid RecipientId { get; set; }
public RemoveMessageRequestType RequestType { get; set; }
public RecipientType RecipientType { get; set; } public RecipientType RecipientType { get; set; }
} }
+1 -1
View File
@@ -11,6 +11,6 @@ public record Error(string Code, string Message, ErrorType Type, Dictionary<stri
public static Error Unauthorized(string code, string message) => new(code, message, ErrorType.Unauthorized); public static Error Unauthorized(string code, string message) => new(code, message, ErrorType.Unauthorized);
public static Error Forbidden(string code, string message) => new(code, message, ErrorType.Forbidden); public static Error Forbidden(string code, string message) => new(code, message, ErrorType.Forbidden);
public static Error Failure(string code, string message) => new(code, message, ErrorType.Failure); public static Error Failure(string code, string message) => new(code, message, ErrorType.Failure);
public static Error ServerError(string code, string message) => new(code, message, ErrorType.ServerError);
public override string ToString() => $"{Code}: {Message}"; public override string ToString() => $"{Code}: {Message}";
} }
+2 -1
View File
@@ -7,5 +7,6 @@ public enum ErrorType
NotFound = 2, // (404 Not Found) NotFound = 2, // (404 Not Found)
Conflict = 3, // (409 Conflict) Conflict = 3, // (409 Conflict)
Unauthorized = 4, // (401 Unauthorized) Unauthorized = 4, // (401 Unauthorized)
Forbidden = 5 // (403 Forbidden) Forbidden = 5, // (403 Forbidden)
ServerError = 6 // (500 Server Error)
} }
@@ -12,7 +12,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace Govor.Domain.Migrations namespace Govor.Domain.Migrations
{ {
[DbContext(typeof(GovorDbContext))] [DbContext(typeof(GovorDbContext))]
[Migration("20260716110338_InitialCreate")] [Migration("20260727130055_InitialCreate")]
partial class InitialCreate partial class InitialCreate
{ {
/// <inheritdoc /> /// <inheritdoc />
@@ -20,7 +20,7 @@ namespace Govor.Domain.Migrations
{ {
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder modelBuilder
.HasAnnotation("ProductVersion", "8.0.6") .HasAnnotation("ProductVersion", "10.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63); .HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
@@ -202,6 +202,9 @@ namespace Govor.Domain.Migrations
b.Property<int>("MaxParticipants") b.Property<int>("MaxParticipants")
.HasColumnType("integer"); .HasColumnType("integer");
b.Property<int>("Participants")
.HasColumnType("integer");
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("Invitations"); b.ToTable("Invitations");
@@ -38,7 +38,8 @@ namespace Govor.Domain.Migrations
Description = table.Column<string>(type: "text", nullable: false), Description = table.Column<string>(type: "text", nullable: false),
DateCreated = table.Column<DateTime>(type: "timestamp with time zone", nullable: false), DateCreated = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
EndDate = table.Column<DateTime>(type: "timestamp with time zone", nullable: false), EndDate = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
MaxParticipants = table.Column<int>(type: "integer", nullable: false) MaxParticipants = table.Column<int>(type: "integer", nullable: false),
Participants = table.Column<int>(type: "integer", nullable: false)
}, },
constraints: table => constraints: table =>
{ {
@@ -17,7 +17,7 @@ namespace Govor.Domain.Migrations
{ {
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder modelBuilder
.HasAnnotation("ProductVersion", "8.0.6") .HasAnnotation("ProductVersion", "10.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63); .HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
@@ -199,6 +199,9 @@ namespace Govor.Domain.Migrations
b.Property<int>("MaxParticipants") b.Property<int>("MaxParticipants")
.HasColumnType("integer"); .HasColumnType("integer");
b.Property<int>("Participants")
.HasColumnType("integer");
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("Invitations"); b.ToTable("Invitations");
+1
View File
@@ -12,6 +12,7 @@ public class Invitation
public DateTime DateCreated { get; set; } public DateTime DateCreated { get; set; }
public DateTime EndDate { get; set; } public DateTime EndDate { get; set; }
public int MaxParticipants { get; set; } public int MaxParticipants { get; set; }
public int Participants { get; set; } = 0;
public List<User> Users { get; set; } = new List<User>(); public List<User> Users { get; set; } = new List<User>();
public override bool Equals(object? obj) public override bool Equals(object? obj)
BIN
View File
Binary file not shown.