Refactor: migrate Core -> Domain and reorganize projects

Large refactor that renames/moves core types into a new Govor.Domain surface and reorganizes the Application layer. Models, configurations, migrations and many files moved from Govor.Core/Govor.Data to Govor.Domain; numerous Application services, interfaces and implementations were relocated or added (authentication, friends, messages, medias, push notifications, user sessions, storage, synching, private chats, etc.). Tests updated to use Govor.Domain namespaces and adjusted project references (removed Govor.Data reference from API tests). Also updated API, Hub and mapping code and project files to reflect the new structure and naming. This is primarily a codebase-wide namespace and module reorganization to establish a Domain project and restructure application services.
This commit is contained in:
Artemy
2026-07-16 19:27:45 +07:00
parent 1d35356c8c
commit 6d1c53beeb
371 changed files with 2729 additions and 6694 deletions
@@ -0,0 +1,101 @@
using Govor.Application.Authentication.Exceptions;
using Govor.Application.Infrastructure.Validators;
using Govor.Application.Users;
using Govor.Domain;
using Govor.Domain.Common;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
using Microsoft.EntityFrameworkCore;
namespace Govor.Application.Authentication;
public class AuthService : IAccountService
{
private readonly GovorDbContext _context;
private readonly IPasswordHasher _passwordHasher;
private readonly IUserNameExistValidator _userNameExistValidator;
private readonly IUsernameValidator _usernameValidator;
public AuthService(
GovorDbContext context,
IUserNameExistValidator existValidator,
IPasswordHasher passwordHasher,
IUsernameValidator usernameValidator)
{
_context = context;
_userNameExistValidator = existValidator;
_passwordHasher = passwordHasher;
_usernameValidator = usernameValidator;
}
public async Task<Result<User>> RegistrationAsync(string name, string password, Invitation invitation)
{
var validationResult = _usernameValidator.Validate(name);
if (validationResult.IsFailure)
{
return Result<User>.Failure(validationResult.Error);
}
if (await _userNameExistValidator.IsUsernameExistsAsync(name))
{
return Result<User>.Failure(new Error(
nameof(UserAlreadyExistException),
$"User with username '{name}' already exists."));
}
var passwordHash = _passwordHasher.Hash(password);
var user = new User
{
Id = Guid.NewGuid(),
Username = name,
PasswordHash = passwordHash,
Description = string.Empty,
CreatedOn = DateOnly.FromDateTime(DateTime.UtcNow),
IconId = Guid.Empty,
WasOnline = DateTime.UtcNow,
InviteId = invitation.Id
};
await _context.Users.AddAsync(user);
await SetRoleAsync(user, invitation);
await _context.SaveChangesAsync();
return user; // Success
}
public async Task<Result<User>> LoginAsync(string name, string password)
{
var user = await _context.Users
.AsNoTracking()
.FirstOrDefaultAsync(u => u.Username == name);
if (user is null)
{
return Result<User>.Failure(new Error(
nameof(UserNotRegisteredException),
$"User '{name}' is not registered."));
}
if (!_passwordHasher.Verify(password, user.PasswordHash))
{
return Result<User>.Failure(new Error(
nameof(InvalidOperationException),
"The password provided is incorrect."));
}
return user; // Success
}
private async Task SetRoleAsync(User user, Invitation invitation)
{
if (invitation.IsAdmin)
{
await _context.Admins.AddAsync(new Admin { UserId = user.Id });
}
}
}
@@ -1,6 +1,6 @@
using Govor.Core;
using Govor.Domain;
namespace Govor.Application.Exceptions.AuthService;
namespace Govor.Application.Authentication.Exceptions;
public class InvalidUsernameException(string message) : GovorCoreException(message)
{
@@ -0,0 +1,5 @@
using Govor.Domain;
namespace Govor.Application.Authentication.Exceptions;
public class LoginUserException : GovorCoreException { }
@@ -0,0 +1,5 @@
using Govor.Domain;
namespace Govor.Application.Authentication.Exceptions;
public class UserAlreadyExistException(string username) : GovorCoreException($"{username} is already exists!") { }
@@ -0,0 +1,5 @@
using Govor.Domain;
namespace Govor.Application.Authentication.Exceptions;
public class UserNotRegisteredException(string username) : GovorCoreException($"{username} is not registered!") { }
@@ -0,0 +1,11 @@
using Govor.Domain.Common;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
namespace Govor.Application.Authentication;
public interface IAccountService
{
public Task<Result<User>> RegistrationAsync(string name, string password, Invitation invitation);
public Task<Result<User>> LoginAsync(string name, string password);
}
@@ -0,0 +1,12 @@
using Govor.Domain.Common;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
namespace Govor.Application.Authentication;
public interface IInvitesService
{
public Task<string> GetRoleNameAsync(User user);
public Task<string> GetRoleNameAsync(Guid sessionId);
public Task<Result<Invitation>> ValidateAsync(string inviteCode);
}
@@ -1,4 +1,4 @@
namespace Govor.Core.Infrastructure.Extensions;
namespace Govor.Application.Authentication;
public interface IPasswordHasher
{
@@ -0,0 +1,56 @@
using Govor.Application.Exceptions.InvitesService;
using Govor.Domain;
using Govor.Domain.Common;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
using Microsoft.EntityFrameworkCore;
namespace Govor.Application.Authentication;
public class InvitesService : IInvitesService
{
private readonly GovorDbContext _context;
public InvitesService(GovorDbContext context)
{
_context = context;
}
public async Task<string> GetRoleNameAsync(User user)
{
return await GetRoleNameAsync(user.InviteId);
}
public async Task<string> GetRoleNameAsync(Guid sessionId)
{
var invitation = await _context.Invitations.FirstOrDefaultAsync(s => s.Id == sessionId);
if (invitation == null)
return "User";
return invitation.IsAdmin ? "Admin" : "User";
}
public async Task<Result<Invitation>> ValidateAsync(string inviteCode)
{
var invite = await _context.Invitations
.Include(s => s.Users)
.FirstOrDefaultAsync(s => s.Code == inviteCode);
if (invite == null)
return Result<Invitation>.Failure(Error.Null);
if (invite.EndDate < DateTime.Now || invite.MaxParticipants <= invite.Users.Count)
{
invite.IsActive = false;
await _context.SaveChangesAsync();
return Result<Invitation>.Failure(new Error(
"Auth.InviteLinkInvalid", $"Invite link invalid: {inviteCode}")
);
}
return invite;
}
}
@@ -1,7 +1,7 @@
using System.Security.Claims;
using Govor.Core.Models.Users;
using Govor.Domain.Models.Users;
namespace Govor.Application.Interfaces.Authentication;
namespace Govor.Application.Authentication.JWT;
public interface IJwtService
{
@@ -1,4 +1,4 @@
namespace Govor.Application.Interfaces.Authentication;
namespace Govor.Application.Authentication.JWT;
public interface IJwtTokenHasher
{
@@ -1,4 +1,4 @@
namespace Govor.Application.Services.Authentication;
namespace Govor.Application.Authentication.JWT;
public class JwtAccessOption
{
public string SecretKey {get; set;}
@@ -1,4 +1,4 @@
namespace Govor.Application.Services.Authentication;
namespace Govor.Application.Authentication.JWT;
public class JwtRefreshOption
{
@@ -1,12 +1,11 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Govor.Application.Interfaces.Authentication;
using Govor.Core.Models.Users;
using Govor.Domain.Models.Users;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
namespace Govor.Application.Services.Authentication;
namespace Govor.Application.Authentication.JWT;
public class JwtService : IJwtService
{
@@ -27,7 +26,7 @@ public class JwtService : IJwtService
{
new Claim("userId", user.Id.ToString()),
new Claim("sid", sessionId.ToString()),
new Claim(ClaimTypes.Role, await _invitesService.GetRoleAsync(user), ClaimValueTypes.String)
new Claim(ClaimTypes.Role, await _invitesService.GetRoleNameAsync(user), ClaimValueTypes.String)
};
var singing = new SigningCredentials(
@@ -1,9 +1,8 @@
using System.Security.Cryptography;
using System.Text;
using Govor.Application.Interfaces.Authentication;
using Microsoft.Extensions.Configuration;
namespace Govor.Application.Services.Authentication;
namespace Govor.Application.Authentication.JWT;
public class JwtTokenHasher : IJwtTokenHasher
{
@@ -1,6 +1,6 @@
using Govor.Core.Infrastructure.Extensions;
using Govor.Domain.Common.Extensions;
namespace Govor.Application.Services.Authentication;
namespace Govor.Application.Authentication;
public class PasswordHasher : IPasswordHasher
{
@@ -1,5 +0,0 @@
using Govor.Core;
namespace Govor.Application.Exceptions.AuthService;
public class LoginUserException : GovorCoreException { }
@@ -1,5 +0,0 @@
using Govor.Core;
namespace Govor.Application.Exceptions.AuthService;
public class UserAlreadyExistException(string username) : GovorCoreException($"{username} is already exists!") { }
@@ -1,5 +0,0 @@
using Govor.Core;
namespace Govor.Application.Exceptions.AuthService;
public class UserNotRegisteredException(string username) : GovorCoreException($"{username} is not registered!") { }
@@ -1,4 +1,4 @@
using Govor.Core;
using Govor.Domain;
namespace Govor.Application.Exceptions.FriendsService;
@@ -1,4 +1,4 @@
using Govor.Core;
using Govor.Domain;
namespace Govor.Application.Exceptions.FriendsService;
@@ -1,4 +1,4 @@
using Govor.Core;
using Govor.Domain;
namespace Govor.Application.Exceptions.FriendsService;
@@ -1,4 +1,4 @@
using Govor.Core;
using Govor.Domain;
namespace Govor.Application.Exceptions.InvitesService;
@@ -1,4 +1,4 @@
using Govor.Core;
using Govor.Domain;
namespace Govor.Application.Exceptions.VerifyFriendship;
@@ -0,0 +1,126 @@
using Govor.Application.Exceptions.FriendsService;
using Govor.Application.Interfaces;
using Govor.Application.PrivateUserChats;
using Govor.Domain;
using Govor.Domain.Common;
using Govor.Domain.Models;
using Microsoft.EntityFrameworkCore;
namespace Govor.Application.Friends;
public class FriendRequestCommandService : IFriendRequestCommandService
{
private readonly GovorDbContext _context;
private readonly IUserPrivateChatsCreator _privateChatsCreator;
public FriendRequestCommandService(
GovorDbContext context,
IUserPrivateChatsCreator privateChatsCreator)
{
_context = context;
_privateChatsCreator = privateChatsCreator;
}
public async Task<Result<Friendship>> SendAsync(Guid fromUserId, Guid toUserId)
{
if (fromUserId == toUserId)
return Result<Friendship>.Failure(new Error(
"Friendship.Send",
"Cannot send a request to self user")
);
var friendship = await _context.Friendships
.FirstOrDefaultAsync(f => (f.RequesterId == fromUserId && f.AddresseeId == toUserId) ||
(f.RequesterId == toUserId && f.AddresseeId == fromUserId));
if (friendship is null)
{
friendship = new Friendship
{
Id = Guid.NewGuid(),
RequesterId = fromUserId,
AddresseeId = toUserId,
Status = FriendshipStatus.Pending
};
await _context.Friendships.AddAsync(friendship);
}
else
{
if (friendship.Status == FriendshipStatus.Pending ||
friendship.Status == FriendshipStatus.Accepted ||
friendship.Status == FriendshipStatus.Blocked)
{
return Result<Friendship>.Failure(new Error(
"Friendship.Send",
$"The request is already {friendship.Status}")
);
}
friendship.RequesterId = fromUserId;
friendship.AddresseeId = toUserId;
friendship.Status = FriendshipStatus.Pending;
}
await _context.SaveChangesAsync();
return friendship;
}
public async Task<Result<Friendship>> AcceptAsync(Guid requestId, Guid currentUserId)
{
var friendship = await _context.Friendships.FindAsync(requestId);
if (friendship is null)
return Result<Friendship>.Failure(new Error(
"Friendship.Accept",
"Friendship not found! You cant accept request!")
);
if (friendship.AddresseeId != currentUserId)
return Result<Friendship>.Failure(new Error(
"Friendship.Accept",
"You cannot accept this request!")
);
if (friendship.Status != FriendshipStatus.Pending)
return Result<Friendship>.Failure(new Error(
"Friendship.Accept",
"Request is already accepted!")
);
friendship.Status = FriendshipStatus.Accepted;
await _context.SaveChangesAsync();
await _privateChatsCreator.CreateAsync(friendship.AddresseeId, friendship.RequesterId);
return friendship;
}
public async Task<Result<Friendship>> RejectAsync(Guid requestId, Guid currentUserId)
{
var friendship = await _context.Friendships.FindAsync(requestId);
if (friendship == null)
return Result<Friendship>.Failure(new Error(
"Friendship.Reject",
"Friendship not found! You cant reject request!")
);
if (friendship.AddresseeId != currentUserId)
return Result<Friendship>.Failure(new Error(
"Friendship.Reject",
"You cannot reject this request!")
);
if (friendship.Status != FriendshipStatus.Pending && friendship.Status != FriendshipStatus.Rejected)
return Result<Friendship>.Failure(new Error(
"Friendship.Reject",
$"Request is already {friendship.Status}")
);
friendship.Status = FriendshipStatus.Rejected;
await _context.SaveChangesAsync();
return friendship;
}
}
@@ -0,0 +1,36 @@
using Microsoft.EntityFrameworkCore;
using Govor.Domain;
using Govor.Domain.Models;
namespace Govor.Application.Friends;
public class FriendRequestQueryService : IFriendRequestQueryService
{
private readonly GovorDbContext _context;
public FriendRequestQueryService(GovorDbContext context)
{
_context = context;
}
public async Task<List<Friendship>> GetIncomingAsync(Guid userId)
{
return await _context.Friendships
.AsNoTracking()
.Include(f => f.Requester)
.Include(f => f.Addressee)
.Where(f => f.AddresseeId == userId && f.Status == FriendshipStatus.Pending)
.ToListAsync();
}
public async Task<List<Friendship>> GetResponsesAsync(Guid userId)
{
return await _context.Friendships
.AsNoTracking()
.Include(f => f.Requester)
.Include(f => f.Addressee)
.Where(f => f.RequesterId == userId && f.Status != FriendshipStatus.Accepted)
.ToListAsync();
}
}
@@ -1,6 +1,4 @@
using Govor.Application.Interfaces;
namespace Govor.Application.Services.Friends;
namespace Govor.Application.Friends;
public class FriendsBlockService : IFriendsBlockService
{
@@ -0,0 +1,62 @@
using Microsoft.EntityFrameworkCore;
using Govor.Domain;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
namespace Govor.Application.Friends;
public class FriendshipService : IFriendshipService
{
private readonly GovorDbContext _context;
public FriendshipService(GovorDbContext context)
{
_context = context;
}
public async Task<List<User>> SearchUsersAsync(string query, Guid currentId)
{
if (string.IsNullOrWhiteSpace(query))
{
return [];
}
return await _context.Users
.AsNoTracking()
.Where(u => u.Id != currentId && u.Username.Contains(query))
.Take(5)
.ToListAsync();
}
public async Task<List<User>> GetPotentialFriendsAsync(Guid userId)
{
var pendingFriendships = await _context.Friendships
.AsNoTracking()
.Include(f => f.Requester)
.Include(f => f.Addressee)
.Where(f => (f.RequesterId == userId || f.AddresseeId == userId)
&& f.Status == FriendshipStatus.Pending)
.ToListAsync();
return pendingFriendships
.Select(f => f.RequesterId == userId ? f.Addressee : f.Requester)
.ToList();
}
public async Task<List<User>> GetFriendsAsync(Guid userId)
{
var acceptedFriendships = await _context.Friendships
.AsNoTracking()
.Include(f => f.Requester)
.Include(f => f.Addressee)
.Where(f => (f.RequesterId == userId || f.AddresseeId == userId)
&& f.Status == FriendshipStatus.Accepted)
.ToListAsync();
var friends = acceptedFriendships
.Select(f => f.RequesterId == userId ? f.Addressee : f.Requester)
.ToList();
return friends;
}
}
@@ -0,0 +1,11 @@
using Govor.Domain.Common;
using Govor.Domain.Models;
namespace Govor.Application.Friends;
public interface IFriendRequestCommandService
{
Task<Result<Friendship>> SendAsync(Guid fromUserId, Guid toUserId);
Task<Result<Friendship>> AcceptAsync(Guid requestId, Guid currentUserId);
Task<Result<Friendship>> RejectAsync(Guid requestId, Guid currentUserId);
}
@@ -1,6 +1,6 @@
using Govor.Core.Models;
using Govor.Domain.Models;
namespace Govor.Application.Interfaces.Friends;
namespace Govor.Application.Friends;
public interface IFriendRequestQueryService
@@ -1,4 +1,4 @@
namespace Govor.Application.Interfaces;
namespace Govor.Application.Friends;
public interface IFriendsBlockService
{
@@ -1,6 +1,6 @@
using Govor.Core.Models.Users;
using Govor.Domain.Models.Users;
namespace Govor.Application.Interfaces.Friends;
namespace Govor.Application.Friends;
public interface IFriendshipService
{
@@ -1,4 +1,4 @@
namespace Govor.Application.Interfaces;
namespace Govor.Application.Friends;
public interface IVerifyFriendship
{
@@ -0,0 +1,59 @@
using Microsoft.EntityFrameworkCore;
using Govor.Application.Exceptions.VerifyFriendship;
using Govor.Domain;
using Govor.Domain.Models;
using Microsoft.Extensions.Logging;
namespace Govor.Application.Friends;
public class VerifyFriendship : IVerifyFriendship
{
private readonly GovorDbContext _dbContext;
private readonly ILogger<VerifyFriendship> _logger;
private const string FriendshipNotAcceptedError = "Friendship between user {0} and friend {1} does not exist or is not accepted.";
public VerifyFriendship(GovorDbContext dbContext, ILogger<VerifyFriendship> logger)
{
_dbContext = dbContext;
_logger = logger;
}
public async Task VerifyAsync(Guid targetUserId, Guid friendUserId)
{
if (targetUserId == Guid.Empty || friendUserId == Guid.Empty)
{
_logger.LogWarning("Invalid user IDs provided: targetUserId={TargetUserId}, friendUserId={FriendUserId}", targetUserId, friendUserId);
throw new ArgumentException("User IDs cannot be empty.");
}
var isFriendshipAccepted = await _dbContext.Friendships
.AsNoTracking()
.AnyAsync(f => f.Status == FriendshipStatus.Accepted &&
((f.RequesterId == targetUserId && f.AddresseeId == friendUserId) ||
(f.RequesterId == friendUserId && f.AddresseeId == targetUserId)));
if (!isFriendshipAccepted)
{
var errorMessage = string.Format(FriendshipNotAcceptedError, targetUserId, friendUserId);
_logger.LogError(errorMessage);
throw new FriendshipException(errorMessage);
}
_logger.LogInformation("Friendship verified successfully for targetUserId={TargetUserId}, friendUserId={FriendUserId}", targetUserId, friendUserId);
}
public async Task<bool> TryVerifyAsync(Guid targetUserId, Guid friendUserId)
{
if (targetUserId == Guid.Empty || friendUserId == Guid.Empty)
{
return false;
}
return await _dbContext.Friendships
.AsNoTracking()
.AnyAsync(f => f.Status == FriendshipStatus.Accepted &&
((f.RequesterId == targetUserId && f.AddresseeId == friendUserId) ||
(f.RequesterId == friendUserId && f.AddresseeId == targetUserId)));
}
}
+9 -5
View File
@@ -6,19 +6,23 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Govor.Core\Govor.Core.csproj" />
<ProjectReference Include="..\Govor.Data\Govor.Data.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="FirebaseAdmin" Version="3.4.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.3.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.6" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="11.0.0-preview.1.26104.118" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.0.1" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Govor.Domain\Govor.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Exceptions\AuthService\" />
</ItemGroup>
</Project>
@@ -1,8 +1,8 @@
using Govor.Application.Interfaces.Messages.Parameters;
using Govor.Core.Models;
using Govor.Core.Models.Users;
using Govor.Domain.Common;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
namespace Govor.Application.Interfaces;
namespace Govor.Application.Groups;
public interface IGroupService
{
@@ -1,6 +1,6 @@
using Govor.Core.Models;
using Govor.Domain.Models;
namespace Govor.Application.Interfaces;
namespace Govor.Application.Groups;
public interface IUserGroupsGetterService
{
@@ -0,0 +1,25 @@
using Govor.Domain;
using Govor.Domain.Models;
using Microsoft.EntityFrameworkCore;
namespace Govor.Application.Groups;
public class UserGroupsGetterService : IUserGroupsGetterService
{
private readonly GovorDbContext _context;
public UserGroupsGetterService(GovorDbContext context)
{
_context = context;
}
public async Task<List<ChatGroup>> GetUserGroupsAsync(Guid userId)
{
return await _context.GroupMemberships
.AsNoTracking()
.Where(m => m.UserId == userId)
.Select(m => m.ChatGroup)
.ToListAsync();
}
}
@@ -0,0 +1,10 @@
using Govor.Domain.Common;
using Govor.Domain.Models;
namespace Govor.Application.Infrastructure.AdminsStuff;
public interface IInvitationGetter
{
Task<List<Invitation>> GetAllAsync();
Task<Result<Invitation>> FindByIdAsync(Guid id);
}
@@ -1,4 +1,4 @@
namespace Govor.Application.Interfaces;
namespace Govor.Application.Infrastructure.AdminsStuff;
public interface IInvitationGenerator
{
@@ -1,6 +1,6 @@
using Govor.Core.Models.Users;
using Govor.Domain.Models.Users;
namespace Govor.Application.Interfaces;
namespace Govor.Application.Infrastructure.AdminsStuff;
public interface IUsersAdministration
{
@@ -1,10 +1,9 @@
using Govor.Application.Interfaces;
using Govor.Core.Models;
using Govor.Core.Repositories.Invaites;
using Govor.Domain;
using Govor.Domain.Models;
namespace Govor.Application.Infrastructure.AdminsStuff;
public class InvitationGenerator(IInvitesRepository repository) : IInvitationGenerator
public class InvitationGenerator(GovorDbContext context) : IInvitationGenerator
{
public async Task<string> GenerateInvitationCode(DateTime time, int maxUsers, bool isAdmin, string description = "")
{
@@ -19,7 +18,9 @@ public class InvitationGenerator(IInvitesRepository repository) : IInvitationGen
IsAdmin = isAdmin
};
await repository.AddAsync(newInvitation);
await context.Invitations.AddAsync(newInvitation);
await context.SaveChangesAsync();
return newInvitation.Code;
}
@@ -0,0 +1,41 @@
using Govor.Domain;
using Govor.Domain.Common;
using Govor.Domain.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Govor.Application.Infrastructure.AdminsStuff;
public class InvitationGetter : IInvitationGetter
{
private readonly ILogger<InvitationGetter> _logger;
private readonly GovorDbContext _context;
public InvitationGetter(ILogger<InvitationGetter> logger, GovorDbContext context)
{
_logger = logger;
_context = context;
}
public async Task<List<Invitation>> GetAllAsync()
{
return await _context.Invitations
.AsNoTracking()
.Where(iv => iv.IsActive)
.ToListAsync();
}
public async Task<Result<Invitation>> FindByIdAsync(Guid id)
{
var res = await _context.Invitations.AsNoTracking()
.FirstOrDefaultAsync(iv => iv.Id == id);
if (res is null)
return Result<Invitation>.Failure(new Error(
nameof(InvalidOperationException),
"Invitation not found.")
);
return res;
}
}
@@ -1,54 +1,45 @@
using Govor.Application.Interfaces;
using Govor.Core.Infrastructure.Extensions;
using Govor.Core.Models.Users;
using Govor.Core.Repositories.Users;
using Govor.Data.Repositories.Exceptions;
using Govor.Application.Authentication;
using Govor.Domain;
using Govor.Domain.Models.Users;
using Microsoft.EntityFrameworkCore;
namespace Govor.Application.Infrastructure.AdminsStuff;
public class UsersService : IUsersAdministration
{
private readonly IUsersRepository _usersRepository;
private readonly GovorDbContext _context;
private readonly IPasswordHasher _passwordHasher;
public UsersService(IUsersRepository usersRepository, IPasswordHasher passwordHasher)
public UsersService(GovorDbContext context, IPasswordHasher passwordHasher)
{
_usersRepository = usersRepository;
_context = context;
_passwordHasher = passwordHasher;
}
public async Task<List<User>> GetAllUsersAsync()
{
try
{
var results = await _usersRepository.GetAllAsync();
return results;
}
catch (NotFoundException ex)
{
return new List<User>();
}
var results = await _context.Users
.AsNoTracking()
.Take(50)
.ToListAsync();
return results;
}
public async Task SetPasswordAsync(Guid userId, string password)
{
try
{
var user = await _usersRepository.FindByIdAsync(userId);
user.PasswordHash = _passwordHasher.Hash(password);
await _usersRepository.UpdateAsync(user);
}
catch (NotFoundException ex)
{
throw new NotFoundException(ex.Message);
}
var user = await GetUserById(userId);
if (user is null)
return;
user.PasswordHash = _passwordHasher.Hash(password);
await _context.SaveChangesAsync();
}
public async Task<User> GetUserById(Guid userId)
{
var result = await _usersRepository.FindByIdAsync(userId);
var result = await _context.Users.FirstOrDefaultAsync(user => user.Id == userId);
return result;
}
@@ -1,5 +1,3 @@
using System.Security.Claims;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Microsoft.AspNetCore.Http;
namespace Govor.Application.Infrastructure.Extensions;
@@ -1,4 +1,3 @@
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Microsoft.AspNetCore.Http;
namespace Govor.Application.Infrastructure.Extensions;
@@ -1,4 +1,4 @@
namespace Govor.Application.Interfaces;
namespace Govor.Application.Infrastructure.Extensions;
public interface IConnectionStore
{
@@ -1,4 +1,4 @@
namespace Govor.Application.Interfaces.Infrastructure.Extensions;
namespace Govor.Application.Infrastructure.Extensions;
public interface ICurrentUserService
{
@@ -1,4 +1,4 @@
namespace Govor.Application.Interfaces.Infrastructure.Extensions;
namespace Govor.Application.Infrastructure.Extensions;
public interface ICurrentUserSessionService
{
@@ -1,7 +1,7 @@
using Govor.Core.Models;
using Govor.Core.Models.Users;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
namespace Govor.Application.Interfaces;
namespace Govor.Application.Infrastructure.Extensions;
public interface IFriendsService
{
@@ -0,0 +1,9 @@
using Govor.Domain.Common;
namespace Govor.Application.Infrastructure.Validators;
public interface IUsernameValidator
{
Result Validate(string username);
bool TryValidate(string username);
}
@@ -1,13 +1,15 @@
using System.Text.RegularExpressions;
using Govor.Application.Exceptions.AuthService;
using Govor.Application.Interfaces.Authentication;
using Govor.Core.Infrastructure.Validators;
using Govor.Application.Authentication.Exceptions;
using Govor.Domain.Common.Constants;
using Govor.Domain.Common;
using Microsoft.Extensions.Configuration;
namespace Govor.Application.Infrastructure.Validators;
public class UsernameValidator : IUsernameValidator
{
private const string ErrorCode = nameof(InvalidUsernameException);
private readonly Regex _usernameRegex = new(@"^[А-Яа-яЁё]+[А-Яа-яЁё0-9]*$", RegexOptions.Compiled);
private readonly HashSet<string> _blockedExact;
@@ -37,43 +39,61 @@ public class UsernameValidator : IUsernameValidator
?? throw new InvalidOperationException("Reserved not set");
}
public void Validate(string username)
public Result Validate(string username)
{
if(username.Length < UserValidator.MIN_LENGHT_OF_NAME || username.Length > UserValidator.MAX_LENGHT_OF_NAME)
throw new InvalidUsernameException($"Username must be between {UserValidator.MIN_LENGHT_OF_NAME} and {UserValidator.MAX_LENGHT_OF_NAME} characters.");
if (!_usernameRegex.IsMatch(username))
throw new InvalidUsernameException("The username must be in Cyrillic and start with a letter.");
if (username.Length < UserConstants.MIN_LENGHT_OF_NAME || username.Length > UserConstants.MAX_LENGHT_OF_NAME)
{
return new Error(
ErrorCode,
$"Username must be between {UserConstants.MIN_LENGHT_OF_NAME} and {UserConstants.MAX_LENGHT_OF_NAME} characters.");
}
if (!_usernameRegex.IsMatch(username))
{
return new Error(
ErrorCode,
"The username must be in Cyrillic and start with a letter.");
}
if (Regex.IsMatch(username, @"(.)\1{4,}"))
throw new InvalidUsernameException("Too many repeating characters.");
{
return new Error(
ErrorCode,
"Too many repeating characters.");
}
var normalized = Normalize(username);
if (_reserved.Contains(normalized))
throw new InvalidUsernameException("This username is reserved.");
{
return new Error(
ErrorCode,
"This username is reserved.");
}
if (_blockedExact.Contains(normalized))
throw new InvalidUsernameException("This username is not allowed.");
{
return new Error(
ErrorCode,
"This username is not allowed.");
}
foreach (var banned in _blockedContains)
{
if (normalized.Contains(banned))
throw new InvalidUsernameException("Username contains prohibited content.");
{
return new Error(
ErrorCode,
"Username contains prohibited content.");
}
}
return Result.Success();
}
public bool TryValidate(string username)
{
try
{
Validate(username);
return true;
}
catch
{
return false;
}
return Validate(username).IsSuccess;
}
private static string Normalize(string username)
@@ -87,4 +107,4 @@ public class UsernameValidator : IUsernameValidator
.Replace("6", "б")
.Replace("8", "в");
}
}
}
@@ -1,10 +0,0 @@
using Govor.Core.Models;
using Govor.Core.Models.Users;
namespace Govor.Application.Interfaces.Authentication;
public interface IAccountService
{
public Task<User> RegistrationAsync(string name, string password, Invitation invitation);
public Task<User> LoginAsync(string name, string password);
}
@@ -1,10 +0,0 @@
using Govor.Core.Models;
using Govor.Core.Models.Users;
namespace Govor.Application.Interfaces.Authentication;
public interface IInvitesService
{
public Task<string> GetRoleAsync(User user);
public Task<Invitation> ValidateAsync(string inviteCode);
}
@@ -1,8 +0,0 @@
using Govor.Core.Infrastructure.Validators;
namespace Govor.Application.Interfaces.Authentication;
public interface IUsernameValidator : IObjectValidator<string>
{
}
@@ -1,10 +0,0 @@
using Govor.Core.Models;
namespace Govor.Application.Interfaces.Friends;
public interface IFriendRequestCommandService
{
Task<Friendship> SendAsync(Guid fromUserId, Guid toUserId);
Task<Friendship> AcceptAsync(Guid requestId, Guid currentUserId);
Task<Friendship> RejectAsync(Guid requestId, Guid currentUserId);
}
@@ -1,10 +0,0 @@
using Govor.Application.Profiles;
namespace Govor.Application.Interfaces;
public interface IProfileService
{
public Task<UserProfile> GetUserProfileAsync(Guid userId);
public Task SetDescription(string description, Guid userId);
public Task SetNewIcon(Guid userId, Guid iconId);
}
@@ -1,8 +0,0 @@
using Govor.Core.Models;
namespace Govor.Application.Interfaces;
public interface IUserPrivateChatsGetterService
{
Task<List<PrivateChat>> GetUserChatsAsync(Guid userId);
}
@@ -1,30 +0,0 @@
using Govor.Application.Interfaces.Messages.Parameters;
using Govor.Core.Models.Messages;
namespace Govor.Application.Interfaces.Messages;
// Combining IChatService and IGroupService functionalities relevant to messages
public interface IMessageCommandService
{
Task<SendMessageResult> SendMessageAsync(SendMessage messageParameters);
Task<EditMessageResult> EditMessageAsync(EditMessage messageParameters);
Task<DeleteMessageResult> DeleteMessageAsync(DeleteMessage messageParameters);
// Potentially other message-related methods like:
// Task<GetMessagesResult> GetMessagesAsync(Guid userId, Guid chatId, RecipientType chatType, int pageNumber, int pageSize);
// Task<Result> MarkMessageAsReadAsync(Guid userId, Guid messageId);
}
public record SendMessageResult(bool IsSuccess, Exception? Exception, Message Message)
: Result(IsSuccess, Exception, Message?.Id ?? Guid.Empty);
public record EditMessageResult(bool IsSuccess, Exception? Exception, Message? OriginalMessage)
: Result(IsSuccess, Exception, OriginalMessage?.Id ?? Guid.Empty)
{
}
public record DeleteMessageResult(bool IsSuccess, Exception? Exception, Message? OriginalMessage)
: Result(IsSuccess, Exception, OriginalMessage?.Id ?? Guid.Empty);
@@ -1,5 +0,0 @@
namespace Govor.Application.Interfaces.Messages.Parameters;
public record DeleteMessage(
Guid DeleterId,
Guid MessageId);
@@ -1,3 +0,0 @@
namespace Govor.Application.Interfaces.Messages.Parameters;
public record Result(bool IsSuccess, Exception Exception, Guid messageId);
@@ -1,5 +0,0 @@
using Govor.Core.Models;
namespace Govor.Application.Interfaces.Messages.Parameters;
public record SendMedia(Guid MediaId, string EncryptedKey);
@@ -1,10 +0,0 @@
namespace Govor.Application.Interfaces.PushNotifications;
public interface IPushNotificationService
{
Task SendToUserAsync(Guid userId, string title, string body, string channelId, string tag = "", Dictionary<string, string>? data = null);
Task SendToUsersAsync(IEnumerable<Guid> userIds, string title, string body, string channelId, string tag = "", Dictionary<string, string>? data = null);
Task SendToSessionAsync(Guid sessionId, string title, string body, string channelId, string tag = "", Dictionary<string, string>? data = null);
}
@@ -1,10 +0,0 @@
using Govor.Core.Models.Users;
namespace Govor.Application.Interfaces.UserSession;
public interface IUserSessionOpener
{
Task<RefreshResult> OpenSessionAsync(User user, string deviceInfo);
}
@@ -1,6 +0,0 @@
namespace Govor.Application.Interfaces.UserSession;
public interface IUserSessionReader
{
Task<List<Core.Models.Users.UserSession>> GetAllSessionsAsync(Guid userId);
}
@@ -1,8 +0,0 @@
namespace Govor.Application.Interfaces.UserSession;
public interface IUserSessionRefresher
{
Task<RefreshResult> RefreshTokenAsync(string refreshToken);
}
public record RefreshResult(string refreshToken, string accessToken);
@@ -1,8 +0,0 @@
namespace Govor.Application.Interfaces.UserSession;
public interface IUserSessionRevoker
{
Task CloseSessionByIdAsync(Guid sessionId, Guid userId);
Task CloseAllSessionsAsync(Guid userId);
}
@@ -1,9 +1,8 @@
using Govor.Application.Interfaces.Medias;
using Govor.Core.Models;
using Govor.Data;
using Govor.Domain.Models;
using Govor.Domain;
using Microsoft.EntityFrameworkCore;
namespace Govor.Application.Services.Medias;
namespace Govor.Application.Medias;
public class AccesserToDownloadMediaService : IAccesserToDownloadMedia
{
@@ -1,4 +1,4 @@
namespace Govor.Application.Interfaces.Medias;
namespace Govor.Application.Medias;
public interface IAccesserToDownloadMedia
{
@@ -1,7 +1,7 @@
using Govor.Core.Models;
using Govor.Core.Models.Messages;
using Govor.Domain.Models;
using Govor.Domain.Models.Messages;
namespace Govor.Application.Interfaces.Medias;
namespace Govor.Application.Medias;
public interface IMediaService
{
@@ -1,11 +1,10 @@
using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Medias;
using Govor.Core.Models;
using Govor.Data;
using Govor.Application.Storage;
using Govor.Domain.Models;
using Govor.Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Govor.Application.Services.Medias;
namespace Govor.Application.Medias;
public class MediaService : IMediaService
{
@@ -0,0 +1,8 @@
using Govor.Application.Messages.Parameters;
namespace Govor.Application.Messages;
public interface IMessageEditingService
{
Task<EditMessageResult> EditMessageAsync(EditMessage editParams);
}
@@ -0,0 +1,8 @@
using Govor.Application.Messages.Parameters;
namespace Govor.Application.Messages;
public interface IMessageRemovingService
{
Task<DeleteMessageResult> DeleteMessageAsync(DeleteMessage deleteParams);
}
@@ -0,0 +1,8 @@
using Govor.Application.Messages.Parameters;
namespace Govor.Application.Messages;
public interface IMessageSendingService
{
Task<SendMessageResult> SendMessageAsync(SendMessage sendParams);
}
@@ -1,6 +1,6 @@
using Govor.Core.Models.Messages;
using Govor.Domain.Models.Messages;
namespace Govor.Application.Interfaces;
namespace Govor.Application.Messages;
public interface IMessagesLoader
{
@@ -0,0 +1,57 @@
using Govor.Application.Messages.Parameters;
using Microsoft.EntityFrameworkCore;
using Govor.Domain;
using Govor.Domain.Models.Messages;
using Microsoft.Extensions.Logging;
namespace Govor.Application.Messages;
public class MessageEditingService : IMessageEditingService
{
private readonly GovorDbContext _dbContext;
private readonly ILogger<MessageEditingService> _logger;
public MessageEditingService(GovorDbContext dbContext, ILogger<MessageEditingService> logger)
{
_dbContext = dbContext;
_logger = logger;
}
public async Task<EditMessageResult> EditMessageAsync(EditMessage editParams)
{
var message = await _dbContext.Messages
.Include(m => m.MediaAttachments)
.FirstOrDefaultAsync(m => m.Id == editParams.MessageId);
if (message == null)
{
return new EditMessageResult(false, new KeyNotFoundException("Message not found."), null);
}
if (message.SenderId != editParams.EditorId)
{
_logger.LogWarning("User {EditorId} unauthorized to edit message {MessageId}", editParams.EditorId, editParams.MessageId);
return new EditMessageResult(false, new UnauthorizedAccessException("User is not authorized to edit this message."), null);
}
var originalMessageSnapshot = new Message
{
Id = message.Id,
SenderId = message.SenderId,
RecipientId = message.RecipientId,
RecipientType = message.RecipientType,
SentAt = message.SentAt,
ReplyToMessageId = message.ReplyToMessageId,
MediaAttachments = message.MediaAttachments?.ToList() ?? []
};
message.EncryptedContent = editParams.NewContent;
message.IsEdited = true;
message.EditedAt = editParams.EditedAt;
await _dbContext.SaveChangesAsync();
_logger.LogInformation("Message {MessageId} edited successfully.", editParams.MessageId);
return new EditMessageResult(true, null, originalMessageSnapshot);
}
}
@@ -0,0 +1,24 @@
using Govor.Application.Messages.Parameters;
using Govor.Domain;
using Microsoft.Extensions.Logging;
namespace Govor.Application.Messages;
public class MessageRemovingService : IMessageRemovingService
{
private readonly GovorDbContext _govorDbContext;
private readonly ILogger<MessageRemovingService> _logger;
public MessageRemovingService
(GovorDbContext govorDbContext,
ILogger<MessageRemovingService> logger)
{
_govorDbContext = govorDbContext;
_logger = logger;
}
public Task<DeleteMessageResult> DeleteMessageAsync(DeleteMessage deleteParams)
{
throw new NotImplementedException();
}
}
@@ -0,0 +1,77 @@
using Govor.Application.Messages.Parameters;
using Microsoft.EntityFrameworkCore;
using Govor.Domain;
using Govor.Domain.Models.Messages;
using Microsoft.Extensions.Logging;
namespace Govor.Application.Messages;
public class MessageSendingService : IMessageSendingService
{
private readonly GovorDbContext _dbContext;
private readonly ILogger<MessageSendingService> _logger;
public MessageSendingService(GovorDbContext dbContext, ILogger<MessageSendingService> logger)
{
_dbContext = dbContext;
_logger = logger;
}
public async Task<SendMessageResult> SendMessageAsync(SendMessage sendParams)
{
var validationResult = sendParams.RecipientType switch
{
RecipientType.User => await ValidateUserRecipientAsync(sendParams.RecipientId),
RecipientType.Group => await ValidateGroupRecipientAsync(sendParams.FromUserId, sendParams.RecipientId),
_ => (Success: false, Error: "Invalid recipient type.")
};
if (!validationResult.Success)
{
_logger.LogWarning("Message send failed: {Error}", validationResult.Error);
return new SendMessageResult(false, new InvalidOperationException(validationResult.Error), default);
}
var messageId = Guid.NewGuid();
var message = new Message
{
Id = messageId,
SenderId = sendParams.FromUserId,
RecipientId = sendParams.RecipientId,
RecipientType = sendParams.RecipientType,
EncryptedContent = sendParams.EncryptContent,
SentAt = sendParams.SendAt,
IsEdited = false,
ReplyToMessageId = sendParams.ReplyToMessageId,
MediaAttachments = sendParams.Media?.Select(m => new MediaAttachments
{
Id = Guid.NewGuid(),
MessageId = messageId,
MediaFileId = m.MediaId
}).ToList() ?? []
};
await _dbContext.Messages.AddAsync(message);
await _dbContext.SaveChangesAsync();
_logger.LogInformation("Message {MessageId} sent successfully.", messageId);
return new SendMessageResult(true, null, message);
}
private async Task<(bool Success, string Error)> ValidateUserRecipientAsync(Guid chatId)
{
var chatExists = await _dbContext.PrivateChats.AnyAsync(c => c.Id == chatId);
return chatExists ? (true, null) : (false, $"Private chat {chatId} not found.");
}
private async Task<(bool Success, string Error)> ValidateGroupRecipientAsync(Guid userId, Guid groupId)
{
var groupExists = await _dbContext.ChatGroups.AnyAsync(g => g.Id == groupId);
if (!groupExists) return (false, $"Group {groupId} not found.");
var isMember = await _dbContext.GroupMemberships.AnyAsync(gm => gm.UserId == userId && gm.GroupId == groupId);
if (!isMember) return (false, "Sender is not a member of the group.");
return (true, null);
}
}
@@ -0,0 +1,107 @@
using Govor.Application.Interfaces;
using Govor.Domain.Models.Messages;
using Govor.Domain;
using Microsoft.EntityFrameworkCore;
namespace Govor.Application.Messages;
public class MessagesLoader : IMessagesLoader
{
private readonly GovorDbContext _dbContext;
public MessagesLoader(GovorDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<List<Message>> LoadMessagesInUserChat(
Guid privateChatId,
Guid currentUser,
Guid? startMessageId,
int before = 20,
int after = 2)
{
if (privateChatId == Guid.Empty)
throw new ArgumentException("PrivateChatId id cannot be empty", nameof(privateChatId));
var chatExists = await _dbContext.PrivateChats.AnyAsync(c => c.Id == privateChatId);
if (!chatExists)
return [];
var query = _dbContext.Messages
.AsNoTracking()
.Include(m => m.MediaAttachments)
.ThenInclude(m => m.MediaFile)
.Where(m => m.RecipientType == RecipientType.User && m.RecipientId == privateChatId);
return await FetchPaginatedMessagesAsync(query, startMessageId, before, after);
}
public async Task<List<Message>> LoadMessagesInChatGroup(
Guid chatId,
Guid currentUser,
Guid? startMessageId,
int before = 20,
int after = 2)
{
if (chatId == Guid.Empty)
throw new ArgumentException("Chat id cannot be empty", nameof(chatId));
var isMember = await _dbContext.GroupMemberships
.AnyAsync(gm => gm.UserId == currentUser && gm.GroupId == chatId);
if (!isMember)
return [];
var query = _dbContext.Messages
.AsNoTracking()
.Include(m => m.MediaAttachments)
.ThenInclude(m => m.MediaFile)
.AsSplitQuery()
.Where(m => m.RecipientType == RecipientType.Group && m.RecipientId == chatId);
return await FetchPaginatedMessagesAsync(query, startMessageId, before, after);
}
private static async Task<List<Message>> FetchPaginatedMessagesAsync(
IQueryable<Message> baseQuery,
Guid? startMessageId,
int before,
int after)
{
if (startMessageId is null)
{
return await baseQuery
.OrderByDescending(m => m.SentAt)
.Take(before)
.OrderBy(m => m.SentAt)
.ToListAsync();
}
var startMessage = await baseQuery.FirstOrDefaultAsync(m => m.Id == startMessageId.Value);
if (startMessage == null)
return [];
var beforeMessages = await baseQuery
.Where(m => m.SentAt < startMessage.SentAt)
.OrderByDescending(m => m.SentAt)
.Take(before)
.ToListAsync();
var afterMessages = await baseQuery
.Where(m => m.SentAt > startMessage.SentAt)
.OrderBy(m => m.SentAt)
.Take(after)
.ToListAsync();
beforeMessages.Reverse();
var result = new List<Message>(beforeMessages.Count + 1 + afterMessages.Count);
result.AddRange(beforeMessages);
result.Add(startMessage);
result.AddRange(afterMessages);
return result;
}
}
@@ -0,0 +1,5 @@
namespace Govor.Application.Messages.Parameters;
public record DeleteMessage(
Guid DeleterId,
Guid MessageId);
@@ -0,0 +1,6 @@
using Govor.Domain.Models.Messages;
namespace Govor.Application.Messages.Parameters;
public record DeleteMessageResult(bool IsSuccess, Exception? Exception, Message? OriginalMessage)
: Result(IsSuccess, Exception, OriginalMessage?.Id ?? Guid.Empty);
@@ -1,4 +1,4 @@
namespace Govor.Application.Interfaces.Messages.Parameters;
namespace Govor.Application.Messages.Parameters;
public record EditMessage(
Guid EditorId,
@@ -0,0 +1,9 @@
using Govor.Domain.Models.Messages;
namespace Govor.Application.Messages.Parameters;
public record EditMessageResult(bool IsSuccess, Exception? Exception, Message? OriginalMessage)
: Result(IsSuccess, Exception, OriginalMessage?.Id ?? Guid.Empty)
{
}
@@ -0,0 +1,3 @@
namespace Govor.Application.Messages.Parameters;
public record Result(bool IsSuccess, Exception Exception, Guid messageId);
@@ -0,0 +1,3 @@
namespace Govor.Application.Messages.Parameters;
public record SendMedia(Guid MediaId, string EncryptedKey);
@@ -1,6 +1,6 @@
using Govor.Core.Models.Messages;
using Govor.Domain.Models.Messages;
namespace Govor.Application.Interfaces.Messages.Parameters;
namespace Govor.Application.Messages.Parameters;
public record SendMessage(
string EncryptContent,
@@ -0,0 +1,6 @@
using Govor.Domain.Models.Messages;
namespace Govor.Application.Messages.Parameters;
public record SendMessageResult(bool IsSuccess, Exception? Exception, Message Message)
: Result(IsSuccess, Exception, Message?.Id ?? Guid.Empty);
@@ -1,4 +1,4 @@
namespace Govor.Application.Interfaces;
namespace Govor.Application.PingHandler;
public interface IPingHandlerService
{
@@ -1,9 +1,8 @@
using Govor.Application.Interfaces;
using Govor.Data;
using Govor.Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
namespace Govor.Application.Services;
namespace Govor.Application.PingHandler;
public class PingHandlerService : IPingHandlerService
{
@@ -1,6 +1,6 @@
using Govor.Core.Models;
using Govor.Domain.Models;
namespace Govor.Application.Interfaces;
namespace Govor.Application.PrivateUserChats;
public interface IPrivateChatGroupManager
{
@@ -1,6 +1,6 @@
using Govor.Core.Models;
using Govor.Domain.Models;
namespace Govor.Application.Interfaces;
namespace Govor.Application.PrivateUserChats;
public interface IUserPrivateChatsCreator
{
@@ -0,0 +1,11 @@
using Govor.Domain.Common;
using Govor.Domain.Models;
namespace Govor.Application.PrivateUserChats;
public interface IUserPrivateChatsGetterService
{
Task<List<PrivateChat>> GetUserChatsAsync(Guid userId);
Task<Result<PrivateChat>> GetPrivateChatAsync(Guid chatId);
Task<bool> ExistChatAsync(Guid userIdA, Guid userIdB);
}
@@ -1,46 +1,52 @@
using Govor.Application.Interfaces;
using Govor.Core.Models;
using Govor.Core.Repositories.PrivateChats;
using Govor.Domain;
using Govor.Domain.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Govor.Application.Services;
namespace Govor.Application.PrivateUserChats;
public class UserPrivateChatsCreator : IUserPrivateChatsCreator
{
private readonly IPrivateChatsRepository _privateChats;
private readonly GovorDbContext _context;
private readonly IPrivateChatGroupManager _privateChatGroupManager;
private readonly ILogger<UserPrivateChatsCreator> _logger;
public UserPrivateChatsCreator(
IPrivateChatsRepository privateChats,
GovorDbContext context,
IPrivateChatGroupManager privateChatGroupManager,
ILogger<UserPrivateChatsCreator> logger)
{
_privateChats = privateChats;
_context = context;
_privateChatGroupManager = privateChatGroupManager;
_logger = logger;
}
public async Task<PrivateChat> CreateAsync(Guid userIdA, Guid userIdB)
{
if (!_privateChats.Exist(userIdA, userIdB))
var existingChat = await _context.PrivateChats
.FirstOrDefaultAsync(c => (c.UserAId == userIdA && c.UserBId == userIdB) ||
(c.UserAId == userIdB && c.UserBId == userIdA));
if (existingChat is null)
{
var recipientId = Guid.NewGuid();
var privateChat = new PrivateChat()
var privateChat = new PrivateChat
{
Id = recipientId,
UserAId = userIdA,
UserBId = userIdB
};
await _privateChats.AddAsync(privateChat);
await _privateChatGroupManager.AddUsersToPrivateChatGroupAsync(privateChat); // Notifying
await _context.PrivateChats.AddAsync(privateChat);
await _context.SaveChangesAsync();
_logger.LogInformation($"User for {userIdA} and {userIdB} was created private chat with Id: {recipientId}");
await _privateChatGroupManager.AddUsersToPrivateChatGroupAsync(privateChat);
_logger.LogInformation($"Private chat created with Id: {recipientId} for users {userIdA} and {userIdB}");
return privateChat;
}
_logger.LogInformation($"Private chat already exists for {userIdA} and {userIdB}; Returning already created chat...");
return await _privateChats.GetByMembersAsync(userIdA, userIdB);
_logger.LogInformation($"Private chat already exists for {userIdA} and {userIdB}; Returning existing chat...");
return existingChat;
}
}
@@ -0,0 +1,46 @@
using Govor.Domain;
using Govor.Domain.Common;
using Govor.Domain.Models;
using Microsoft.EntityFrameworkCore;
namespace Govor.Application.PrivateUserChats;
public class UserPrivateChatsGetter : IUserPrivateChatsGetterService
{
private readonly GovorDbContext _context;
public UserPrivateChatsGetter(GovorDbContext context)
{
_context = context;
}
public async Task<List<PrivateChat>> GetUserChatsAsync(Guid userId)
{
return await _context.PrivateChats
.AsNoTracking()
.Where(p => p.UserAId == userId || p.UserBId == userId)
.ToListAsync();
}
public async Task<Result<PrivateChat>> GetPrivateChatAsync(Guid chatId)
{
var res = await _context.PrivateChats.AsNoTracking()
.FirstOrDefaultAsync(p => p.Id == chatId);
if (res == null)
return Result<PrivateChat>.Failure(new Error(nameof(InvalidOperationException),
"PrivateChat not found.")
);
return res;
}
public async Task<bool> ExistChatAsync(Guid userIdA, Guid userIdB)
{
return await _context.PrivateChats
.AsNoTracking()
.AnyAsync(p => (p.UserAId == userIdA && p.UserBId == userIdB) ||
(p.UserBId == userIdA && p.UserAId == userIdB)
);
}
}
@@ -0,0 +1,10 @@
using Govor.Domain.Common;
namespace Govor.Application.Profiles;
public interface IProfileService
{
public Task<Result<UserProfile>> GetUserProfileAsync(Guid userId);
public Task<Result> SetDescription(string description, Guid userId);
public Task<Result> SetNewIcon(Guid userId, Guid iconId);
}
@@ -0,0 +1,78 @@
using Govor.Domain;
using Govor.Domain.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Govor.Application.Profiles;
public class ProfileService : IProfileService
{
private readonly ILogger<ProfileService> _logger;
private readonly GovorDbContext _context;
public ProfileService(GovorDbContext context, ILogger<ProfileService> logger)
{
_context = context;
_logger = logger;
}
public async Task<Result<UserProfile>> GetUserProfileAsync(Guid userId)
{
_logger.LogInformation("Getting user {UserId} profile", userId);
var profile = await _context.Users
.AsNoTracking()
.Where(u => u.Id == userId)
.Select(user => new UserProfile
{
Id = user.Id,
Username = user.Username,
Description = user.Description,
IconId = user.IconId
})
.FirstOrDefaultAsync();
if (profile is null)
{
return Result<UserProfile>.Failure(CreateNotFoundError(userId));
}
return profile;
}
public async Task<Result> SetDescription(string description, Guid userId)
{
_logger.LogInformation("Updating description for user {UserId}", userId);
var updatedRows = await _context.Users
.Where(u => u.Id == userId)
.ExecuteUpdateAsync(setters => setters.SetProperty(u => u.Description, description));
if (updatedRows == 0)
{
return Result.Failure(CreateNotFoundError(userId));
}
return Result.Success();
}
public async Task<Result> SetNewIcon(Guid userId, Guid iconId)
{
_logger.LogInformation("Updating icon for user {UserId}", userId);
var updatedRows = await _context.Users
.Where(u => u.Id == userId)
.ExecuteUpdateAsync(setters => setters.SetProperty(u => u.IconId, iconId));
if (updatedRows == 0)
{
return Result.Failure(CreateNotFoundError(userId));
}
return Result.Success();
}
private static Error CreateNotFoundError(Guid userId) =>
new("Profile.UserNotFound", $"User with ID {userId} was not found.");
}
@@ -0,0 +1,12 @@
using Govor.Domain.Common;
namespace Govor.Application.PushNotifications;
public interface IPushNotificationService
{
Task<Result> SendToUserAsync(Guid userId, string title, string body, string channelId, string tag = "", Dictionary<string, string>? data = null);
Task<Result> SendToUsersAsync(IEnumerable<Guid> userIds, string title, string body, string channelId, string tag = "", Dictionary<string, string>? data = null);
Task<Result> SendToSessionAsync(Guid sessionId, string title, string body, string channelId, string tag = "", Dictionary<string, string>? data = null);
}
@@ -0,0 +1,14 @@
using Govor.Domain.Common;
namespace Govor.Application.PushNotifications;
public interface IPushTokenService
{
Task<Result> DeactivateTokenBySessionAsync(Guid sessionId);
Task<Result> DeactivateAllTokensByUserIdAsync(Guid userId);
Task<Result<List<string>>> GetStringsActiveTokensAsync(Guid userId);
Task<Result<List<string>>> GetUsersStringsActiveTokensAsync(IEnumerable<Guid> userIds);
Task<Result<string?>> GetActiveTokenBySessionAsync(Guid sessionId);
Task<Result> RemoveTokensAsync(IEnumerable<string> tokens);
Task<Result> AddOrUpdateTokenAsync(Guid userId, Guid sessionId, string token, string platform);
}

Some files were not shown because too many files have changed in this diff Show More