mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-16 20:56:03 +00:00
Stable server
was added removing messages many fixes bugs and moving to result pattern from throwing exceptions
This commit is contained in:
@@ -31,7 +31,6 @@ public class AuthService : IAccountService
|
||||
|
||||
public async Task<Result<User, Error>> RegistrationAsync(string name, string password, Invitation invitation)
|
||||
{
|
||||
|
||||
var validationResult = _usernameValidator.Validate(name);
|
||||
if (validationResult.IsFailure)
|
||||
{
|
||||
@@ -63,8 +62,8 @@ public class AuthService : IAccountService
|
||||
await _context.Users.AddAsync(user);
|
||||
|
||||
await SetRoleAsync(user, invitation);
|
||||
|
||||
// TODO: inv.participantCount -= 1; db.save();
|
||||
|
||||
invitation.Participants += 1;
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using Govor.Application.Exceptions.InvitesService;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models;
|
||||
@@ -24,7 +23,7 @@ public class InvitesService : IInvitesService
|
||||
|
||||
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)
|
||||
return "User";
|
||||
@@ -41,7 +40,7 @@ public class InvitesService : IInvitesService
|
||||
if (invite == null)
|
||||
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;
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
@@ -26,7 +26,8 @@ public class JwtService : IJwtService
|
||||
{
|
||||
new Claim("userId", user.Id.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(
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.Application.Medias;
|
||||
|
||||
public interface IMediaService
|
||||
{
|
||||
public Task<MediaUploadResult> UploadMediaAsync(Media file);
|
||||
public Task DeleteMediaAsync(Guid fileId);
|
||||
public Task<Media> GetMediaByUrlAsync(string url);
|
||||
public Task<Media> GetMediaByIdAsync(Guid mediaId);
|
||||
public Task<Result<MediaUploadResult, Error>> UploadMediaAsync(Media file);
|
||||
public Task<Result<Unit, Error>> DeleteMediaAsync(Guid fileId);
|
||||
public Task<Result<Media, Error>> GetMediaByUrlAsync(string url);
|
||||
public Task<Result<Media, Error>> GetMediaByIdAsync(Guid mediaId);
|
||||
public Task<bool> HasMediaAsync(Guid mediaId);
|
||||
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,
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
using Govor.Application.Storage;
|
||||
using Govor.Domain.Models;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.Application.Medias;
|
||||
|
||||
@@ -19,7 +21,7 @@ public class MediaService : IMediaService
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<MediaUploadResult> UploadMediaAsync(Media file)
|
||||
public async Task<Result<MediaUploadResult, Error>> UploadMediaAsync(Media file)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -47,37 +49,56 @@ public class MediaService : IMediaService
|
||||
}
|
||||
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
|
||||
.FirstOrDefaultAsync(x => x.Id == mediaId)
|
||||
?? throw new KeyNotFoundException($"No media found by given id {mediaId}");
|
||||
|
||||
.FirstOrDefaultAsync(x => x.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);
|
||||
|
||||
_dbContext.MediaFiles.Remove(mediaFile);
|
||||
|
||||
await _dbContext.SaveChangesAsync();
|
||||
|
||||
return new Unit();
|
||||
}
|
||||
|
||||
public Task<Media> GetMediaByUrlAsync(string url)
|
||||
public Task<Result<Media, Error>> GetMediaByUrlAsync(string url)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<Media> GetMediaByIdAsync(Guid mediaId)
|
||||
public async Task<Result<Media, Error>> GetMediaByIdAsync(Guid mediaId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var mediaFile = await _dbContext.MediaFiles
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(x => x.Id == mediaId)
|
||||
?? throw new KeyNotFoundException($"No media found by given id {mediaId}");
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(x => x.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);
|
||||
|
||||
@@ -86,7 +107,8 @@ public class MediaService : IMediaService
|
||||
await dataStream.CopyToAsync(memoryStream);
|
||||
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
|
||||
return new Media(
|
||||
@@ -103,33 +125,43 @@ public class MediaService : IMediaService
|
||||
}
|
||||
catch (FileNotFoundException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Media file not found on storage.");
|
||||
throw;
|
||||
_logger.LogWarning(ex, "Media file ({0}) not found on storage.", mediaId);
|
||||
return Result<Media, Error>.Failure(Error.ServerError("File.GetMediaById", $"Media file not found on storage!"));
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> HasMediaAsync(Guid mediaId)
|
||||
{
|
||||
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)
|
||||
{
|
||||
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
|
||||
.FirstOrDefaultAsync(x => x.Id == mediaId)
|
||||
?? throw new KeyNotFoundException($"No media found by given id {mediaId}");
|
||||
.FirstOrDefaultAsync(x => x.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)
|
||||
{
|
||||
_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;
|
||||
@@ -139,5 +171,7 @@ public class MediaService : IMediaService
|
||||
await _dbContext.SaveChangesAsync();
|
||||
|
||||
_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.Domain.Common;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.Application.Messages;
|
||||
|
||||
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 SmartRes;
|
||||
|
||||
namespace Govor.Application.Messages;
|
||||
|
||||
public interface IMessagesLoader
|
||||
{
|
||||
Task<List<Message>> 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>> LoadMessagesInUserChat(Guid privateChatId,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.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.Application.Messages;
|
||||
|
||||
@@ -17,8 +21,67 @@ public class MessageRemovingService : IMessageRemovingService
|
||||
_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;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
using Govor.Application.Interfaces;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.Application.Messages;
|
||||
|
||||
@@ -14,7 +16,7 @@ public class MessagesLoader : IMessagesLoader
|
||||
_dbContext = dbContext;
|
||||
}
|
||||
|
||||
public async Task<List<Message>> LoadMessagesInUserChat(
|
||||
public async Task<Result<List<Message>,Error>> LoadMessagesInUserChat(
|
||||
Guid privateChatId,
|
||||
Guid currentUser,
|
||||
Guid? startMessageId,
|
||||
@@ -22,11 +24,11 @@ public class MessagesLoader : IMessagesLoader
|
||||
int after = 2)
|
||||
{
|
||||
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);
|
||||
if (!chatExists)
|
||||
return [];
|
||||
return new List<Message>(0);
|
||||
|
||||
var query = _dbContext.Messages
|
||||
.AsNoTracking()
|
||||
@@ -37,7 +39,7 @@ public class MessagesLoader : IMessagesLoader
|
||||
return await FetchPaginatedMessagesAsync(query, startMessageId, before, after);
|
||||
}
|
||||
|
||||
public async Task<List<Message>> LoadMessagesInChatGroup(
|
||||
public async Task<Result<List<Message>,Error>> LoadMessagesInChatGroup(
|
||||
Guid chatId,
|
||||
Guid currentUser,
|
||||
Guid? startMessageId,
|
||||
@@ -45,13 +47,13 @@ public class MessagesLoader : IMessagesLoader
|
||||
int after = 2)
|
||||
{
|
||||
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
|
||||
.AnyAsync(gm => gm.UserId == currentUser && gm.GroupId == chatId);
|
||||
|
||||
if (!isMember)
|
||||
return [];
|
||||
return new List<Message>(0);
|
||||
|
||||
var query = _dbContext.Messages
|
||||
.AsNoTracking()
|
||||
|
||||
@@ -2,4 +2,5 @@ namespace Govor.Application.Messages.Parameters;
|
||||
|
||||
public record DeleteMessage(
|
||||
Guid DeleterId,
|
||||
Guid MessageId);
|
||||
Guid MessageId,
|
||||
bool ForceRemove = false);
|
||||
|
||||
@@ -119,7 +119,9 @@ public class PushTokenService : IPushTokenService
|
||||
await _context.UserPushTokens
|
||||
.Where(t => tokens.Contains(t.Token))
|
||||
.ExecuteDeleteAsync();
|
||||
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -42,7 +42,6 @@ public class UserSessionRefresher : IUserSessionRefresher
|
||||
try
|
||||
{
|
||||
var session = await _context.UserSessions
|
||||
.AsNoTracking()
|
||||
.Include(userSession => userSession.User)
|
||||
.FirstOrDefaultAsync(s => s.RefreshTokenHash == hashedToken);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user